Java – when exactly are objects available for garbage collection?

I'm competing with my application for memory problems and trying to get my head close to garbage collection If I have the following code:

public void someMethod() {
   MyObject myObject = new MyObject();
   myObject.doSomething();  //last use of myObject in this scope
   doAnotherThing();
   andEvenMoreThings();
}

So my question is, MyObject can be in MyObject Dosomething () can be used for garbage collection after the last use of this object or when somemethod () after a range is completed? That is, is garbage collection smart enough to see that although local variables are still in scope, the rest of the code will not be used?

Solution

"Out of range"

public void someMethod() {
   MyObject myObject = new MyObject();
   myObject.doSomething();  //last use of myObject in this scope
   myObject = null; //Now available for gc
   doAnotherThing();
   andEvenMoreThings();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>