What are Java daemon threads and when to use them?

3

From the Java documentation I get the following snippet:

  

The Java Virtual Machine exits when the only running threads are all daemon threads.

But it's still not clear to me when I should set a thread as a daemon or not. Would anyone have a clearer definition, preferably with an example? Thanks!

    
asked by anonymous 18.12.2015 / 00:36

1 answer

3

Daemon threads stop when the main thread , which executes the main method, finishes executing and the program terminates.

If a thread < strong> is daemon , the Java process is still active and running, even when it reaches the end of the main method and the main thread ends.

By default, threads inherit the daemon property from the thread that created them. Because the main thread is daemon , the threads created in the program are not, either.

This makes programs that "do not end" common, especially because few understand this concept or forget to create a mechanism to end threads created during the execution of the main program.

    
18.12.2015 / 01:01