问题
Follow up from previous question
If you've read the previous question an alternative title may be:
How often should my daemon check to see if it's been interrupted?
回答1:
When the JVM is signaled to quit it runs a shutdown process, which starts all of the shutdown hook threads and then waits for them to finish. It is up to the OS to decide how long to wait and that depends on the method used to initiate the termination of the process. You can try this for yourself with a simple test program like:
public static void main ( String[] args ) throws InterruptedException {
Runtime.getRuntime ().addShutdownHook ( new Thread () {
@Override
public void run () {
System.out.println ( "Shutdown hook" );
while ( true ) { }
}
} );
while ( true ) {
System.out.println ( "Looping" );
Thread.sleep ( 10000 );
}
}
If you signal the process with ctrl+c the process will start the shutdown hook but never finish. If you remove the busy loop in the shutdown hook, you will see it terminate when the hook finishes.
回答2:
jvm executes shutdown. grace time is based on operating system and AFAIK we don't have any control to configure this.
来源:https://stackoverflow.com/questions/8663425/how-long-does-the-jvm-allow-shutdown-hooks-to-run-before-calling-halt