I recently discovered that Java has finalization methods for objects, just like C++. However, they do not behave the same way due to Java's garbage collection.

In Java, a finalization method has the following prototype: protected void finalize();, which is inherithed from java.lang.Object. This method can do any task it wants to explicitly release resources owned by an object.

In C++ you have the following expectation: a finalization method is called whenever the object ceases to exist. That is: when a local object goes out of scope (all of them are deleted when the program shuts down) or when you explicitly delete a region of allocated memory. However, dynamically allocated objects are not automatically deleted when the program exits (you must remember to do it by hand).

Java behaves much like C++'s dynamically allocated objects in this regard. If they are not "explicitly" deleted, their finalization method is not executed. And who deletes them? The GC when it feels it has to. This means that you cannot predict in any way when your object will be deleted; in fact, you cannot even know if the destroyer method will be ever executed. This is why Java classes provide methods to deallocate resources on purpose (see the close method on any class that affects files).

Let's see a little example:
class Test {
protected void finalize() {
System.out.println("Removed");
}

public static void main(String[] args) {
Test c = new Test();
}
}
If you build and run this program, it will probably print nothing. The GC doesn't act on shutdown so the object is implicitly removed when the VM closes. Instead, if you try the following, you will probably see something:
class Test {
protected void finalize() {
System.out.println("Removed");
}

public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
Test c = new Test();
}
}
}
It's a pity that destoryers do not work "correctly" (I mean, as in C++'s local variables), because this can make some pieces of code overly complex to control all possible execution flows.

And sorry for the long delay in posting. I'm nowadays extremely busy with a university project and have few time for anything else.

Comments from the original Blogger-hosted post: