Daemon thread in Java

In addition to the working threads ,background threads are needed for doing background tasks.The concept Daemon thread in Java is intended for this purpose.

Daemon thread in Java

Daemon threads are supporting threads those are running at the back ground. These threads are usually intended to give support to other threads. The best example of daemon thread is the garbage collector.A thread can be chnaged to daemon by using the setDaemon(boolean arg) method of Thread class.To   make a thread  as daemon  ,setdaemon(true) needs to be called.A thread can be converted to daemon before it starts. In other words, once  the start() method is called , we should not use setDaemon() method on that thread.

A java process terminates when its main thread is over. Main thread  leaves its execution when all the child threads are over .So the main thread waits for all its child threads to complete .Once child threads are over main thread also exits.But it is not waiting for daemon threads.If there are only daemon threads then main thread is not waiting for them to get complete.And application gets terminated So the main thread will never wait to for a daemon thread ,for its termination. This concept will be clear once we examine the following program .

public class DaemonSample extends Thread {
public DaemonSample(String name) {
super(name);
}

public void run() {
int count = 0;
while (count < 10) { System.out.println("Number = " + count); count++; try { sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { DaemonSample sample = new DaemonSample("Thread1"); sample.setDaemon(true); sample.start(); } }

In this case the sample.setDaemon(true) makes the child thread daemon.So child thread is not starting(Before starting the daemon child thread , main thread exits.).So no numbers were printed in the console.If we remove the sample.setDaemon(true) then numbers will be printed

See Related Discussions

Threading Basics

Thread Safety in Java

Thread Communication in Java

Thread Priorities in Java

The join() method in Threading

The yield() method in Threading

The sleep() method in threading

Thread pool executor in java

Thread pools in Java

Thread Dead lock in Java

Thread Live lock in Java