JVM Termination and Daemon Threads
What you'll learn: How the JVM decides when to shut down based on which threads are still running.
The JVM's Exit Strategy
The JVM doesn't wait for all threads to finish before terminating—only for user threads. When the last user thread completes, the JVM exits immediately, regardless of whether daemon threads are still running. This means daemon threads can be abruptly stopped mid-execution without completing their work.
Think of it like a theater closing for the night: the building manager (JVM) waits for all paying customers (user threads) to leave, but doesn't wait for the janitors (daemon threads) to finish cleaning. Once the last customer exits, the lights go out—even if the janitors are mid-mop.
Why This Matters
Daemon threads are designed for background tasks that support user threads—logging, monitoring, garbage collection. Because they're support staff, the JVM assumes they're not essential to application correctness and can be safely abandoned when there's no more real work to do.
Important: Any resources daemon threads were managing (open files, network connections, unsaved data) may be left in an inconsistent state. Daemon threads receive no warning or chance to clean up gracefully.
Practical Implications
When your main thread and all other user threads finish, the JVM terminates instantly. If you have a daemon thread logging data to a file, it might have buffered entries that never get written. If it's processing a queue, unfinished items are lost.
This is why critical cleanup operations should never rely on daemon threads completing—use user threads with proper shutdown coordination instead.
Key Takeaway: The JVM exits as soon as the last user thread terminates, immediately halting any remaining daemon threads without allowing them to complete their work or perform cleanup.