User Threads vs Daemon Threads
What you'll learn: How user threads and daemon threads differ in their impact on JVM shutdown behavior.
The Fundamental Difference
In Java, every thread is classified as either a user thread or a daemon thread. The JVM's shutdown behavior hinges on this distinction: the JVM will only terminate when all user threads have completed. Daemon threads, on the other hand, do not prevent the JVM from exiting—if only daemon threads remain running, the JVM shuts down immediately, terminating those daemon threads abruptly.
By default, any thread you create is a user thread. User threads represent the "main work" of your application—tasks that must complete for your program to finish properly.
Daemon threads are designed for background support tasks that should run only as long as the application needs them. Think of daemon threads as "servants" to user threads: garbage collection, monitoring, or housekeeping tasks that don't need to finish if the main work is done.
The Analogy
Imagine a restaurant:
- User threads are the paying customers. The restaurant stays open as long as customers are dining.
- Daemon threads are the background staff (janitors, HVAC systems). When the last customer leaves, you turn off the lights and close—even if the janitor is mid-sweep.
Key Properties
- User threads keep the JVM alive
- Daemon threads do not keep the JVM alive
- When the last user thread finishes, all daemon threads stop immediately (no cleanup guarantees)
- Threads inherit daemon status from their parent thread by default
Implications for JVM Lifecycle
If your main thread (a user thread) completes but you've started other user threads, the JVM continues running. However, if you only have daemon threads remaining, the JVM exits—potentially leaving files half-written or connections unclosed.
Key Takeaway: User threads represent essential work that must complete before JVM shutdown; daemon threads provide background services that can be safely abandoned when no user threads remain.