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

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 threadsRuntime.getRuntime().addShutdownHook(shutdownHook);

Your shutdown hook can obviously do whatever tasks are required for a "graceful" shutdown.


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.


AFAIK,Daemon threads not really for main stream I/O work. If all threads are completed, JVM may close all daemon threads abruptly. The possible work around for your requirement will be create a ExecutorService like below:

ExecutorService execPool = Executors.newSingleThreadExecutor(new ThreadFactory() {    @Override        public Thread newThread(Runnable runnable) {                Thread thread = Executors.defaultThreadFactory().newThread(runnable);         thread.setDaemon(true);         return thread;        } }); 

invoke executorservice shutdown method from Shutdown hook.

Runtime.getRuntime().addShutdownHook(....)