Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At what point exactly is an object available for garbage collection?

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?

like image 858
Chris Knight Avatar asked Jan 20 '12 11:01

Chris Knight


People also ask

When an object is eligible for garbage collection?

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.

At what point is only a single object eligible for GC?

Only objects that have no reference variables referring to them can be eligible for GC.

What are the three possible conditions for a garbage collection?

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 exactly JVM runs garbage collector?

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.


1 Answers

"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();
}
like image 114
Farmor Avatar answered Oct 19 '22 23:10

Farmor