Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces


Garbage Collection of unused objects

Other object-oriented languages require that you keep track of all the objects you create and that you destroy them when they are no longer needed. Writing code to manage memory in this way is tedious and often error-prone. Java saves you from this by allowing you to create as many objects as you want (limited of course to whatever your system can handle) but never having to destroy them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection.

The Java runtime environment supports a garbage collector that periodically frees the memory used by objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java's dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (that is, not referenced) are known to be garbage and are collected.

The garbage collector runs in a low priority both synchronously and asynchronously depending on the situation and the system on which Java is running.

The garbage collector runs synchronously when the system runs out of memory, or in response to a request from a Java program. Your Java program can ask the garbage collector to run at any time by calling System.gc(). Note that the garbage collector requires about 20 milliseconds to complete its task so, your program should only run the garbage collector when there will be no performance impact and the program anticipates an idle period long enough for the garbage collector to finish its job.
Note: Asking the garbage collection to run does not guarantee that your objects will be garbage collected.

The Java garbage collector runs asynchronously when the system is idle on systems that allow the Java runtime to note when a thread has begun and to interrupt another thread (such as Windows 95). As soon as another thread becomes active, the garbage collector is asked to get to a consistent state and then terminate.


Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces