public class Main {
public static void main(String[] args) throws InterruptedException {
ClassA a = new ClassA();
a = null;
//Runtime.getRuntime().gc();
Thread.sleep(4000);
}
}
public class ClassA {
@Override
public void finalize(){
System.out.println("cleaned");
}
}
With the above code finalize() never executes. Nothing is printed to the console. When Removing comment from gc(), finalize() executes, and "cleaned" is printed to the console. Why do I have to call to the garbage collector explicitly ?
Finalization is not guaranteed to be executed with the virtual machine exit. There is no explicit GC for and the finalization is run in a dedicated thread which also exits. Link to explanation: http://download.oracle.com/javase/6/docs/api/java/lang/System.html#runFinalizersOnExit%28boolean%29
If you need clean up code use:
Runtime.addShutdownHook
http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29