Showing posts with label Deamon Thread. Show all posts
Showing posts with label Deamon Thread. Show all posts

Monday, June 19, 2023

What is Daemon thread in Java and Difference to Non daemon thread - Tutorial Example

In Java, a thread is a lightweight unit of execution that allows concurrent processing within a program. Threads can be classified as daemon threads or non-daemon threads, depending on their behavior. Let me explain the difference between them.


1. Daemon Threads:

A daemon thread is a type of thread that runs in the background and does not prevent the Java Virtual Machine (JVM) from exiting when the main thread completes. In other words, a daemon thread is a low-priority thread that runs in the background to perform tasks that support the main application threads.


Characteristics of daemon threads:

Daemon threads are created using the setDaemon(true) method on a Thread object before starting it.

The JVM automatically terminates all daemon threads when there are no more non-daemon threads running.

Daemon threads should not perform critical operations or hold resources that need to be properly released since they may be abruptly terminated by the JVM.

Typical examples of daemon threads include garbage collection, background logging, or other maintenance tasks.

Here's an example that demonstrates a daemon thread in Java:


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();
                }
            }
        });

        daemonThread.setDaemon(true); // Set the thread as daemon
        daemonThread.start(); // Start the thread

        System.out.println("Main thread is finished.");
    }
}

In the example, we create a daemon thread that continuously prints a message to the console. The main thread completes its execution, but the daemon thread keeps running in the background. If you run this code, you'll see the "Daemon thread is running." message printed repeatedly until you terminate the program. Non-Daemon Threads: 

2. A non-daemon thread, also known as a user thread, is the opposite of a daemon thread. Non-daemon threads are designed to perform critical tasks and prevent the JVM from exiting as long as they are running. The JVM waits for all non-daemon threads to complete before terminating the program. 


Here's an example that demonstrates a non-daemon thread:


public class NonDaemonThreadExample {
    public static void main(String[] args) {
        Thread nonDaemonThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Non-daemon thread is running.");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        nonDaemonThread.setDaemon(false); // Set the thread as non-daemon (optional, since it's the default)
        nonDaemonThread.start(); // Start the thread

        System.out.println("Main thread is finished.");
    }
}

In this example, we create a non-daemon thread that prints a message to the console five times. The main thread waits for the non-daemon thread to complete its execution before terminating. If you run this code, you'll see both the non-daemon thread and the main thread messages printed alternately. 

Remember, if all the non-daemon threads complete their execution, the JVM will exit, even if there are daemon threads still running.