Daemon Thread

In java we have two types of Threads: Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread).

User thread is generally meant to run our program code. JVM doesn’t terminate unless all the user thread terminate.
On the other hand we have Daemon threads. Typically these threads are service provider threads. They should not be used to run your program code but some system code. These threads run parallel to your code but survive on the mercy of the JVM. When JVM finds no user threads it stops and all daemon thread terminate instantly. Thus one should never rely on daemon code to perform any program code.

For better understanding consider a well known example of Daemon thread: Java Garbage collector. Garbage collector runs as a daemon thread to reclaim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly.

If only daemon threads are active in the application, then JVM quit the program (At least one user thread is necessary for application to run in JVM).
setDaemon(boolean) method is used to mark any thread as daemon thread.

package com.G2.Thread;

public class DaemonThreadDemo extends Thread {

	public static void main(String[] args) {
		Thread t = new DaemonThreadDemo();
                // Set Thread to daemon
		t.setDaemon(true);
		t.start();
	}

	public void run(){
		for(int i=1;i<1000;i++){
			System.out.println(i);
		}
	}
}

In above program, if “t.setDaemon(true)“ statement is commented then program prints the number from 1 to 999. It is the normal execution. But when we uncomment that statement, it means that the main Thread is only User thread and “t” is daemon thread. And therefore the number will not be printed completely. As only daemon thread lasts, the JVM exits the program before completion.

Posted

in

by

Tags:


Related Posts

Comments

One response to “Daemon Thread”

  1. javin @ unix grep examples Avatar

    Nice post. I think main difference between daemon and non daemon thread is that in case of former JVM doesn’t wait for finishing execution. see here for more difference between daemon and non daemon threads in java

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading