javamultithreadingdaemon

java daemon thread and non-daemon thread


I am doing java past exam paper, and I have encounter the following question that is confusing me.

Which of the following are true? (Choose all that apply.)

A. When an application begins running, there is one daemon thread, whose job is to execute main().

B. When an application begins running, there is one non-daemon thread, whose job is to execute main().

C. A thread created by a daemon thread is initially also a daemon thread.

D. A thread created by a non-daemon thread is initially also a non-daemon thread.

The key answer is B,C,D, could anyone tell me why B,C is correct? Many thanks.


Solution

  • A. When an application begins running, there is one daemon thread, whose job is to execute main().

    This is incorrect. See below.

    B. When an application begins running, there is one non-daemon thread, whose job is to execute main().

    Correct. The JVM exits when the last non-daemon thread exits. If the main thread wasn't non-daemon then the JVM would start up and see that there were no non-daemon threads running and would shutdown immediately.

    So therefore the main thread must be a non-daemon thread. For a description of the different between daemon and non, see my answer here: Difference between a daemon thread and a low priority thread

    C. A thread created by a daemon thread is initially also a daemon thread.

    D. A thread created by a non-daemon thread is initially also a non-daemon thread.

    Both are correct. The thread gets its daemon status from the thread that spawned it by default. Daemon threads spawn other daemon threads. Non-daemon threads spawn other non-daemon threads. Looking at the code from Thread.init():

    Thread parent = currentThread();
    ...
    this.daemon = parent.isDaemon();
    

    If you want to change the daemon status then you have to do so before the thread is started.

    Thread thread = new Thread(...);
    // thread has the daemon status of the current thread
    // so we have to override it if we want to change that
    thread.setDaemon(true);
    // we need to set the daemon status _before_ the thread starts
    thread.start();