How does the JVM terminate daemon threads? or How to write daemon threads that terminate gracefully

Aaron J Lang picture Aaron J Lang · Dec 29, 2011 · Viewed 21.3k times · Source

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?

Answer

skiller3 picture skiller3 · Dec 29, 2011

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.