CORE JAVA,Interview,Interview Questions

Why finalize() method should be avoided?

15 Oct , 2016  

We all know the basic statement that finalize() method is called by garbage collector thread before reclaiming the memory allocated to the object. See this program which prove that finalize() invocation is not guaranteed at all. Other reasons can be:

  1. finalize()methods do not work in chaining like constructors. It means like when you call a constructor then constructors of all super classes will be invokes implicitly. But, in case of finalize methods, this is not followed. Super class’s finalize() should be called explicitly.
  2. Any Exception thrown by finalize method is ignored by GC thread and it will not be propagated further, in fact it will not be logged in your log files. So bad, isn’t it?
  3. Also, There is some performance penalty when finalize() in included in your class. In Effective java (2nd edition ) Joshua bloch says,

“Oh, and one more thing: there is a severe performance penalty for using finalizers. On my machine, the time to create and destroy a simple object is about 5.6 ns. Adding a finalizer increases the time to 2,400 ns. In other words, it is about 430 times slower to create and destroy objects with finalizers.”

Lets prove it using a program. I have written a simple java runnable with one print statement in each block i.e. try-catch-finally-finalize. I have also created another class which will create 3 instances of this runnable and then we will see the execution path.

There is another method also: Runtime.getRuntime().runFinalization(); But, it only guarantees that GC will make best efforts. Even in our program it is not able to run finalize method for all 3 threads.

Moving forward, we have used Runtime.runFinalizersOnExit(true); Well, this is another pit. This method has already been deprecated in JDK, with following reason:

“This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.”

Leave a Reply

Your email address will not be published. Required fields are marked *