Java Reference
In-Depth Information
The infinite while loop within main() instantiates objects of type Sim-
pleObject (whose definition follows) that are immediately available for
garbage collection.
■■
public class SimpleObject
{
private String name;
public SimpleObject(String n)
{
System.out.println(“Instantiating “ + n);
name = n;
}
public void finalize()
{
System.out.println(“*** “ + name + “ is getting garbage
collected ***”);
}
}
The SimpleObject class overrides the finalize() method and prints out a mes-
sage. (Recall that the finalize() method is invoked by the garbage collector just
before an object's memory is freed.) Figure 15.6 shows a sample output of the
TimerDemo program. Notice that even when the main() thread is sleeping, the
objects are not garbage collected until the GCTask is scheduled by the timer,
which invokes the System.gc() method. This behavior will vary, depending on
the JVM.
Figure 15.6
Sample output of the TimerDemo program.
Search WWH ::




Custom Search