Garbage Collection
The garbage collection routine is automatically invoked when the heap fills up.
The garbage collector identifies objects that are no longer referenced by the
application and removes them to free up memory. The garbage collector can
be manually invoked through the System.gc() method, but there is no
guarantee when the process will start.
The algorithm used for garbage collection is called mark and sweep. In the first
step, objects that are referenced in memory are identified and marked. In the
second step,
unmarked objects are deleted, freeing up chunks of memory.
The remaining memory can then be compacted into contiguous blocks
in a process similar to defragmenting a hard drive.
Strong References
A strong reference is a typical reference such as assigning
an object to a variable
or putting an object in an array. A strong reference to an object guarantees that
the object will remain on the heap. An object is eligible for garbage collection
if it cannot be accessed through any chain of strong references.
Strong references can accumulate over time. When
an application uses more
memory than the allocated heap space, the result is an OutOfMemoryError.
When an application fills up the heap with unintentional references,
the result
is a memory leak. OutOfMemoryErrors can be fixed by allocating a larger
heap size through JVM arguments, but a memory
leak could eventually fill
up a heap of any size.