You could try java.lang.Runtime.addShutdownHook(), and have the hook iterate over all threads and dump their stack traces with Thread.getAllStackTraces(). However, if the JVM was shutdown by Runtime.halt()
then the hooks won't be called. More complicated would be to use instrumentation to hook into the calls to Runtime.exit()
and Runtime.halt()
(or Shutdown.sequence()
, see edit #2), so you can see exactly what's happening at the time that either is called.
EDIT: Another way of doing it would be to install a SecurityManager which doesn't enforce any security, but which dumps the list of threads whenever SecurityManager.checkExit()
is invoked, since both halt()
and exit()
call that security manager method. This would be a lot easier than using instrumentation, and you could even decide to throw an exception in addition to logging what the threads are doing.
EDIT 2: The system the JVM is running on can tell the JVM to terminate, in which case using a security manager won't work. Nor will using instrumentation on Runtime.exit()
or Runtime.halt()
, since the method that gets invoked is java.lang.Shutdown.exit()
. And if the JVM is shutting down because the last daemon thread finished then Shutdown.shutdown()
is invoked. But shutdown hooks will work in either of those situations. So you should always use the shutdown hooks, even if you're also going to use the security manager or instrumentation.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…