Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a daemon thread in Java?

Can anybody tell me what daemon threads are in Java?

like image 734
rocker Avatar asked Feb 06 '10 14:02

rocker


People also ask

What does thread daemon do?

daemon-This property that is set on a python thread object makes a thread daemonic. A daemon thread does not block the main thread from exiting and continues to run in the background. In the below example, the print statements from the daemon thread will not printed to the console as the main thread exits.

What is daemon and non daemon threads in Java?

Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks.

What's the difference between user thread and daemon thread?

Java offers two types of threads: user threads and daemon threads. User threads are high-priority threads. The JVM will wait for any user thread to complete its task before terminating it. On the other hand, daemon threads are low-priority threads whose only role is to provide services to user threads.

Is main thread a daemon thread in Java?

The main thread cannot be set as daemon thread. Because a thread can be set daemon before its running and as soon as the program starts the main thread starts running and hence cannot be set as daemon thread.


2 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(boolean) method to change the Thread daemon properties before the thread starts.

like image 104
b_erb Avatar answered Sep 30 '22 21:09

b_erb


A few more points (Reference: Java Concurrency in Practice)

  • When a new thread is created it inherits the daemon status of its parent.
  • When all non-daemon threads finish, the JVM halts, and any remaining daemon threads are abandoned:

    • finally blocks are not executed,
    • stacks are not unwound - the 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.

like image 42
sateesh Avatar answered Sep 30 '22 22:09

sateesh