Item 7: Avoid finalizers

There is no guarantee that the finalize method will be called immediately. So, one should not depend upon it for anything time critical.

The Great Ancient Myth

System.gc and System.runFinalization call finalizers with guarantee.

The Truth

They even don’t guarantee it, they might increase the probability of execution of the garbage collector

The evil siblings

System.runFinalizersOnExit and Runtime.runFinalizersOnExit are fatally flawed and have been deprecated.

Why else should I not use finalizers?

  1. If an uncaught exception is thrown during finalization, the exception is ignored.
  2. There is a sever performance hit for using finalizers.

Any alternatives?

Explicit termination methods are typically used in combination with the try-finally construct to ensure termination. Finally block guarantees the execution of the statements written inside it. It must be usually used to free up space, free up resources like sql connections, input & output stream. In case the finally block fails to release a resource, it must log an error.

Finalizer Chaining

The finalizer chaining, i.e. the finalizer of the subclass calling the super class finalizer, doesn’t happen in java automatically. This has to be taken care of manually. Thus, don’t forget to call super.finalize

Finalizer Gaurdian

A private object is written and its finalize is overriden, just to finalize the outer object. The example will make things clear for you.

// Finalizer Guardian idiom
public class Foo {
    // Sole purpose of this object is to finalize outer Foo object
    private final Object finalizerGuardian = new Object() {
        @Override
        protected void finalize() throws Throwable {
            ... // Finalize outer Foo object
        }
   };
   ... // Remainder omitted
}
Advertisements

About Gaurav

I'm Gaurav; friends call me Teddy, n i'm shivi fr my family!! A java enthusiast who likes experimenting with what he knows. View all posts by Gaurav

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: