Possible Duplicate:
What is Daemon thread in java
When are daemon threads useful?
I am confused with the difference between user threads and daemon threads in Java.
Can you tell me:
Java offers two types of threads: user threads and daemon threads. User threads are high-priority threads. The JVM will wait for any user thread to complete its task before terminating it. On the other hand, daemon threads are low-priority threads whose only role is to provide services to user threads.
A Daemon thread is a background service thread which runs as a low priority thread and performs background operations like garbage collection. JVM exits if only daemon threads are remaining. The setDaemon() method of the Thread class is used to mark/set a particular thread as either a daemon thread or a user thread.
JVM creates them and also looks after their termination. User threads are controlled by user. It is also said, we can convert a user thread to daemon thread by calling setDaemon() method.
The main difference between a user thread and a daemon thread is that your Java program will not finish execution until one of the user threads is live. JVM will wait for all active user threads to finish their execution before it shutdown itself.
a JVM will exit once the last non-jvm thread terminates. this means that if any of the threads you create is still running, the jvm will not shutdown. daemon threads are threads that do not prevent the JVM from shutting down. normally you'd use them for some background tasks which you dont want keeping your application up if the user requested it to shut down.
also, your question was already asked (and answered) here - What is Daemon thread in Java?
some common (from personal experience) use cases for daemon threads might include
2nd Question :
Daemon threads get automatically terminated when all normal threads have been terminated.
You can use daemon threads to do some housekeeping or cleaning in your application. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. GC thread is a daemon thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With