Home > Software engineering >  why we can't call setDaemon(true) after starting thread?
why we can't call setDaemon(true) after starting thread?

Time:10-12

public class MyThread extends Thread {

    public void run() {
        System.out.println("Thread is running");
    }

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start(); 
        t1.setDaemon(true); // throw IllegalThreadStateException why ?
    }
}

CodePudding user response:

The Thread javadocs clearly state that setDaemon must be called before a thread is started1.

And according to my research, the Thread javadocs have always stated this. At least as far back to Java 1.1.4.

1 - But interestingly, the in the draft javadocs for Loom it states that the behavior of calling setDaemon after a thread has terminated is unspecified.


Why?

One possible reason is that if a thread's daemon status can change while it is alive, then it becomes difficult to determine when the JVM should exit. Consider what might happen when the last non-daemon thread terminates simultaneously with a daemon thread setting itself to be non-daemon. Does the JVM exit, or not?

If a running thread's daemon status can change, there is clearly potential for "races", and it is unclear how an application would mitigate against them ... unless the Java SE libraries provided some extra (probably complicated) infrastructure to deal with this.

If I was the designer for the Thread API, I would be asking why would a running thread need to switch (or be switched) between daemon and non-daemon state? I can't think of a realistic use case; i.e one that is implementing useful behavior, and that can't be implemented some other way.


Anyway, the spec says what it says, so the (original) reason for this is moot ... for all practical purposes.

CodePudding user response:

setDaemon() must be called before the Thread started. Have a look at What is a daemon thread in Java? more information about Daemon Threads.

  • Related