Java Reference
In-Depth Information
resurrecting itself by placing its reference in a reachable reference variable. Once it is reachable through an already
reachable reference variable, it is back to life. The garbage collector marks an object using the object's header bits as
finalized, after it calls the object's finalize() method. If an already finalized object becomes unreachable the next
time during garbage collection, the garbage collector does not call the object's finalize() method again.
The resurrection of an object is possible because the garbage collector does not reclaim an object's memory just
after calling its finalize() method. After calling the finalize() method, it just marks the object as finalized. In the
next phase of the garbage collection, it determines again if the object is reachable. If the object is unreachable and
finalized, only then will it reclaim the object's memory. If an object is reachable and finalized, it does not reclaim
object's memory; this is a typical case of resurrection.
Resurrecting an object in its finalize() method is not a good programming practice. One simple reason is that
if you have coded the finalize() method, you expect it to be executed every time an object dies. If you resurrect the
object in its finalize() method, the garbage collector will not call its finalize() method again when it becomes
unreachable a second time. After resurrection, you might have obtained some resources that you expect to be
released in the finalize() method. This will leave subtle bugs in your program. It is also hard for other programmers
to understand your program flow if your program resurrects objects in their finalize() methods. Listing 11-3
demonstrates how an object can resurrect using its finalize() method.
Listing 11-3. Object Resurrection
// Resurrect.java
package com.jdojo.gc;
public class Resurrect {
// Declare a static variable of the Resurrect type
private static Resurrect res = null;
// Declare an instance variable that stores the name of the object
private String name = "";
public Resurrect(String name) {
this.name = name;
}
public static void main(String[] args) {
// We will create objects of the Resurrect class and will not store
// their references, so they are eligible for garbage collection immediately.
for(int count = 1; count <= 1000; count++) {
new Resurrect("Object #" + count);
// For every 100 objects created invoke garbage collection
if (count % 100 == 0) {
System.gc();
System.runFinalization();
}
}
}
public void sayHello() {
System.out.println("Hello from " + name);
}
Search WWH ::




Custom Search