jeudi 10 novembre 2011

Let's talk about finalize in java

So, what is finalize, how do we use it?
Well, the answer is simple, we don't. To be more precise, most of the time we don't.
The finalize method gets called when an object is garbage collected to clean any mess caused by that object. All java object have that method, since it is implemented on the Object class. And as you are already aware of, it's the mother class of all other java classes. If the object which was just garbage collected, was using system resources, the finalize method will take care of releasing them. An example of these resources could be an open file. So be careful when you try to use it, it won't clean your java objects, it will only take care of non-java resources.

The finalize method shouldn't be used since it's not a very reliable method, since there is no guarantee that the object will be garbage collected during the lifetime of an application, in addition to the fact that it takes care only of non-java resources. But if you want to use it, here's how to proceed.

You have to declare your method this way:

protected void finalize () throws throwable
Now, inside the method:

Since the method is error-prone, it should contain the famous try-catch-finally statement

    //you do your personalized cleaning operations here
} finally {
    //then you have to call the parent finalize method
Now you have your finalize() method ready for action, just don't forget, don't rely on it too much, because maybe it will be called, and maybe it won't.