Here are some select quotes from Effective Java 2nd Edition: Item 7: Avoid finalizers:
Finalizers are unpredictable, often dangerous, and generally unnecessary. Their use can cause erratic behavior, poor performance, and portability problems. Finalizers have few valid uses, [...] as a rule of thumb, you should avoid finalizers.
You should really make sure that in fact, you DO need finalizers; most of the time you DON'T.
C++ programmers are cautioned not to think of finalizers as Java's analog of C++ destructors. In C++, destructors are the normal way to reclaim the resources associated with an object, a necessary counterpart to constructors. In Java, the garbage collector reclaims the storage associated with an object when it becomes unreachable, requiring no special effort on the part of the programmer. C++ destructors are also used to reclaim other nonmemory resources. In Java, the try-finally
block is generally used for this purpose.
The semantics of when finalizers are invoked is also important to consider:
The Java programming language does not specify how soon a finalizer
will be invoked [...nor] which thread will invoke the finalizer for any given object. [...] If an uncaught exception is thrown during the finalization, the exception is ignored and finalization of that object terminates. (JLS 12.6.2) Finalizer Invocations are Not Ordered
Moreover, the only mechanism to run finalizer on demand is broken. The following quotes are from Effective Java 2nd Edition:
[...] The only methods that claim to guarantee finalization are System.runFinalizersOnExit
and its evil twin, Runtime.runFinalizersOnExit
. These methods are fatally flawed and have been deprecated.
Bloch went further to comment on the performance penalty (emphasis his):
Oh, and there's 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.6ns. Adding a finalizer increases the time to 2,400ns. In other words, it is about 430 times slower to create and destroy objects with finalizers.
With such little details on the benchmarking methodology, I don't think the specific numbers mean much, but it does confirm what have been widely documented: finalizers are very costly.
The book does explain the rare scenarios under which using finalizers is valid. The omission of those quotes from this answer is intentional.