Tuesday, November 5, 2013

Can anybody tell me what daemon threads are in Java?
share|improve this question
3 
The Thread javadoc describes what they are: java.sun.com/javase/6/docs/api/java/lang/Thread.html – skaffman Feb 6 '10 at 14:54

15 Answers

A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.
You can use the setDaemon() method to change the Thread daemon properties.
share|improve this answer
39 
For posterity, setDamon(boolean) can only be called before the thread has been started. By default the thread inherits the daemon status of its parent thread. –  Gray Nov 30 '11 at 13:47
A few more points (Reference: Java Concurrency in Practice)
  • When a new thread is created it inherits the daemon status of its parent.
  • Normal thread and daemon threads differ in what happens when they exit. When the JVM halts any remaining daemon threads are abandoned: finally blocks are not executed, stacks are not unwound - JVM just exits. Due to this reason daemon threads should be used sparingly and it is dangerous to use them for tasks that might perform any sort of I/O.
share|improve this answer
13 
The second point is very important. –  dimo414 Jan 19 at 17:38
1 
Why shouldn't daemon threads be used for I/O? Is it a concern about BufferedWriters etc not being flushed?–  Paul Cager Jul 26 at 10:04
 
@PaulCager Yeah, they can just get cut off at the knees in the middle of a write/read as well. –  CruncherSep 11 at 17:33
I think you mean "daemon" rather than "demon". Traditionally daemon processes in UNIX were those that were constantly running in background, much like services in Windows.
A daemon thread in Java is one that doesn't prevent the JVM from exiting. Specifically the JVM will exit when only daemon threads remain. You create one by calling the setDaemon() method on Thread.
Have a read of Daemon threads.
share|improve this answer
2 
your link is dead at this point of time, perhaps you want to update? anyway, +1 for you. –  Jasonw Jul 6 '12 at 8:04
 
link works for me –  Jeshurun Jun 26 at 6:59
All the above answers are good. Here's a simple little code snippet, to illustrate the difference. Try it with each of the values of true and false in setDaemon.
public class DaemonTest {

    public static void main(String[] args) {
        new WorkerThread().start();
        try {
            Thread.sleep(7500);
        } catch (InterruptedException e) {}
        System.out.println("Main Thread ending") ;
    }

}
class WorkerThread extends Thread {

    public WorkerThread() {
        setDaemon(true) ;   // When false, (i.e. when it's a user thread),
                // the Worker thread continues to run.
                // When true, (i.e. when it's a daemon thread),
                // the Worker thread terminates when the main 
                // thread terminates.
    }

    public void run() {
        int count=0 ;
        while (true) {
            System.out.println("Hello from Worker "+count++) ;
            try {
                sleep(5000);
            } catch (InterruptedException e) {}
        }
    }
}
share|improve this answer
1 
This example clearly explains the concept of demon threads! –  om39a Jul 26 '12 at 10:34
 
@russ Really Nice Demonstration with example –  Mr.Chowdary Apr 16 at 13:41
 
@russ Good code snippet! I had to define WorkerThread class as static though. –  xli Oct 31 at 20:13
daemon thread is a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.
When your program only have damon threads remaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.
You can specify that a Thread is a demon one by using setDaemon method, they usually don't exit, neither they are interrupted.. they just stop when application stops.
share|improve this answer
Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits.
For example, the HotJava browser uses up to four daemon threads named "Image Fetcher" to fetch images from the file system or network for any thread that needs one.
Daemon threads are typically used to perform services for your application/applet (such as loading the "fiddley bits"). The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated. Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution.
setDaemon(true/false) ? This method is used to specify that a thread is daemon thread.
public boolean isDaemon() ? This method is used to determine the thread is daemon thread or not.
Eg:
public class DaemonThread extends Thread {
    public void run() {
        System.out.println("Entering run method");

        try {
            System.out.println("In run Method: currentThread() is" + Thread.currentThread());

            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException x) {}

                System.out.println("In run method: woke up again");
            }
        } finally {
            System.out.println("Leaving run Method");
        }
    }
    public static void main(String[] args) {
        System.out.println("Entering main Method");

        DaemonThread t = new DaemonThread();
        t.setDaemon(true);
        t.start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException x) {}

        System.out.println("Leaving main method");
    }

}
OutPut:
C:\java\thread>javac DaemonThread.java

C:\java\thread>java DaemonThread
Entering main Method
Entering run method
In run Method: currentThread() isThread[Thread-0,5,main]
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
Leaving main method

C:\j2se6\thread>
share|improve this answer

No comments: