2.6. Daemon threads
Last updated: 31 January 2013.
What is a daemon thread?
There are two types of threads: user threads and daemon threads. So far, all the threads that you have seen in action in the previous tutorials were user threads. A program can run user threads and daemon threads concurrently. The behaviour of the JVM towards a program running user threads and daemon threads is what makes the difference between user threads and daemon threads: The JVM does not shut down a program as long as there is one or more user threads running. The JVM only shuts down a program when all the user threads have died. If any daemon threads are running by the time all user threads die, the JVM terminates the daemon threads regardless of what they are doing.
In a word, user threads keep a program from being shut down by the JVM whereas daemon threads do not keep a program from being shut down by the JVM.
When to use daemon threads?
Daemon threads are considered as threads that run in the background and they are generally used as service providers for user threads. For example, the Java garbage collector is a daemon thread. When all the user threads of a program die, the JVM terminates the garbage collector and shuts down the program. Therefore, you should not use daemon threads to run your program's code but instead to provide some sorts of services to user threads.
How to create a daemon thread?
Just create a normal thread and call the method setDaemon before starting the thread as shown below:
MyThread myThread = new MyThread();
In the above sample, the class MyThread is a subclass of the class Thread. The method setDaemon must be called before the thread has been started, otherwise an IllegalThreadStateException is thrown.