Monday, November 24, 2008

Daemon Threads in Java

Any Java thread can be a daemon thread. Daemon threads are service providers for other threads running in the same process as the daemon thread.

When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.

Daemon threads are sometimes called “service” threads. These are threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. An example of a daemon thread that is continuously running is the garbage collector thread. This thread is provided by the JVM.

The Thread Object

class HelloThread extends Thread {

public void run() {

try {

for ( ; ; ) { System.out.println("hello"); sleep(1000); }


catch(Exception e ){}


The normal thread

public class RegularThreader{public static void main(String[] args){
Thread hello = new HelloThread();
System.out.println("Sorry, I must be leaving destroy");

The Daemon Thread

public class DaemonThreader{

public static void main(String[] args) {

Thread hello = new HelloThread();


System.out.println("Sorry, I must be leaving");}}

Just the check the difference in the way ther run

1. In the first case the child thread runs continously

2. but the Daemon thread exits when the main thread is complete;

Free Domain Names @!