views:

623

answers:

4

Can anybody tell me what daemon threads are in Java?

+8  A: 

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.

PartlyCloudy
+5  A: 

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.

cletus
+5  A: 

A 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.

Jack
+2  A: 

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.
sateesh