Java Reference
In-Depth Information
Because garbage collection runs sporadically in the background, it is not trivial to demon-
strate it. However, one way it can be done is through the use of the finalize( ) method.
Recall that finalize( ) is called when an object is about to be recycled. As explained, objects
are not necessarily recycled as soon as they are no longer needed. Instead, the garbage col-
lector waits until it can perform its collection efficiently, usually when there are many un-
used objects. Thus, to demonstrate garbage collection via the finalize( ) method, you often
need to create and destroy a large number of objects—and this is precisely what you will
do in this project.
1. Create a new file called Finalize.java.
2. Create the FDemo class shown here:
The constructor sets the instance variable x to a known value. In this example, x is
used as an object ID. The finalize( ) method displays the value of x when an object is
recycled. Of special interest is generator( ) . This method creates and then promptly
discards an FDemo object. You will see how this is used in the next step.
3. Create the Finalize class, shown here:
Search WWH ::




Custom Search