Saturday, August 18, 2007

Garbage Collection

Takes care of freeing dynamically allocated memory that is no longer referenced. The JVM specification states that the heap of the JVM must be garbage collected but the actual implementation is vendor specific.

Advantages of Garbage Collection:
  • Increased productivity - developer doesn't need to worry about freeing allocated memory
  • Program Integrity - programmers are unable to crash the JVM by incorrectly freeing memory

Disadvantages of Garbage Collection:

  • Added Overhead - CPU activity required to keep track of references

Garbage collection is automatically performed but can be explicitly requested by invoking System.gc() or Runtime.gc().

Garbage collection algorithms must detect garbage objects and reclaim heap space. This is usually accomplished by defining a set of roots and determining reachability from the roots. All objects reside on the heap with local variables residing in the stack of its own thread of execution.

Two basic approaches to distiguishing live objects from garbage are reference counting and tracing.

  • Reference Counting - keeps a count for each object of the number of references to that object, but cannot detect cycles where two or more objects refer to each other even though they are unreachable and has the overhead of incrementing and decrementing the reference count
  • Tracing - trace out a graph of the references starting with root nodes and mark objects, any unmarked objects are subsequently garbage collected (mark and sweep)

JVM's implement different strategies to help combat heap fragmentation:

  • Compacting - live objects are moved over to free memory space toward one end of the heap causing the other end of the heap to become a contiguous free area
  • Copying - move all live objects to a new area placing them side by side and eliminating the free space seperating them in the old area

Java's Garbage-Collected Heap

No comments: