This method call requests the Java Virtual Machine for running garbage collection process. This call does not
guarantee that GC will run immediately. Note that this method is not recommended to rely on for applying some application logic.
package com.logicbig.example.system;
public class GcExample {
public static void main(String... args) {
for (int i = 1; i < 11; i++) {
MyClass myClass = new MyClass(i);
System.out.printf("MyClass created, c= %s%n",
myClass.getC());
System.gc();
}
}
public static class MyClass {
private final int c;
public MyClass(int c) {
this.c = c;
}
public int getC() {
return c;
}
//This method will be Called by the garbage collector
//before removing this object from the memory.
@Override
protected void finalize() throws Throwable {
System.out.printf("-- %s is getting garbage collected --%n", c);
}
}
}
Output
MyClass created, c= 1
MyClass created, c= 2
MyClass created, c= 3
-- 1 is getting garbage collected --
MyClass created, c= 4
-- 2 is getting garbage collected --
MyClass created, c= 5
-- 3 is getting garbage collected --
MyClass created, c= 6
-- 4 is getting garbage collected --
MyClass created, c= 7
-- 5 is getting garbage collected --
MyClass created, c= 8
-- 6 is getting garbage collected --
MyClass created, c= 9
-- 7 is getting garbage collected --
MyClass created, c= 10
-- 8 is getting garbage collected --
-- 9 is getting garbage collected --
-- 10 is getting garbage collected --
Without System.gc() call:
package com.logicbig.example.system;
public class GcExample2 {
public static void main(String... args) {
for (int i = 1; i < 11; i++) {
GcExample.MyClass myClass = new GcExample.MyClass(i);
System.out.printf("MyClass created, c= %s%n",
myClass.getC());
}
}
}
Output:
MyClass created, c= 1
MyClass created, c= 2
MyClass created, c= 3
MyClass created, c= 4
MyClass created, c= 5
MyClass created, c= 6
MyClass created, c= 7
MyClass created, c= 8
MyClass created, c= 9
MyClass created, c= 10