The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Essential Java Classes
Lesson: Accessing System Resources

Forcing Finalization and Garbage Collection

The Java runtime system performs memory management tasks for you. When your program has finished using an object, that is, when there are no more references to an object, the object is finalized and is then garbage collected. These tasks happen asynchronously in the background. However, you can force object finalization and garbage collection using the appropriate method in the System class.

Finalizing Objects

Before an object is garbage collected, the Java runtime system gives the object a chance to clean up after itself. This step is known as finalization and is achieved through a call to the object's finalize method.

You can force object finalization to occur by calling System's runFinalization method.

System.runFinalization();
This method calls the finalize methods on all objects that are waiting to be garbage collected.

Running the Garbage Collector

You can ask the garbage collector to run at any time by calling System's gc method:
System.gc();
You might want to run the garbage collector to ensure that it runs at the best time for your program rather than when it's most convenient for the runtime system to run it. For example, your program may wish to run the garbage collector right before it enters a compute or memory intensive section of code or when it knows there will be some idle time.

Note that the garbage collector requires time to complete its task. The amount of time that gc requires to complete varies depending on certain factors: How big your heap is and how fast your processor is, for example. Your program should only run the garbage collector when doing so will have no performance impact on your program.

For general information about Java's garbage collection scheme, see Cleaning Up Unused Objects(in the Essential Java Classes trail).


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search