How does the JVM terminate daemon threads? or How to write daemon threads that terminate gracefully
Hypothetical scenario:
I have a daemon thread responsible for some I/O, the main thread finishes and returns, and the JVM decides to terminate my daemon thread.
How does it do so? Interrupt? Finalize? How can I code my daemon thread so that it reacts gracefully when terminated?
Solution 1:
I just wrote the following code as a test:
public class DaemonThreadPlay {
public static void main(String [] args) {
Thread daemonThread = new Thread() {
public void run() {
while (true) {
try {
System.out.println("Try block executed");
Thread.sleep(1000l);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
@Override
public void finalize() {
System.out.println("Finalize method called");
}
};
daemonThread.setDaemon(true);
daemonThread.start();
try {
Thread.sleep(2500l);
} catch (Throwable t) {
//NO-OP
}
}
}
I put breakpoints in the catch block of the daemon thread and in the finalize method. Neither breakpoint was reached even though the try block was executed. Obviously this code has synchronization/timing issues, but I think we can safely conclude that daemon threads are not interrupted on shutdown nor are their finalize() methods necessarily invoked.
You can always add a shutdown hook to the JVM Runtime:
Thread shutdownHook = ... // construct thread that somehow
// knows about all the daemon threads
Runtime.getRuntime().addShutdownHook(shutdownHook);
Your shutdown hook can obviously do whatever tasks are required for a "graceful" shutdown.
Solution 2:
I think you misunderstand what a daemon thread is.
See what is a daemon thread in java
In summary, it basically means that a daemon thread shouldn't be doing any I/O or holding any resources. If you are contravening this basic rule then your thread doesn't qualify being a daemon thread.
Adding a shutdown hook is the standard way of ensuring your code gets invoked prior to JVM termination, but even this isn't 100% guaranteed - your JVM could crash for example, leaving the OS to tidy up resources in a way which protects the OS, but quite likely leaves your application in an inconsistent/erroneous state.
System checkpointing and recovery mechanisms go back to the early days of software (operating systems and batch operations for example), and unfortunately, this wheel keeps getting re-invented as there's no "silver bullet" approach (API) which tackles this problem in a generic enough way.