Wednesday, June 20, 2012

Wait for JVM Garbage Collector

We all know the need to accasinally run the garbage collector.

The JVM by design does not allow you to force the garbage collector to run.

Using functions like System.gc(); or Runtime.getRuntime().gc(); only suggest to the JVM that you want to run the garbage collector.



I found a way on the internet not to force the grabage collector but to wait until the garbage collector runs.

The idea is to use the WeakReference object. This object holds a pointer to the object, but is not counted as a pointer by the garbage collector. You then release the actual pointer but continue to check the object via the WeakReference pointer until it is null.



/**
    * This method guarantees that garbage collection is
    * done unlike <code>{@link System#gc()}</code>
    */
   public static void gc() {
     Object obj = new Object();
     WeakReference ref = new WeakReference<Object>(obj);
     obj = null;
     while(ref.get() != null) {
       System.gc();
     }
   }
 
  For more information please see: http://jlibs.googlecode.com/svn/trunk/core/src/main/java/jlibs/core/lang/RuntimeUtil.java