Java Reference
In-Depth Information
public static void resurrectIt(Resurrect r) {
// Set the reference r to static variable res, which makes it reachable
// as long as res is reachable.
res = r ;
// Call a method to show that we really got the object back
res.sayHello();
}
public void finalize() {
System.out.println("Inside finalize(): " + name);
// Resurrect this object
Resurrect.resurrectIt(this);
}
}
(Partial output is shown below)
...
Inside finalize(): Object #14
Hello from Object #14
...
Inside finalize(): Object #997
Hello from Object #997
The Resurrect class creates 1,000 objects in the main() method. It does not store references of those new objects,
so they become garbage as soon as they are created. After creating 100 new objects, it invokes the garbage collector
using the System.gc() method. It also calls the System.runFinalization() method, so the finalizers are run for
the garbage objects. When the garbage collector calls the finalize() method for an object, that object passes its
reference to the resurrectIt() method. This method stores the dying object's reference in the static variable res ,
which is reachable. The method resurrectIt() also calls the sayHello() method on the resurrected object to show
which object was resurrected. Note that once another object resurrects itself you are overwriting the static res
variable with the recently resurrected object reference. The previously resurrected object becomes garbage again. The
garbage collector will reclaim the memory for the previously resurrected object without calling its finalize() method
again. You may get different output when you run the program.
State of an Object
The state of a Java object is defined based on two criteria:
Finalization status
Reachability
Based on the finalization status, an object can be in one of the following three states:
Unfinalized
Finalizable
Finalized
 
Search WWH ::




Custom Search