Thursday, July 5, 2007

Garbage Collection ( Part I )

Why Objects are called Reachable, Resurrectable, and Unreachable?

Prior to the release of Java 2 Platform, Standard Edition (J2SE) 1.2, an object could be in only one of three states

Reachable: An object is reachable if the garbage collector can trace a path from a root-set variable to that object. When the JVM creates an object, that object stays initially reachable as long as a program maintains at least one reference to the object. Assigning null to an object reference variable reduces the object's references by one. For example:

Employee e = new Employee (); Employee e2 = e; e = null;
In the above code fragment, the Employee object is initially reachable through e.
Then it is reachable through e2 as well as through e. After null assigns to e, the
Object is only reachable through e2.

Resurrectable: An object is resurrectable if it is currently unreachable through root-set variables, but has the potential to be made reachable through a garbage collector call to that object's overridden finalize () method. Because finalize ()'s code can make the object reachable, the garbage collector must retrace all paths from root-set variables in an attempt to locate the object after finalize () returns. If the garbage collector cannot find a path to the object, it makes the object unreachable. If a path does exist, the garbage collector makes the object reachable. If the object is made reachable, the garbage collector will not run it’s finalize () method a second time when no more references to that object exist. Instead, the garbage collector makes that object unreachable

Unreachable: An object is unreachable when no path from root-set variables to that object exists and when the garbage collector cannot call that object's finalize() method. The garbage collector is free to reclaim the object's memory from the heap.

1 comment:

The Stupid Programmer said...

Good details. Hope to see more on garbage collection.