I'm battling out of memory issues with my application and am trying to get my head around 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, will myObject
be available for garbage collection after myObject.doSomething()
which is the last use of this object, or after the completion of someMethod()
where it comes out of scope? I.e. is the garbage collection smart enough to see that though a local variable is still in scope, it won't be used by the rest of the code?
An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null.
Only objects that have no reference variables referring to them can be eligible for GC.
Conditions for a garbage collectionThe system has low physical memory. The memory size is detected by either the low memory notification from the operating system or low memory as indicated by the host. The memory that's used by allocated objects on the managed heap surpasses an acceptable threshold.
When the JVM doesn't have necessary memory space to run, the garbage collector will run and delete unnecessary objects to free up memory. Unnecessary objects are the objects which have no other references (address) pointing to them.
"Where it comes out of scope"
public void someMethod() {
MyObject myObject = new MyObject();
myObject.doSomething(); //last use of myObject in this scope
myObject = null; //Now available for gc
doAnotherThing();
andEvenMoreThings();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With