Troubleshooting a java memory leak: finalization?

Rom1 picture Rom1 · Oct 4, 2011 · Viewed 12.3k times · Source

I have a misbehaving application that seems to leak. After a brief profiler investigation, most memory (80%) is held by java.lang.ref.Finalizer instances. I suspect that finalizers fail to run.

A common cause of this seems to be exceptions thrown from the finalizer. However, the javadoc for the finalize method of the Object class (see here for instance) seems to contradict itself: it states

If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

but later, it also states that

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

What should I believe (i.e., is finalization halted or not?), and do you have any tips on how to investigate such apparent leaks?

Thanks

Answer

Bringer128 picture Bringer128 · Oct 4, 2011

Both quotes say:

An exception will cause finalization of this object to be halted/terminated.

Both quotes also say:

The uncaught exception is ignored (i.e. not logged or handled by the VM in any way)

So that answers the first half of your question. I don't know enough about Finalizers to give you advice on tracking down your memory leak though.

EDIT: I found this page which might be of use. It has advice such as setting fields to null manually in finalizers to allow the GC to reclaim them.

EDIT2: Some more interesting links and quotes:

From Anatomy of a Java Finalizer

Finalizer threads are not given maximum priorities on systems. If a "Finalizer" thread cannot keep up with the rate at which higher priority threads cause finalizable objects to be queued, the finalizer queue will keep growing and cause the Java heap to fill up. Eventually the Java heap will get exhausted and a java.lang.OutOfMemoryError will be thrown.

and also

it's not guaranteed that any objects that have a finalize() method are garbage collected.

EDIT3: Upon reading more of the Anatomy link, it appears that throwing exceptions in the Finalizer thread really slows it down, almost as much as calling Thread.yield(). You appear to be right that the Finalizer thread will eventually flag the object as able to be GC'd even if an exception is thrown. However, since the slowdown is significant it is possible that in your case the Finalizer thread is not keeping up with the object-creation-and-falling-out-of-scope rate.