How do I implement graceful termination in Java?
Asked Answered
S

2

11

Say for instance I have my application running in a Linux terminal and I press "CTRL+C" on my keyboard to kill the process it will terminate the Java program.

Is there any way to catch this "request" in my Java application so I can shut it down gracefully and release all resources/write logs. I have several different threads running if it makes a difference to the response.

I know you have have an addShutDownHook, but as written in the Java documentation, it isn't called under certain circumstances, like the kill signal from "CTRL+C" in linux...are there any other ways?

Runtime.getRuntime().addShutdownHook(new Thread()
{
    public void run ()
    {
        // TODO: implement graceful shutdown here.
    }
});
Sustentacular answered 17/5, 2011 at 10:34 Comment(0)
U
3

I think the disclaimer is only there for kill -9, so that you don't rely on the shutdown hook being invoked to maintain say the consistency of your data.

So if the process is allowed to act on the signal by the OS, the shutdown hook is invoked, which is pretty obvious if you know how an OS works, but maybe not to all Java developers.

It is actually explained in great detail in the javadoc.

Also worth bearing in mind is that there can be multiple shutdown hooks registered in a VM, so yours might not be THE shutdown hook, just one of several.

Unthankful answered 17/5, 2011 at 10:38 Comment(2)
Shutdown hooks will also not be called if the JVM is halted download.oracle.com/javase/6/docs/api/java/lang/…Antiperspirant
@Nathan D. Ryan True, it's pretty reasonable I believe. :) To sum it up, they won't be invoked in situations when there's nothing you could do anyway.Unthankful
T
2

This works for me, capturing SIGINT/Ctrl-C on Linux:

public class TestShutdownHook
{
    public static void main(final String[] args) throws InterruptedException
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("Shutdown hook ran!");
            }
        });

        while (true)
        {
            Thread.sleep(1000);
        }
    }
}
Therefore answered 17/5, 2011 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.