When I run a Java process in background and I shut down the computer (ArchLinux), will the computer wait some seconds for the termination of my shutdown-hook in Java?
Advertisement
Answer
A shutdown hook will be called when a call to close the JVM is made. However, there is no guarantee that the hook will be called. The hook might not/won’t run:
- If the JVM crashes from an internal error.
- If SIGKILL is signaled, or kill -9 in linux and TerminateProcess in windows.
- The
Runtime.halt()
will also prevent a hook from begin run. - The computer power is pulled (at the plug).
- Your OS crashes.
When the user turns off the computer (not by pulling the plug), the computer sends a shutdown command to the JVM which will execute the shutdown hooks, although if the power is pulled the computer won’t have any time to do anything, let alone issue a command to the JVM.
I remember reading somewhere (but i couldn’t find the link again) – it said that a shutdown hook shouldn’t take to much time to execute or windows might kill it when the system wants shutdown. This indicates that the shutdown hooks will be run if you decide to turn off the system though the OS.
Tl;dr: It depends, pulling the power directly or if the OS crashes, they won’t be run. A normal OS shutdown will run the hooks, although it’s possible the OS might close them before they finish if they’re taking too long.
This is from the javadoc.
When the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit. It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook.
This states that the hooks will be run when the OS wants to shutdown, but it’s advised that they don’t take long or they might get killed.