Deamon Threads

In Java, daemon threads are a type of thread that runs in the background and provides support to non-daemon threads. Daemon threads are considered as service providers for other threads and are automatically terminated when all non-daemon threads have finished executing.

Here are some key characteristics of daemon threads:

1.Daemon vs. Non-Daemon Threads: In Java, a thread can be marked as a daemon thread by calling the setDaemon(true) method on a Thread object. By default, threads created by the main thread are non-daemon threads, meaning they do not have the daemon flag set to true. When all non-daemon threads have completed their execution, the Java runtime system will exit, regardless of whether daemon threads are still running.

2.Background Execution: Daemon threads typically perform background tasks or provide services to other threads. They are designed to run continuously in the background, performing tasks such as garbage collection, logging, monitoring, or other maintenance activities.

3.Automatic Termination: When all non-daemon threads have finished executing, the Java runtime system automatically terminates any remaining daemon threads. This behavior allows daemon threads to provide support without blocking the JVM from exiting.

4.Limited Cleanup: Daemon threads should not be relied upon to perform critical operations that require proper cleanup or resource release. Since they can be abruptly terminated by the JVM, it is generally not recommended to perform critical operations or rely on finalizers within daemon threads.

To mark a thread as a daemon thread, you can use the setDaemon(true) method before starting the thread, like this:

Thread daemonThread = new Thread(new MyRunnable());
daemonThread.setDaemon(true);
daemonThread.start();Code language: JavaScript (javascript)

Program-1

To demonstrate the concept of a Daemon Thread. Create a custom thread class named MyDaemon that continuously prints a message indicating it is running. Set the thread as a daemon using the setDaemon(true) method before starting it.

//DeamonThreadDemo.java
class MyDaemon extends Thread {
    String name;
	MyDaemon(String name){
		this.name=name;
		this.setName(name);
	}	
	@Override
    public void run() {
	    while (true) {
            try {
                System.out.println(name+" Daemon thread is running.");
                Thread.sleep(1000);
				
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class DaemonThreadDemo {
    public static void main(String[] args) {
        MyDaemon daemonThread = new MyDaemon("Dev");
        daemonThread.setDaemon(true); // Set the thread as a daemon
        daemonThread.start();
		if(daemonThread.isDaemon())
			System.out.println(daemonThread.getName()+" is Daemon Thread");
		else
			System.out.println(daemonThread.getName()+" is not a Daemon Thread");
        
		System.out.println("Main thread exiting.");
    }
}

/*

D:\Threading>javac DaemonThreadDemo.java

D:\Threading>java DaemonThreadDemo
Dev is Daemon Thread
Main thread exiting.
Dev Daemon thread is running.

*/

Program-2

To demonstrate a daemon thread using the Runnable interface, where a mentor provides continuous guidance in the background while a student studies for a limited time, and the daemon thread automatically terminates when the main thread finishes.

//DaemonMentorDemo.java
class MentorRunnable implements Runnable {
    @Override
    public void run() {
        while (true) {
            System.out.println("Mentor providing guidance...");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class DaemonMentorDemo {
    public static void main(String[] args) {
        Thread mentorThread = new Thread(new MentorRunnable());
        mentorThread.setDaemon(true); // Set the mentor thread as a daemon
        mentorThread.start();

        // Simulating student activity
        for (int i = 1; i <= 5; i++) {
            System.out.println("Student studying...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Student finished studying. Exiting main thread.");
    }
}

/*

D:\MAHESH\BhavaThreading>javac DaemonMentorDemo.java

D:\MAHESH\BhavaThreading>java DaemonMentorDemo
Student studying...
Mentor providing guidance...
Student studying...
Mentor providing guidance...
Student studying...
Student studying...
Mentor providing guidance...
Student studying...
Student finished studying. Exiting main thread.

*/

Daemon threads can be useful in scenarios where background tasks need to be performed continuously without affecting the termination of the Java application.

Scroll to Top