Uses of Finalize method in Java

3 Flares Twitter 0 Facebook 1 Google+ 2 LinkedIn 0 Filament.io 3 Flares ×

In Java, finalize is a method that garbage collector must run on the object before freeing or garbage collecting the object. To add a finalizer to a class, just declare it as follows:

The finalize method is defined in the java.lang.Object class and you are in fact overriding it in your class. It is defined as protected in the super class and that’s the reason the overridden method is having the protected access modifier. It is a best practice to call the super.finalize() after your class has freed up the resources it was holding. This is because call to finalize are not automatically chained and garbage collector calls finalize only once on an instance. If you don’t call super.finalize, any resource held by the super class may never be given the opportunity to free it up.

Finalize actually makes the job of a garbage collector more difficult. Garbage collector has to inspect all objects to see whether it  has a finalize method defined and if true, it has to invoke it. You should always keep in mind that by Java Language Specification there is no timely execution of  finalize method. Garbage collector may decide to call it at time decided by its algorithm. For instance, if you write code such that you use a shared resource and rely on the execution of the finalize, to free the resource so that, another part of the program can gain exclusive access to the resource, you are going on the wrong path.  Hence you should never write code such that other parts of the program depends on the timely execution of the finalize.

There is a lot of confusion on the need for the finalize method and when you need to override it. Here is a scenario where it is useful.If you have an object that has a lock on a file or database table, you may want to override your finalize method to release those when your object is garbage collected. But if you keep you file and database connections to the shortest possible scope and release them as soon as the use is over, it is rarely required for you to override finalize. But, java gives you the facility to clean up any resource held by your object just before it is thrown to garbage.