why to use daemon threads if we can use normal threads instead. what is the thing that a daemon thread can do but normal thread can’t. because up to I know, there is not much difference in those two
Asked
Active
Viewed 226 times
0
-
1Answers on the "duplicate" emphasize _what_ more than _why_. The _why_ is just convenience. If your program has a thread that does not need to be cleanly shut down when the program ends, then making the thread a daemon saves you from having to write the code to shut it down. – Solomon Slow Oct 01 '19 at 13:13
-
1https://www.baeldung.com/java-daemon-thread – Conffusion Oct 01 '19 at 13:25
1 Answers
0
The Java VM will exit when the last non-daemon thread has finished. That is, a non-daemon thread will prevent the VM from exiting as long as it is running, whereas a daemon thread will not.
You would use a daemon thread for operations which make sense only as long as any non-daemon thread is running. One such example (used internally by the VM) is garbage collection.
A caveat with daemon threads is that the VM kills them off the hard way and does not even guarantee execution of finally
blocks. That makes daemon threads dangerous to use for any operations that have effects outside the process itself.

user149408
- 5,385
- 4
- 33
- 69