determine if an application is shutting down normally
is there a way to determing if a jvm is shutting down normally? Shutdown hook can only spawn a thread, is there a开发者_StackOverflow社区 way to determine if the JVM is existing normally or abnormally at that time?
You could write a file on startup and delete it again on graceful exit. If the JVM is gone but the file is still there you know that it crashed or has otherwise exited in a unintended manner.
I remembered a similar question being asked time ago. One possible course of action is the use of SignalHandler.
You can read the full article here. It appears to be related to IBM JVM but I think it is equally valid for Java Hotspot.
A little-known feature of Java is the ability of an application to install its own signal handler, which is supported through the sun.misc.Signal class. However, use caution when using classes from the sun.misc package because it contains undocumented support classes that may change between releases of Java. You can install a Java handler for any signal that is not used by the JVM. These signal handlers are similar to native handlers because they're invoked when a native system signal is raised, but they will always run as a separate Java thread. Essentially, when a signal is raised for which a Java signal handler is available, the JVM's "signal dispatcher thread" is woken up and informed of the signal. The signal dispatcher thread then invokes a Java method to create and start a new thread for the installed Java signal handler. To write a Java signal handler, define a class that implements the sun.misc.SignalHandler interface and register the handler by using the sun.misc.Signal.handle() method.
Check return sttaus using command $?
When the JVM is shutting down normally, this means that the main thread has ended. If the JVM is shutting down for some other resaon (e.g. the user pressed Strg+C), the main thread is still running. So you can store a reference to the main thread in your shutdown hook and check whether this thread is still alive. Of course this assumes that the main thread will normally be the last running thread in your application. I don't know how the situation is if one of the threads called System.exit(), but you could easily find this out.
精彩评论