Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java threading - Daemon thread?

What will happen to a thread treated as Daemon?

What will be the effect of this to the thread?

What are the "can and can'ts" on the thread?

like image 795
Kevin Florenz Daus Avatar asked Feb 15 '26 02:02

Kevin Florenz Daus


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. Daemon threads are service providers for other threads running in the same process as the daemon thread

E.g Garbage Collection.

You can explicitly specify a thread created by a user thread to be a daemon thread by calling setDaemon(true) on a Thread object.


For your reference,

Note that the setDaemon() method must be called before the thread's start() method is invoked.Once a thread has started executing (i.e., its start() method has been called) its daemon status cannot be changed. To determine if a thread is a daemon thread, use the accessor method isDaemon().

like image 108
Saurabh Gokhale Avatar answered Feb 16 '26 15:02

Saurabh Gokhale


The main difference between a daemon thread and a non-daemon thread is that a program terminates when all non-daemon threads have terminated. So if you've got an active daemon thread and end your first thread, the program terminates. So you'd want to use a daemon thread for something you want to keep doing as long as the program is running.

like image 41
Jeremy Avatar answered Feb 16 '26 14:02

Jeremy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!