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.");
}
}
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.
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.
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.
The JVM won't exit while there are still non-daemon threads running. Try calling setDaemon(true)
on your new thread.
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