threads

Java Daemon Thread Example

In this example we shall show you how to make use Java Daemon Thread, A Thread 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 the run() method of class Thread. An instance of the subclass can then be allocated and started.
  2. Declare a class that implements the Runnable interface. That class then implements the run() 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 calling setDaemon(true).
  2. Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java, otherwise It will throw IllegalThreadStateException if corresponding Thread is already started and running.

3. Example:

3.1. Create a daemon thread:

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

DaemonThread.java:

package com.jcg;

/**
 * @author ashraf
 * 
 */
public class DaemonThread extends Thread {

	@Override
	public 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 another UserThread class which implements implements Runnable interface, we override the run() method to print a simple message User 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 new DaemonThreadTest class where we create a new DaemonThread 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 it
		DaemonThread daemonThread = new DaemonThread();
		daemonThread.setDaemon(true);
		daemonThread.start();

		// Create a new user thread and start it
		Thread userThread = new Thread(new UserThread());
		userThread.start();

	}

}

Output:

Daemon thread is running
User thread is running
Daemon thread is running
User thread is running
Daemon thread is running
User thread is running
Daemon thread is running
User thread is running
Daemon thread is running
User thread is running
Daemon thread is running
User Thread exiting

Now let’s see what will happen when mark the first daemon thread as non daemon user thread using setDaemon(false) and running the example again using the new UserThreadTest 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 it
		DaemonThread daemonThread = new DaemonThread();
		daemonThread.setDaemon(false);
		daemonThread.start();

		// Create a new user thread and start it
		Thread userThread = new Thread(new UserThread());
		userThread.start();

	}

}

Output:

Daemon thread is running
User thread is running
Daemon thread is running
User thread is running
Daemon thread is running
User thread is running
Daemon thread is running
User thread is running
Daemon thread is running
User thread is running
Daemon thread is running
User Thread exiting
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon 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

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.
Back to top button