Java Garbage Collection: How it works, How to control it
Java has Garbage Collection. Good thing, yes! But, say with me:
The Garbage Collector deallocates all objects with zero references when it wants!!
Two troubles:
- Objects with zero references: typically a Java code looks like:
public void doSomething() {
Configuration c = new Configuration("test.conf");
long limit = c.getLimit();
for(long i = 0; i≤limit ; i++) {
String s = new String(i);
System.out.println(s);
}
}
The Configuration instance lives until the method's end. We can write:public void doSomething() {
Configuration c = new Configuration("test.conf");
long limit = c.getLimit();
c = null; // good! now c has 0 reference!
for(long i = 0; i≤limit ; i++) {
String s = new String(i);
System.out.println(s);
}
} - GC deallocates them when it wants: it seems that the String instances will be cleaned when they go out of scope, but it isn't!!.
The String instances are in a particular state called Invisible State.
The GC cleans all the object that go out of scope only when the method doSomething() returns!!
Simply, manually set the reference to null:public void doSomething() {
Configuration c = new Configuration("test.conf");
long limit = c.getLimit();
c = null; // good! now c has 0 reference!
for(long i = 0; i≤limit ; i++) {
String s = new String(i);
System.out.println(s);
s = null; // good! now s has 0 reference!
}
}
Now all our Object are only eligible for cleaning.
You cannot force garbage collection, just suggest it! You can suggest GC withSystem.gc()
, but this does not guarantee when it will happen.