Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are daemon threads useful?

Tags:

java

I know that Deamon threads background threads. We can create our own daemon thread by calling setDaemon(true).

My question is: why and when do we need to create our thread as daemon thread?

like image 338
user414967 Avatar asked Aug 15 '11 16:08

user414967


People also ask

What is the use of daemon thread give an example?

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.

What is a daemon thread and what are its use cases?

Daemon thread in Java is a low-priority thread that runs in the background to perform tasks such as garbage collection. Daemon thread in Java is also a service provider thread that provides services to the user thread.

What is the use of daemon thread in Python?

The threads which are always going to run in the background that provides supports to main or non-daemon threads, those background executing threads are considered as Daemon Threads. The Daemon Thread does not block the main thread from exiting and continues to run in the background.

What is the difference between daemon thread and user thread?

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.


1 Answers

The JVM exits when all the running threads are daemon threads. So imagine you're writing a simple game where your main method loops until you decide to quit. And imagine that at the start of the game, you start a thread that will endlessly poll some website to trigger alerts. You would like the JVM to exit when you decide to end the game. You don't want the endless polling to prevent the game from ending. So you make this polling thread a daemon thread.

like image 197
JB Nizet Avatar answered Oct 22 '22 02:10

JB Nizet