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?
Linux Shutdown and Java Shutdown Hook
1.9k views Asked by Harald At
3
There are 3 answers
0
On
You can wrap your java program as a service and it will started and shut down with OS. One of the easiest way to do so, is using spring boot framework.
2
On
In case you want to do something on system shutdown, you need to add a shutdown-hook (assuming you already do this) :
Runtime.getRuntime().addShutdownHook(
new Thread(new Runnable() {
@Override
public void run() {
// This method will be executed and Virtual Machine will close when this method will return
}
}));
The system will NEVER await a full termination if it took too much time
From the doc Runtime#addShutdownHook
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.
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:
Runtime.halt()
will also prevent a hook from begin run.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.
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.