Previous | Next | Trail Map | Writing Java Programs | Using 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 (1.1notes)

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. The object should override the finalize method to perform any final cleanup tasks such as freeing system resources like files and sockets. For information about the finalize method, see Writing a finalize Method(in the Writing Java Programs trail).

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 Garbage Collection of Unused Objects(in the Writing Java Programs trail).


Previous | Next | Trail Map | Writing Java Programs | Using System Resources