| 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

> > 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 acheived 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.

> > 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. The garbage collector requires about 20 milliseconds to complete its task so, your program should only run the garbage collector when doing so will have no performance impact on your program--that is, that your program anticipates that the garbage collector will have enough time to finish its job.

> > For general information about Java's garbage collection scheme see Garbage Collection of Unused Objects.

| Using System Resources