Java gc force

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) {
  For more information please see:



Backend/Data Architect

Backend Group
Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at