JaVa
   

Daemon Threads

A "demon" is an evil supernatural being that wishes to take over the world and destroy it. A demon doesn't realize that it needs the world for survival. It depends on it. Similarly, somehow, a daemon (pronounced like demon) thread is one that depends on other user threads being alive. If a thread is not a daemon thread, it is known as a user thread, meaning it will run on its own independently of other threads, whereas a daemon thread will run but will stop when no more user threads, like main's threads, are running in the app. Basically, the program will exit when the only threads left running are daemon threads, meaning they will then stop too. You can simply set a thread as a daemon or not by using the setDaemon method of a thread object. Note that this method needs to be called before the thread is started. The following code illustrates a simple example of how a daemon thread relies on its creator. Here is the code for DaemonThread.java:

Code Listing 7-5: DaemonThread.java
public class DaemonThread extends Thread
{
 public DaemonThread()
 {
 setDaemon(true);
 }
 public void run()
 {
 while(true)
 {
 System.out.println("How long can we last");
 }
 }
 public static void main(String args[])
 {
 DaemonThread myThread = new DaemonThread();
 myThread.start();
 }
}


Java End example

When you compile and run this example, you should get multiple lines of the text "How long can we last" until the thread dies, as can be seen in the following screen shot.

Java Click To expand
Screenshot-5:

In this code, the thread in which main is running creates a new thread, which we first set as a daemon before starting it. This means that the daemon thread's existence relies on the main thread staying alive. They're like Romeo and Juliet. When main exits and the user thread it is running in finally dies, the app terminates, as all that is left is a daemon thread. You can use the thread method isDaemon to check if a thread is a daemon or not.

The default setting for whether a thread is a daemon or not is determined by the status of the current thread in which the new thread is created. The threads we have created so far have been user threads and not daemon threads by default because the thread they were created from, where main runs, is a user thread. A thread created by a daemon thread will, by default, be a daemon thread.

JaVa
   
Comments