Question

I'm having a bit of trouble understanding the semantics for Java's thread interrupted flag. My understanding is that the flag should only be true after a thread is interrupted, and once set to true will not be false again until the InterruptedException or equivalent has been caught or the flag is explicitly cleared with .interrupted(). Hence, I am not able to explain why the following program prints false:

Thread t = new Thread() {
    @Override
    public void run() {
        try {
            // While await()ing, another thread calls t.interrupt().
            new CyclicBarrier(2).await();
        } finally {
            // I believe I should still be interrupted here, but am not...
            System.out.println(Thread.currentThread().isInterrupted());
        }
    }
};

(Some details excluded for simplicity - assume it's ok for run() to throw exceptions.)

Was it helpful?

Solution

1) Open CyclicBarrier source and you will see that await() method resets interrupt flag by calling Thread.currentThread().interrupt(). See doWait() which is the actual impl of wait(). Actually this is what CyclicBarrier's javadoc says.

2) I don't agree that interrupt flag is cleared when InterruptedException has been caught

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top