How to Force Garbage Collection

3 years ago by in How To, Utilities Tagged:

The System.gc() does not guarantee that the garbage collection has executed and that the memory was cleaned from unused objects. The following code fragment shows how to ensure the invocation of garbage collection.

Object object = new Object();
final WeakReference<Object> ref = new WeakReference<>(object);
object = null;
while (ref.get() != null) {

The above code make use of the WeakReference (Java doc) class ability.

Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable. At that time it will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references. At the same time it will declare all of the formerly weakly-reachable objects to be finalizable. At the same time or at some later time it will enqueue those newly-cleared weak references that are registered with reference queues.

The weak reference will ensure us that the garbage collection has executed when the weak reference is cleared.

Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 award (Website).

Leave a Comment

Time limit is exhausted. Please reload the CAPTCHA.