Janitha Bandara
Janitha Bandara

Reputation: 11

Daemon And Non-Daemon Threads In Java

JVM in Java is responsible to create a Non-Daemon Thread when executing a Java program. Is it correct? If so, who is responsible to create Daemon Threads in Java? Programmers and JVM both create Non-Daemon Threads? Is it correct? Looking for a clear explanation.

Thanks in Advance.

Upvotes: 0

Views: 950

Answers (1)

Holger
Holger

Reputation: 298233

It doesn’t matter whether “the JVM” or “the programmer” started a thread. A thread is a daemon thread when setDaemon(true) has been called on it before starting or a daemon thread created the thread without calling setDaemon. That’s it.

The documentation of Thread also says:

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class).

There is no responsibility to create daemon threads. Marking a thread as daemon has only one implication which the documentation continues to explain:

The Java Virtual Machine continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

So, that’s the only implication; the existence of a non-daemon thread may prevent the JVM from terminating automatically, whereas threads marked as daemon do not.

Upvotes: 3

Related Questions