Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java shutdown hook with more than one thread

I am trying to get a shutdown hook to work on my ubuntu server, however I seem to have an issue with more than one thread. Using the a basic ShutdownHook, the following bit of code does work when I kill the process using kill <PID>, meaning the shutdown behavior is activated.

public static void main(String[] args) {
    ShutdownHook shutDown = new ShutdownHook();
    shutDown.attachShutDownHook();

    while(true){}
}

however this same code with an additional thread does not

public static void main(String[] args) {
    ShutdownHook shutDown = new ShutdownHook();
    shutDown.attachShutDownHook();

    (new Thread() {
        public void run() {
            while ( true ) {}
        }
    }).start();

    while(true){}
}

Any ideas?

class ShutdownHook {

    ShutdownHook() {
    }

    public void attachShutDownHook() {

            Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                            System.out.println("Shut down hook activating");
                    }
            });
            System.out.println("Shut Down Hook Attached.");

    }
}
like image 674
Reese Avatar asked Oct 31 '12 13:10

Reese


People also ask

How do you trigger a shutdown hook?

Consider running your program in a console and you signal it with Ctrl+C to terminate it. It will trigger the shutdown hooks you registered.

What is graceful shutdown in Java?

Graceful Shutdown Timeout During a graceful shutdown Spring Boot allows some grace period to the application to finish all the current requests or processes. Once, the grace period is over the unfinished processes or requests are just killed. By default, Spring Boot allows a 30 seconds graceful shutdown timeout.

What is shutdown hook in spring?

Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used. In addition, beans may implement the org. springframework.


1 Answers

The JVM won't exit while there are still non-daemon threads running. Try calling setDaemon(true) on your new thread.

like image 193
SimonC Avatar answered Oct 19 '22 22:10

SimonC