Garbage Collection

Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An object is considered "in use" if some part of your program still maintains a reference to that object. Unused objects, on the flip side, are no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

In a programming language like C, allocating and deallocating memory is a manual process. In Java, process of deallocating memory is handled automatically by the garbage collector.

Note, when considering the memory used by objects, which can contain references to other objects, which in turn can reference still other objects, and so on, with the distinct possibility of circular references among these -- identifying which objects are actually "orphans" with no references to them is an interesting problem in its own right, as the diagram below suggests.

It is good practice, if we know that a particular object will not be used again in the course of a program we have written, to set any references to that object to null so that garbage collection can happen and the memory that object was using can be freed.