if main method completes the execution, what happens to any long running thread?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
When Java's main method finishes, the main thread dies, but the JVM does not necessarily exit at that moment. What happens next depends on the other threads that are still alive, especially whether they are user threads or daemon threads.
The Main Method Ends Only One Thread
main is just the entry point for the initial thread. Finishing main does not automatically stop every other thread in the process.
If you start another long-running thread, that thread keeps running after main returns, as long as it is a normal user thread.
This program does not exit when main ends because worker is a user thread.
User Threads Keep the JVM Alive
By default, new threads are user threads. The JVM stays alive as long as at least one user thread is running.
That means a long-running background computation, listener, or scheduler can keep the whole application alive even if main has already returned.
This is often exactly what server-style applications want. It is also why command-line tools sometimes appear to hang after printing their final line: some non-daemon thread is still alive somewhere in the process.
Daemon Threads Behave Differently
Daemon threads are background-support threads. They do not keep the JVM alive on their own.
Once main ends and no user threads remain, the JVM may exit even though the daemon thread is still looping.
So the rule is simple:
- user threads keep the JVM alive
- daemon threads do not
What This Means for Long-Running Work
If a thread is important and must finish cleanly, do not rely on it being a daemon. Use a user thread or, better, an executor service and controlled shutdown. The same idea applies to background schedulers started by frameworks: if they create non-daemon threads, they will keep the process alive until you stop them explicitly.
For example, with an executor:
That pattern is usually safer than manually managing raw threads.
Common Pitfalls
The biggest mistake is assuming the process exits automatically when main returns. It exits only if no user threads remain.
Another mistake is marking important work as daemon and then being surprised when it is cut off during JVM shutdown.
A third mistake is starting long-lived threads without a shutdown strategy. Even if the behavior is technically correct, the process can become hard to stop cleanly. Calling join() or coordinating executor shutdown is often the missing step in simple examples.
Summary
- When
maincompletes, only themainthread ends. - The JVM keeps running while any user thread is still alive.
- Daemon threads do not keep the JVM alive once user threads are gone.
- Long-running important work should not depend on daemon-thread survival.
- Prefer executors and explicit shutdown handling over unmanaged raw threads.

