Learn Java daemon vs. non-daemon threads: termination impact & usage. Optimize concurrency efficiently.
Difference between Daemon and Non Daemon thread in Java :
Termination Behavior:
- Daemon Threads:
- A daemon thread is a thread that does not prevent the Java Virtual Machine (JVM) from exiting when the main thread (or other non-daemon threads) completes.
- If all remaining threads in a program are daemon threads, the JVM will exit, even if daemon threads are still running. Daemon threads are typically used for background tasks or services that are not critical to the application and can be terminated when the main program finishes.
- Non-Daemon Threads (User Threads):
Example Usage:
- Daemon Threads:
- Daemon threads are often used for tasks like garbage collection, monitoring, and other background tasks that don’t need to complete before the program exits.
- Non-Daemon Threads (User Threads):
- User threads are used for tasks that are integral to the application’s functionality and need to be completed before the program can safely terminate.
Creation:
- Daemon Threads:
- You can set a thread as a daemon thread using the
setDaemon(true)
method before starting it. By default, threads are non-daemon.
- You can set a thread as a daemon thread using the
- Non-Daemon Threads (User Threads):
- Threads are non-daemon by default.
Daemon Thread Java Example-1:
CrunchifyDaemonThreadGuide.java
package crunchify.com.tutorials; /** * @author Crunchify.com * Mastering Multithreading: Demystifying Daemon Threads in Java * * - daemon thread will continue running in the background indefinitely, * while the non-daemon thread will complete its loop and then the program will exit. * */ public class CrunchifyDaemonThreadGuide { public static void main(String[] args) { Thread crunchifyDaemonThread = new Thread(() -> { while (true) { System.out.println("Daemon thread running"); } }); crunchifyDaemonThread.setDaemon(true); crunchifyDaemonThread.start(); Thread crunchifyNonDaemonThread = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println("Non-daemon thread running"); } }); crunchifyNonDaemonThread.start(); System.out.println("Main thread exiting"); } }
setDaemon(true/false) ?
This method is used to specify that a thread is daemon thread.
public boolean isDaemon() ?
This method is used to determine the thread is daemon thread or not.
Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks.
Daemon Thread Java Example-2:
Here’s an explanation of the code:
- Class Definition: The class
CrunchifyDaemonThread
extends theThread
class, which means it can be used to create and manage threads. - Main Method: The
main
method serves as the entry point of the program. It does the following steps:- Prints a message indicating the start of the main method.
- Creates an instance of the
CrunchifyDaemonThread
class. - Sets the created thread as a daemon thread using the
setDaemon(true)
method. Daemon threads are threads that do not prevent the program from exiting. - Starts the daemon thread using the
start()
method. - The main thread then sleeps for 3 seconds using
Thread.sleep(3000)
to allow the daemon thread to execute. - Finally, it prints a message indicating the exit of the main method.
- Daemon Thread’s Run Method: The
run()
method is an overridden method from theThread
class that contains the logic to be executed by the daemon thread. It does the following:- Prints a message indicating the entry of the daemon thread’s run method.
- Prints information about the current thread (the daemon thread itself).
- Enters a loop that repeatedly sleeps for 1 second and then prints a message indicating the execution of the daemon thread.
- The loop runs indefinitely unless the thread is interrupted.
- A
finally
block ensures that a message is printed when the daemon thread’s run method exits.
CrunchifyDaemonThread.java
package crunchify.com.tutorials; /** * @author Crunchify.com * Mastering Multithreading: Demystifying Daemon Threads in Java * */ public class CrunchifyDaemonThread extends Thread { public static void main(String[] args) { System.out.println("Main Method Entry"); CrunchifyDaemonThread daemonThread = new CrunchifyDaemonThread(); daemonThread.setDaemon(true); // When false, (i.e. when it's a user thread), the Worker thread continues to run. // When true, (i.e. when it's a daemon thread), the Worker thread terminates when the main thread terminates. daemonThread.start(); try { Thread.sleep(3000); } catch (InterruptedException x) { x.printStackTrace(); } System.out.println("Main Method Exit"); } @Override public void run() { System.out.println("Daemon Method Entry"); try { System.out.println("In run Method: currentThread() is" + Thread.currentThread()); while (true) { try { Thread.sleep(1000); } catch (InterruptedException x) { x.printStackTrace(); } System.out.println("Daemon thread executing..." + Thread.currentThread()); } } finally { System.out.println("Daemon Method Exit"); } } }
Output1: (with t.setDaemon(true)):
Main Method Entry run Method Entry In run Method: currentThread() isThread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] Main Method Exit
When daemon thread is the only threads running in a program – as you see here JVM ends the program
finishing the thread.
Output2: (with t.setDaemon(false)):
Main Method Entry run Method Entry In run Method: currentThread() isThread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] Main Method Exit In run method..Thread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] ... ... ...
As you see here program doesn't exit
when it’s not a daemon thread.
Points to Note :
Any thread created by main thread, which runs main method in Java is by default non daemon because Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since main thread is a non daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by calling setDaemon(true)
.
Thread.setDaemon(true)
makes a Thread daemon but it can only be called before starting Thread in Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.