Java Force Garbage Collection – Code Example
Java garbage collection process in java can not be enforced. But still sometimes, we call the System.gc( ) function explicitly. System.gc() method is just as a “hint” to the VM 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 runs after System.gc() is called. This is NOT guaranteed.
public class Main {
public static void main(String[] args) throws InterruptedException {
ClassA a = new ClassA("white");
a = null;
Runtime.getRuntime().gc();
}
}
class ClassA {
private String color;
public ClassA(String color){
this.color = color;
}
@Override
public void finalize(){
System.out.println(this.color + " cleaned");
}
}
The program below shows that the garbage collection automatically works behind without System.gc() called.
public class Main {
public static void main(String[] args) throws InterruptedException {
ClassA a = new ClassA("white");
for(int i=0; i<10000000;i++){
if(i%2 == 1){
a = new ClassA("red");
}else{
a = new ClassA("blue");
}
a = null;
}
}
}
class ClassA {
private String color;
public ClassA(String color){
this.color = color;
}
@Override
public void finalize(){
System.out.println(this.color + " cleaned");
}
}