Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do finalizers (and ReferenceQueue's) run on JVM termination? [duplicate]

I know you can't count on finalizers to clean up your mess (i.e. free resources), but I was wondering - do java objects get GC'ed / finalized when the JVM normally terminates (System.exit() / no threads left)?

EDIT:

So, the GC is not guaranteed to be triggered, hence nor finalize(), but will ReferenceQueue work?

like image 280
Elist Avatar asked Aug 06 '13 06:08

Elist


1 Answers

For a while, there was a method Runtime.runFinalizersOnExit which could be called with argument true to guarantee that all objects were finalized before the VM shuts down. That method is now deprecated, for reasons that are documented in the java documentation at http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html all the way at the bottom of the page. This is the relevant section:

Why is Runtime.runFinalizersOnExit deprecated?

Because it 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. While this problem could be prevented if the class whose objects are being finalized were coded to "defend against" this call, most programmers do not defend against it. They assume that an object is dead at the time that its finalizer is called.

Further, the call is not "thread-safe" in the sense that it sets a VM-global flag. This forces every class with a finalizer to defend against the finalization of live objects!

Now that this method has been deprecated, there is no way whatsoever to guarantee object finalization. Whether and when to garbage collect an object is completely up to the JVM.

like image 59
tbodt Avatar answered Sep 27 '22 23:09

tbodt