threads

Java Daemon Thread Example

Photo of Ashraf SarhanAshraf SarhanNovember 3rd, 2014Last Updated: November 25th, 2014
159 4 minutes read

In this example we shall show you how to make use JavaDaemon Thread, AThread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads (User, Daemon) of execution running concurrently.

Daemon Thread is typically used to provide a general service in the background as long as the program is running like the garbage collector thread. When a Java Virtual Machine starts up, there is usually a single user (non-daemon) thread which typically calls the method named main of some designated class. The Java Virtual Machine continues to execute threads until all threads that are not daemon threads have died, JVM doesn’t wait for daemon threads to finish their execution. As soon as last non daemon thread finished, JVM terminates no matter how many daemon thread exists or running.

1. Differences between User and Daemon thread:

  1. JVM doesn’t wait for any daemon thread to finish before exiting.
  2. Daemon Thread is treated differently than User Thread when JVM terminates, finally blocks are not called, Stacks are not unwounded and JVM just exits.

2. Ways to create a thread:

There are two ways to create a new thread of execution:

  1. Declare a class to be a subclass of Thread. This subclass should override therun() method of class Thread. An instance of the subclass can then be allocated and started.
  2. Declare a class that implements theRunnable interface. That class then implements therun() method. An instance of the class can then be allocated and started.

Tip

  1. Thread inherits its daemon nature from the parent Thread which creates it and since the main thread is a non daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by callingsetDaemon(true).
  2. Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java, otherwise It will throwIllegalThreadStateException if corresponding Thread is already started and running.

3. Example:

3.1. Create a daemon thread:

We create a newDaemonThread class which extend Thread class and we override the run() method to print a simple messageDaemon thread is running on the console.

DaemonThread.java:

package com.jcg;/** * @author ashraf *  */public class DaemonThread extends Thread {@Overridepublic void run() {try {while (true) {System.out.println("Daemon thread is running");Thread.sleep(1000);}} catch (InterruptedException ie) {ie.printStackTrace();} finally {System.out.println("Daemon Thread exiting"); // never called}}}

3.2. Create a user thread:

This time, we create anotherUserThread class which implements implements Runnable interface, we override the run() method to print a simple messageUser thread is running five times on the console.

UserThread.java:

package com.jcg;/** * @author ashraf *  */public class UserThread implements Runnable {public void run() {try {for (int i = 0; i < 5; i++) {System.out.println("User thread is running");Thread.sleep(1000);}} catch (InterruptedException ie) {ie.printStackTrace();} finally {System.out.println("User Thread exiting");}}}

3.3. Run the example:

We create a newDaemonThreadTest class where we create a newDaemonThread and mark it as a daemon thread using setDaemon(true) then start it. Also, we create another user thread which will die after printing five messages. We will notice that when the user thread die, the JVM terminates the running daemon thread and it will die as well.

DaemonThreadTest.java:

package com.jcg;/** * @author ashraf *  */public class DaemonThreadTest {/** * @param args */public static void main(String[] args) {// Create a new daemon thread and start itDaemonThread daemonThread = new DaemonThread();daemonThread.setDaemon(true);daemonThread.start();// Create a new user thread and start itThread userThread = new Thread(new UserThread());userThread.start();}}

Output:

Daemon thread is runningUser thread is runningDaemon thread is runningUser thread is runningDaemon thread is runningUser thread is runningDaemon thread is runningUser thread is runningDaemon thread is runningUser thread is runningDaemon thread is runningUser Thread exiting

Now let’s see what will happen when mark the first daemon thread as non daemon user thread usingsetDaemon(false) and running the example again using the newUserThreadTest class. We will notice that the user thread has died and the JVM still waits for daemon thread to finish its execution, it doesn’t terminates the running daemon thread.

UserThreadTest.java:

package com.jcg;/** * @author ashraf *  */public class UserThreadTest {/** * @param args */public static void main(String[] args) {// Create a new daemon thread and start itDaemonThread daemonThread = new DaemonThread();daemonThread.setDaemon(false);daemonThread.start();// Create a new user thread and start itThread userThread = new Thread(new UserThread());userThread.start();}}

Output:

Daemon thread is runningUser thread is runningDaemon thread is runningUser thread is runningDaemon thread is runningUser thread is runningDaemon thread is runningUser thread is runningDaemon thread is runningUser thread is runningDaemon thread is runningUser Thread exitingDaemon thread is runningDaemon thread is runningDaemon thread is runningDaemon thread is runningDaemon thread is running

4. Download the Source Code of this example:

This was an example of Java Daemon Thread.

Download
You can download the full source code of this example here:JavaDaemonThreadExampleCode.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Ashraf SarhanAshraf SarhanNovember 3rd, 2014Last Updated: November 25th, 2014
159 4 minutes read
Photo of Ashraf Sarhan

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.

Related Articles

Bipartite Graph

Return a value from a thread

November 11th, 2012
Bipartite Graph

Java Thread Join Example

February 9th, 2015
Bipartite Graph

CountDownLatch example

November 11th, 2012
Bipartite Graph

BlockingQueue example

November 11th, 2012
Bipartite Graph

CyclicBarrier example

November 11th, 2012
Bipartite Graph

Bounded work queue example

November 11th, 2012
Bipartite Graph

Unbounded work queue example

November 11th, 2012