Java Thread setDaemon() Method

The Thread.setDaemon() method in Java is used to mark a thread as a daemon thread or a user thread.

Table of Contents

  1. Introduction
  2. setDaemon() Method Syntax
  3. Understanding Daemon Threads
  4. Examples
    • Basic Usage
    • Setting Daemon Threads
    • Daemon Threads in Multi-threaded Environment
  5. Real-World Use Case
  6. Conclusion

Introduction

The Thread.setDaemon() method is used to mark a thread as a daemon thread. Daemon threads are background threads that do not prevent the JVM from exiting when all user threads have finished executing.

setDaemon() Method Syntax

The syntax for the setDaemon() method is as follows:

public final void setDaemon(boolean on)

Parameters:

  • on: If true, marks this thread as a daemon thread; otherwise, marks this thread as a user thread.

Throws:

  • IllegalThreadStateException if this thread is alive.

Understanding Daemon Threads

Daemon threads are typically used for background tasks that support the main program. When all non-daemon threads (user threads) terminate, the JVM exits, and any remaining daemon threads are abruptly terminated.

Examples

Basic Usage

To demonstrate the basic usage of setDaemon(), we will create a thread and set it as a daemon thread.

Example

public class SetDaemonExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running...");
        });

        thread.setDaemon(true);
        thread.start();

        try {
            thread.join(); // Wait for the thread to finish
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main thread resumes after daemon thread completion.");
    }
}

Output:

Thread is running...
Main thread resumes after daemon thread completion.

Setting Daemon Threads

You can set multiple threads as daemon threads to perform background tasks.

Example

public class MultipleDaemonThreadsExample {
    public static void main(String[] args) {
        Runnable daemonTask = () -> {
            while (true) {
                System.out.println("Daemon thread is running...");
                try {
                    Thread.sleep(1000); // Simulate work
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        };

        Thread thread1 = new Thread(daemonTask);
        thread1.setDaemon(true);

        Thread thread2 = new Thread(daemonTask);
        thread2.setDaemon(true);

        thread1.start();
        thread2.start();

        System.out.println("Main thread is running...");

        // Main thread sleeps for a while to let daemon threads run
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

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

Output:

Main thread is running...
Daemon thread is running...
Daemon thread is running...
Daemon thread is running...
Daemon thread is running...
Daemon thread is running...
Main thread is exiting.

Daemon Threads in Multi-threaded Environment

In a multi-threaded environment, you can use daemon threads to handle background tasks that should not block the JVM from shutting down.

Example

public class MultiThreadDaemonExample {
    public static void main(String[] args) {
        Runnable userTask = () -> {
            System.out.println("User thread is running...");
            try {
                Thread.sleep(5000); // Simulate work
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("User thread has finished.");
        };

        Runnable daemonTask = () -> {
            while (true) {
                System.out.println("Daemon thread is running...");
                try {
                    Thread.sleep(1000); // Simulate work
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        };

        Thread userThread = new Thread(userTask);
        Thread daemonThread = new Thread(daemonTask);
        daemonThread.setDaemon(true);

        userThread.start();
        daemonThread.start();

        try {
            userThread.join(); // Wait for user thread to finish
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main thread is exiting after user thread completion.");
    }
}

Output:

User thread is running...
Daemon thread is running...
Daemon thread is running...
Daemon thread is running...
Daemon thread is running...
User thread has finished.
Main thread is exiting after user thread completion.

Real-World Use Case

Background Services

Daemon threads are often used for background services that should not block the JVM from shutting down. Examples include garbage collection, logging services, and background monitoring tasks.

Example

public class BackgroundServiceExample {
    public static void main(String[] args) {
        Thread loggingService = new Thread(() -> {
            while (true) {
                System.out.println("Logging service is running...");
                try {
                    Thread.sleep(1000); // Simulate work
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });

        loggingService.setDaemon(true);
        loggingService.start();

        System.out.println("Main application is running...");
        try {
            Thread.sleep(5000); // Simulate main application work
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main application is exiting.");
    }
}

Output:

Logging service is running...
Main application is running...
Logging service is running...
Logging service is running...
Logging service is running...
Logging service is running...
Main application is exiting.

Conclusion

The Thread.setDaemon() method in Java provides a way to mark a thread as a daemon thread. By understanding how to use this method, you can manage background tasks more effectively in your Java applications. Whether you are working with single-threaded or multi-threaded environments, the setDaemon() method offers used for ensuring that background services do not prevent the JVM from shutting down.

Comments