Understanding Java Memory Management

The most important thing to remember about Java memory management is "nullify" your reference.

Only objects that are not referenced are to be garbage collected.

For example, objects in the following code is never get collected and your memory will be full just to do nothing.

List objs = new ArrayList();
for (int i = 0; i  < Integer.MAX_VALUE; i++) objs.add(new Object());

But if you don't reference those object ... you can loop as much as you like without memory problem.

List objs = new ArrayList();
for (int i = 0; i  < Integer.MAX_VALUE; i++) new Object();

So what ever you do, make sure you remove reference to object to no longer used (set reference to null or clear collection).

When the garbage collector will run is best left to JVM to decide. Well unless your program is about to start doing things that use a lot of memory and is speed critical so you may suggest JVM to run GC before going in as you may likely get the garbaged collected and extra memory to go on. Other wise, I personally see no reason to run System.gc().

Hope this helps.


Below is little summary I wrote back in the days (I stole it from some blog, but I can't remember where from - so no reference, sorry)

  1. There is no manual way of doing garbage collection in Java.
  2. Java Heap is divided into three generation for the sake of garbage collection. These are the young generation, tenured or old generation, and Perm area.
  3. New objects are created in the young generation and subsequently moved to the old generation.
  4. String pool is created in Perm area of Heap, Garbage collection can occur in perm space but depends on upon JVM to JVM.
  5. Minor garbage collection is used to move an object from Eden space to Survivor 1 and Survivor 2 space, and Major collection is used to move an object from young to tenured generation.
  6. Whenever Major garbage collection occurs application, threads stops during that period which will reduce application’s performance and throughput.
  7. There are few performance improvements has been applied in garbage collection in Java 6 and we usually use JRE 1.6.20 for running our application.
  8. JVM command line options -Xms and -Xmx is used to setup starting and max size for Java Heap. The ideal ratio of this parameter is either 1:1 or 1:1.5 based on my experience, for example, you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.

Command line options: -Xms:<min size> -Xmx:<max size>