Since garbage collection runs sporadically in the background,
It's not easy to demonstrate. However, one way to do it is with
using the finalize() method. Remember 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 collector waits until it can perform its collection efficiently, usually when there are many unused objects.
So, to demonstrate garbage collection via the finalize() method, we have to
create and destroy various objects – and that's exactly what we'll do in this project.
1 Create a new file called Finalize.java.
2 Create the FDemo class:
The constructor sets the instance variable x to a known value
of. In this example, x is used as an object ID. The
method
finalize() displays the value of x when an object is recycled. Of special interest is generator( ). This method creates and then immediately discards an FDemo object. You will see how it is used in the next step.
3 Create the Finalize class:
This class creates an initial FDemo object called ob. Then using
ob, it creates 100,000 objects by calling generator( ) in ob. As a result, 100,000 objects are created and discarded. At various points in the middle of
process, garbage collection will occur. Many factors will influence exactly how often or when, such as the initial amount of free memory and the operating system. However, at some point you will start to see messages generated by finalize( ). If you can't see them, try increasing the number of objects being generated by increasing the count in the for loop.
The above is the detailed content of Try This: Garbage Collection and Termination. For more information, please follow other related articles on the PHP Chinese website!