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

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.

Leave a Comment