Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force garbage collection in Java?

People also ask

How do you force garbage collection to run?

GC. Collect() forces garbage collector to run.

Is it possible to force garbage collection in?

You really can't force Java GC. The Java garbage collection algos are non-deterministic, and while all of these methods can motivate the JVM to do GC, you can't actually force it.

Can you manually call the garbage collector?

You can call Garbage Collector explicitly, but JVM decides whether to process the call or not. Ideally, you should never write code dependent on call to garbage collector.


Your best option is to call System.gc() which simply is a hint to the garbage collector that you want it to do a collection. There is no way to force and immediate collection though as the garbage collector is non-deterministic.


The jlibs library has a good utility class for garbage collection. You can force garbage collection using a nifty little trick with WeakReference objects.

RuntimeUtil.gc() from the jlibs:

   /**
    * 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();
     }
   }

The best (if not only) way to force a GC would be to write a custom JVM. I believe the Garbage collectors are pluggable so you could probably just pick one of the available implementations and tweak it.

Note: This is NOT an easy answer.


Using the Java™ Virtual Machine Tool Interface (JVM TI), the function

jvmtiError ForceGarbageCollection(jvmtiEnv* env)

will "Force the VM to perform a garbage collection." The JVM TI is part of the JavaTM Platform Debugger Architecture (JPDA).