Thursday, May 15, 2008

Java Garbage Collection

A garbage collector is responsible for
  • allocating memory
  • ensuring that any referenced objects remain in memory, and
  • recovering memory used by objects that are no longer reachable from references in executing code.

Space is allocated by a large space called heap. The JVM's heap stores all objects created by an executing Java program. Objects are created by Java's "new" operator, and memory for new objects is allocated on the heap at run time.

In addition to freeing unreferenced objects, a garbage collector may also combat heap fragmentation. Heap fragmentation occurs through the course of normal program execution. New objects are allocated, and unreferenced objects are freed such that free blocks of heap memory are left in between blocks occupied by live objects

Code for System.gc is as follows

public static void gc() {
Runtime.getRuntime().gc();
}


System.gc() is just more convinient to call/use

freeMem = Runtime.getRuntime().freeMemory();
System.gc();
System.out.println("free memory after running gc(): " + freeMem);


Interesting links
http://chaoticjava.com/posts/garbage-collection-the-comic-panel/
http://chaoticjava.com/posts/how-does-garbage-collection-work/
http://chaoticjava.com/posts/parallel-and-concurrent-garbage-collectors/
http://chaoticjava.com/posts/gc-tips-and-memory-leaks/

No comments: