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 ...
<pre><code> String foo = "bar"; </code></pre>
-
Evan Bechtol
-
Luis Alberto Romero Calderon
-
ryanlr
-
Luis Alberto Romero Calderon
-
tippu
-
JP @ java interview question