I'm going through this tutorial on Java concurrency. There's a snippet provided in the linked article regarding the implementation of Thread.interrupted
.
The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method
Thread.interrupted
, interrupt status is cleared. The non-staticisInterrupted
method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag. By convention, any method that exits by throwing anInterruptedException
clears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.
And this is the corresponding Javadoc
java.lang.Thread
public static boolean interrupted()
Tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by this method. In other words, if this method were to be called twice in succession, the second call would return false (unless the current thread were interrupted again, after the first call had cleared its interrupted status and before the second call had examined it). A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.
Returns: true if the current thread has been interrupted; false otherwise.
See Also:
isInterrupted()
After reading both of these explanations of Thread.interrupted
, I'm confused about what the interruption flag is and where it is being cleared. Shouldn't a function like Thread.interrupted
be idempotent and not modify the state of the of the object it's being called on? I get that the Thread.interrupted
is static because it operates on the currentThread()
and Thread.isInterrupted
is an instance method because it operates on the Thread
instance it's being called on.