MultiThreaded Programming  «Prev 

daemon and non-daemon threads, setDaemon method and Java Thread Concepts

In Java 1.1, the setDaemon method (now commonly referred to as setDaemon in modern Java versions) plays a crucial role in defining the behavior of threads, particularly in relation to the termination of the Java Virtual Machine (JVM). Here's a detailed explanation of its role within the context of the Java 1.1 Threading Model:
Daemon Threads vs. Non-Daemon Threads
  • Daemon Threads: These are threads that run in the background and do not prevent the JVM from exiting when the program finishes. If all non-daemon threads have completed, the JVM will exit, even if daemon threads are still running.
  • Non-Daemon Threads: These are threads that will keep the JVM alive until they complete their execution. The JVM will not exit as long as there are any non-daemon threads running.

The setDaemon Method
The setDaemon method is used to mark a thread as either a daemon thread or a non-daemon thread. The method takes a boolean parameter:
  • setDaemon(true): Marks the thread as a daemon thread.
  • setDaemon(false): Marks the thread as a non-daemon thread (this is the default).

Key Points about setDaemon
  1. Default Behavior: By default, threads are non-daemon threads. This means that if you create a new thread without calling setDaemon(true), it will be a non-daemon thread.
  2. Setting Daemon Status: You must call setDaemon before starting the thread with the start method. If you try to set the daemon status after the thread has started, it will throw an IllegalThreadStateException.
  3. JVM Termination: The JVM will exit when all non-daemon threads have completed. Daemon threads are terminated abruptly if the JVM exits.
  4. Use Cases: Daemon threads are typically used for background tasks that should not prevent the JVM from exiting. Examples include garbage collection, monitoring, or other maintenance tasks.


Example Usage
Here is an example of how to use the setDaemon method:
public class DaemonThreadExample {
    public static void main(String[] args) {
        Thread daemonThread = new Thread(() -> {
            while (true) {
                System.out.println("Daemon thread is running");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // Mark the thread as a daemon thread
        daemonThread.setDaemon(true);

        // Start the thread
        daemonThread.start();

        // Main thread sleeps for a while to allow daemon thread to run
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Main thread is finishing, JVM will exit if there are no non-daemon threads running.");
    }
}

Explanation
  • Daemon Thread: The daemonThread is marked as a daemon thread using setDaemon(true). It runs in an infinite loop, printing a message every second.
  • Main Thread: The main thread sleeps for 5 seconds, allowing the daemon thread to run. After the main thread finishes, the JVM exits, and the daemon thread is terminated abruptly.

Conclusion The setDaemon method in Java 1.1 (and later versions) is essential for controlling the lifecycle of threads in relation to the JVM's termination. By marking threads as daemon threads, you can ensure that they do not prevent the JVM from exiting when the main program has completed, making them suitable for background tasks that should not block the termination of the application.


daemon versus non-daemon Thread

  • daemon Thread: Java has a special kind of thread called daemon thread. These kind of threads have very low priority and normally only execute when no other thread of the same program is running.
    When daemon threads are the only threads running in a program, the JVM ends the program finishing these threads.
    With these characteristics, the daemon threads are normally used as service providers for normal (also known as user) threads running in the same program. They usually have an infinite loop that waits for the service request or performs the tasks of the thread. They cannot do important jobs because we do not know when they are going to have CPU time and they can finish any time if there are no other threads running. A typical example of these kind of threads is the Java garbage collector.
  • non-daemon Thread: A Java program ends when all its threads finish (more specifically, when all its non-daemon threads finish). If the initial thread (the one that executes the main() method) ends, the rest of the threads will continue with their execution until they finish. If one of the threads use the System.exit() instruction to end the execution of the program, all the threads end their execution.Creating an object of the Thread class doesn't create a new execution thread. Also, calling the run() method of a class that implements the Runnable interface does not create a new execution thread. Only calling the start() method creates a new execution thread.



setDaemon Threads

The JVM will be alive until all the "non-deamon threads" have finished execution. When you set the daemon flag to false, the thread is a "non-deamon" and will keep running.
However, if you set the daemon flag to true,
t.setDaemon(true);

as soon as the main() method completes execution, the JVM will exit.
The JVM will not shut down until all the "non-daemon threads" complete.
Question: Can we force all threads to exit before the main exit by using setDaemon(true); ?

Answer: Yes, unless System.exit() is called.
There is a thread called the "main thread", which is the one that runs the main() method. This thread is just another "non-daemon thread" with the name main and it starts before the other "non-daemon threads".
However, the JVM will not terminate until all "non-daemon threads" have completed, or until System.exit() is called.
When there are no more "non-daemon threads", there may or may not be "daemon threads" present. In any case, the JVM can exit, and any remaining "daemon threads" are killed when the JVM exits.
Nevertheless, you cannot force the main() method to exit 1) before or 2) after the "daemon threads" terminate. When the JVM exits, it automatically terminates any remaining threads as it exits. The "main thread" can exit even if the daemon threads are running since the main daemon is just another thread that runs the "main() method" in Java. The JVM will not shut down if there are still "non-daemon threads" running.

Java Concurrency
Question: In a normal case (when there are no "non-daemon threads" running), does the JVM exit with the main thread?
Answer: The JVM will exit shortly after the last "non-daemon thread" exits. The last "non-daemon thread" may be the main thread (for the main() method), or it may be a different thread. As part of the JVM shutdown, any remaining "daemon threads" will also be shut down.
This is not something you can force, it is something that will always happen when the JVM shuts down, if there are any "daemon threads" remaining.

Quiz Question with respect to the setDaemon Method

What will the following program print when run?
class MyThread extends Thread{
 public void run(){
  for(;;){
   System.out.println("running...");
  }
 }
}

public class TestClass{
 public static void main(String args[]) throws Exception{
  MyThread mt = new MyThread();
  mt.setDaemon(true);
  mt.start();
  mt.setDaemon(false);
 }
}

Select 1 option:
  1. It will keep printing "running..." for ever.
  2. It will throw an exception at runtime.
  3. It will print "running..." for some time and end without any exception.
  4. It will not even compile.


Answer: b
Explanation:
You cannot call setDaemon() after the thread is started. It will throw IllegalThreadStateException if you do so. Remember that same exception is thrown if you try to call start() on a thread that is already started.

Remote 1