Java Force Garbage Collection – Code Example

Garbage collection in java can not be enforced. But still sometimes, we call the System.gc( ) method explicitly. System.gc() method provides just a “hint” to the JVM that garbage collection should run. It is not guaranteed!

The API documentation for System.gc() states that “When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.” The responsibility for a programmer is to make sure no references remain for objects.

The program below shows that the garbage collection may run after System.gc() is called. Again, it is NOT guaranteed.

public class GCTest {
	public static void main(String[] args) throws InterruptedException {
		A a = new A("white");
		a = null;
 
		Runtime.getRuntime().gc();
	}
}
 
class A {
	private String color;
 
	public A(String color) {
		this.color = color;
	}
 
	@Override
	public void finalize() {
		System.out.println(this.color + " cleaned");
	}
}

So the program may or may not output the following:

white cleaned

The program below shows that the garbage collection automatically works behind without System.gc() called.

public class GCTest {
	public static void main(String[] args) throws InterruptedException {
		A a = new A("white");
 
		for (int i = 0; i < 10000000; i++) {
			if (i % 2 == 1) {
				a = new A("red");
			} else {
				a = new A("green");
			}
			a = null;
		}
	}
}
 
class A {
	private String color;
 
	public A(String color) {
		this.color = color;
	}
 
	@Override
	public void finalize() {
		System.out.println(this.color + " cleaned");
	}
}

It will output something like the following:

...
green cleaned
green cleaned
red cleaned
red cleaned
green cleaned
green cleaned
red cleaned
red cleaned
green cleaned
green cleaned
red cleaned
red cleaned
...

7 thoughts on “Java Force Garbage Collection – Code Example”

  1. This is honestly not good practice; calling System.gc()

    It’s a sign that your code is fundamentally flawed somewhere and needs serious revising.
    It also implies that the developer expects something to be cleaned, but as you state it may not necessarily be cleaned. This can result is some serious repercussions later in your program if you write code that is dependent on that object being picked up by gc.

    Also, the title is a bit misleading, you can NEVER explicitly force the garbage collection to run.

    Overall, calling garbage collection manually is HIGHLY inadvisable.

Leave a Comment