How do I stop a Java process gracefully in Linux and Windows?
When does Runtime.getRuntime().addShutdownHook
get called, and when does it not?
What about finalizers, do they help here?
Can I send some sort of signal to a Java process from a shell?
I am looking for preferably portable solutions.
pgrep -a java will return the PID and full command line of each java process. Once you have the PID of the command you wish to kill, use kill with the -9 (SIGKILL) flag and the PID of the java process you wish to kill.
Kill a process by the pkill command It allows us to kill a process by entering the matching name of the process. For example, we want to kill all the processes with matching name java, execute the command as follows: pkill java.
Scroll down to the "Java.exe" process. Right-click the process name and select "End Task." Click "Yes" to confirm that you want to stop the process. The process stops, and any opened Java programs also stop.
If you want to kill all java.exe processes : taskkill /F /IM java.exe /T .
Shutdown hooks execute in all cases where the VM is not forcibly killed. So, if you were to issue a "standard" kill (SIGTERM
from a kill command) then they will execute. Similarly, they will execute after calling System.exit(int)
.
However a hard kill (kill -9
or kill -SIGKILL
) then they won't execute. Similarly (and obviously) they won't execute if you pull the power from the computer, drop it into a vat of boiling lava, or beat the CPU into pieces with a sledgehammer. You probably already knew that, though.
Finalizers really should run as well, but it's best not to rely on that for shutdown cleanup, but rather rely on your shutdown hooks to stop things cleanly. And, as always, be careful with deadlocks (I've seen far too many shutdown hooks hang the entire process)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With