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.
System.runFinalizersOnExit()
, however it is deprecated. Anyway, when you exit a process, it is the OS which cleans up ultimately. Now, why this question? – OperationRuntime.addShutdownHook()
! there is no warranty about calling finalize, and if system did, there is no warranty to let the finalize does everything it wants. – Saito