PriMe
PriMe

Reputation: 55

Why there is difference between ways interrupted and isInterrupted behave?

I was just going through Javadoc for interrupts. I do get the difference between two methods of Thread class: interrupted() and isInterrupted(). To quote the doc:

When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

What I do not get is why exactly has the behavior been kept so? Is there any reason why interrupted resets the status of current thread while isInterrupted doesn't of the thread it is called on?

Upvotes: 4

Views: 477

Answers (2)

xingbin
xingbin

Reputation: 28279

When you want to check if a thread has been interrupted, call thread.isInterrupted().

When you want to check if current thread has been interrupted, and if it is, you will handle & swallow it, call Thread.interrupted()

Upvotes: 1

Michael
Michael

Reputation: 44150

Thread.interrupted only applies to the current thread; it's a static method.

new Thread(() -> {
    while (true) {
        if (Thread.interrupted()) {
            break;
        }
        System.out.println("Running");
    }
});

It's convenient to clear the flag because the thread performing the check is expected to react to the interruption and deal with it somehow. If you want to reset the flag again, that's simple: just call interrupt.


isInterrupted is not a static method. It's designed to possibly be called by other threads.

Thread foo = new Thread(/*...*/);
foo.start();

//...

if (foo.isInterrupted()) 
{
   //do something
}

Firstly, other threads should not conceptually be able to tell foo that it's no longer interrupted. foo has to deal with interruption itself - other threads can't do it on foos behalf.

From an implementation perspective, if this method were to clear the flag automatically then this check-then-reset would have to be made atomic to avoid the thread foo reading the flag before it was reset. You would have to somehow share this mutex with the thread itself. This would make the isInterrupted method incredibly clunky to use.

Upvotes: 4

Related Questions