Is there a destructor for Java? I don\'t seem to be able to find any documentation on this. If there isn\'t, how can I achieve the same effect?
To make my question m
I agree with most of the answers.
You should not depend fully on either finalize
or ShutdownHook
finalize
The JVM does not guarantee when this finalize()
method will be invoked.
finalize()
gets called only once by GC thread. If an object revives itself from finalizing method, then finalize
will not be called again.
In your application, you may have some live objects, on which garbage collection is never invoked.
Any Exception
that is thrown by the finalizing method is ignored by the GC thread
System.runFinalization(true)
and Runtime.getRuntime().runFinalization(true)
methods increase the probability of invoking finalize()
method but now these two methods have been deprecated. These methods are very dangerous due to lack of thread safety and possible deadlock creation.
shutdownHooks
public void addShutdownHook(Thread hook)
Registers a new virtual-machine shutdown hook.
The Java virtual machine shuts down in response to two kinds of events:
The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit
) method is invoked, or
The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.
A shutdown hook is simply an initialized but non-started thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled.
Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if the shutdown was initiated by invoking the exit method.
Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit.
But even Oracle documentation quoted that
In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly
This occurs when the virtual machine is terminated externally, for example with the SIGKILL
signal on Unix or the TerminateProcess
call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.
Conclusion : use try{} catch{} finally{}
blocks appropriately and release critical resources in finally(}
block. During release of resources in finally{}
block, catch Exception
and Throwable
.