There is a javadoc for System.exit(int):
|
1 2 3 4 5 6 |
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally. The call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n) |
And based on this I made a simple java app:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.Date; public class TestSystemExit { public static void main(String[] args) { Runtime.getRuntime().addShutdownHook(new Thread(() -> { while(true ) { System.out.println("$ " + new Date().getTime()); try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } })); System.out.println("$ system exit"); System.exit(1); System.out.println("$ something is wrong"); } } |
I expect to see “$ system exit” only since System.exit(int) “terminates the currently running Java Virtual Machine”. But app never stop instead. The cause in shutdown hook and that’s specified in javadoc for method Runtime.exit(int):
|
1 2 3 4 5 6 |
Terminates the currently running Java virtual machine by initiating its shutdown sequence. This method never returns normally. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. The virtual machine's shutdown sequence consists of two phases. In the first phase all registered shutdown hooks, if any, are started in some unspecified order and allowed to run concurrently until they finish. In the second phase all uninvoked finalizers are run if finalization-on-exit has been enabled. Once this is done the virtual machine halts. If this method is invoked after the virtual machine has begun its shutdown sequence then if shutdown hooks are being run this method will block indefinitely. If shutdown hooks have already been run and on-exit finalization has been enabled then this method halts the virtual machine with the given status code if the status is nonzero; otherwise, it blocks indefinitely. The System.exit method is the conventional and convenient means of invoking this method. |