There already are numerous answers; however, maybe I could shed a bit clearer light on this, as when I was reading about Daemon Threads, initially, I had a feeling, that I understood it well; however, after playing with it and debugged a bit, I observed a strange (to me) behaviour.
I was taught, that:
If I want the thread to die right after the main thread orderly finishes its execution, I should set it as Diamond.
What I tried:
- I created two threads from the
Main Thread
, and I only set one of those as adiamond
; - After orderly completing execution of the
Main Thread
, none of those newly created threads exited, but I expected, thatDaemon
thread should have been exited; - I surfed over many blogs and articles, and the best and clearest definition I found so far, comes from the Java Concurrency In Practice book, which very clearly states, that:
7.4.2 Daemon threads
Sometimes you want to create a thread that performs some helperfunction but you don’t want the existence of this thread to preventthe JVM from shutting down. This is what daemon threads are for.Threads are divided into two types: normal threads and daemon threads.When the JVM starts up, all the threads it creates (such as garbagecollector and other housekeeping threads) are daemon threads, exceptthe main thread. When a new thread is created, it inherits the daemonstatus of the thread that created it, so by default any threadscreated by the main thread are also normal threads. Normal threads anddaemon threads differ only in what happens when they exit. When athread exits, the JVM performs an inventory of running threads, and ifthe only threads that are left are daemon threads, it initiates anorderly shutdown. When the JVM halts, any remaining daemon threads areabandoned— finally blocks are not executed, stacks are not unwound—theJVM just exits. Daemon threads should be used sparingly—few processingactivities can be safely abandoned at any time with no cleanup. Inparticular, it is dangerous to use daemon threads for tasks that mightperform any sort of I/O. Daemon threads are best saved for“housekeeping” tasks, such as a background thread that periodicallyremoves expired entries from an in-memory cache.