|
|
|
|||
|
Cleaning Up Unused ObjectsMany other object-oriented languages require that you keep track of all of the objects you create and that you explicitly destroy them when they are no longer needed. This technique of managing memory is tedious and often error-prone. Java allows you to create as many objects as you want (limited, of course, by what your system can handle), and you never have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection. The next section discusses this in more detail.An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are naturally dropped when the variable goes out of scope. Or you can explicitly drop an object reference by setting the variable to null. The Garbage CollectorThe Java platform has 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. A mark-sweep garbage collector scans dynamic memory areas for objects and marks those that are referenced. After all possible paths to objects are investigated, unmarked objects (unreferenced objects) are known to be garbage and are collected. (A more complete description of Java's garbage collection algorithm might be "a compacting, mark-sweep collector with some conservative scanning.") FinalizationBefore an object gets garbage-collected, the garbage collector gives the object an opportunity to clean up after itself through a call to the object's | |||
|