Garbage Collection Java tries its best to manage your application's use of memory as it executes. Memory is a precious, limited commodity in most computer systems. Every time your code creates an object, Java must find memory space in which to store the object. If Java did nothing to manage memory, objects put in memory would stay there forever, and you would very quickly use up all available memory. Java uses a technique known as garbage collection to manage your application's memory use. The Java VM tracks your use of all objects; from time to time it runs something known as a garbage collector in the background. The garbage collector reclaims objects that it knows you no longer need. You no longer need an object when no other objects refer to that object. Suppose you create an object within a method and assign it to a local variable (but not to anything else). When the VM completes execution of the method, the object remains in memory, but nothing points to itthe local variable reference is only valid for the scope of the method. At this point, the object is eligible for garbage collection and should disappear the next time the garbage collector runs (if everyou can never guarantee that the garbage collector will run). If an instance variable refers to an object, you can give the object up for potential garbage collection by setting the value of the instance variable to null. Or you can wait until the object containing the instance variable is no longer referred to. Once nothing refers to an object, any objects it in turn refers to are also eligible for garbage collection. If you store an object in a standard collection, such as an ArrayList, the collection holds a reference to the object. The object cannot be garbage collected as long the collection contains it. |