Java.Multithreading.Can the main thread of a program be made a daemon?

🧩 Why?

Because:

  • The main thread is created by the JVM before your program code even runs.
  • You don’t get a chance to call setDaemon(true) on it.
  • Once a thread has started, you can no longer change its daemon status — it must be set before calling .start().

✅ From the Java Docs

“A daemon thread is a thread that does not prevent the JVM from exiting once all user (non-daemon) threads finish. The main thread is a user thread by default and cannot be made a daemon.”


💥 If You Try…

You can’t even get a reference to the main thread and make it daemon:

Thread.currentThread().setDaemon(true); // ❌ IllegalThreadStateException

It throws:

Exception in thread "main" java.lang.IllegalThreadStateException

Because the thread is already running!


🧠 Fun Fact

  • The JVM exits when all non-daemon threads finish, including the main thread.
  • So the main thread is the reason daemon threads get killed — not something you’d ever want to mark as daemon.

🔒 Summary

| Can main thread be daemon? | ❌ No | | Why not? | It’s already started by the time your code runs | | Can you change a thread’s daemon status after .start()? | ❌ No | | Daemon threads die when…| All non-daemon threads (like main) finish |

This entry was posted in Без рубрики. Bookmark the permalink.