Stefan
Stefan

Reputation: 1

interrupt() on Thread does not necessarily throw InterruptedExeption when join() is called

I have a main class which starts another thread like:

public class Main {
    public static void main(String[] args) {
        var worker = new Worker(Thread.currentThread());
        worker.start();
        try {
            worker.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

The other thread interrupts the main thread in its run()-method:

public class Worker extends Thread {

    private final Thread master;
    public Worker(Thread master) {
        this.master = master;
    }

    @Override
    public void run() {
        master.interrupt();
    }
}

I'd expect that the main thread throws always an InterruptedException since the documentation for join() states: "Throws: InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown."

But why does it only throw sometimes an InterruptedException?

I've inspected the join method and detected that the join() method checks first if a thread is alive before wait() is called. This could explain why an InterruptedExeption in not thrown?

Upvotes: 0

Views: 64

Answers (0)

Related Questions