Reputation: 96
I am learning locking mechanism in java and found out some code which was given as a example in the LockSupport class in which the thread interrupting itself by calling interrupt() method. I am very confused that when a thread is already running then why it is interrupting itself.
I also want to clear all of you that I know what happen when the current thread is interrupted inside the catch block but I want to know what happen when running Thread interrupt itself.
code from LockSupport
sample code is here
class FIFOMutex {
private final AtomicBoolean locked = new AtomicBoolean(false);
private final Queue<Thread> waiters = new ConcurrentLinkedQueue<Thread>();
public void lock() {
boolean wasInterrupted = false;
Thread current = Thread.currentThread();
waiters.add(current);
// Block while not first in queue or cannot acquire lock
while (waiters.peek() != current || !locked.compareAndSet(false, true)) {
LockSupport.park(this);
if (Thread.interrupted()) // ignore interrupts while waiting
wasInterrupted = true;
}
waiters.remove();
if (wasInterrupted) // reassert interrupt status on exit
current.interrupt(); // Here it is interrupting the currentThread which
}
public void unlock() {
locked.set(false);
LockSupport.unpark(waiters.peek());
}
}
Upvotes: 0
Views: 417
Reputation: 533570
I want to know what happen when running Thread interrupt itself.
The interrupt flag is set to true nothing else. Nothing magically like triggering an exception or signalling the thread.
If you interrupt another thread which is blocked on a interruptable method, this would trigger that method to throw an InterruptedException.
When you call
Thread.interrupted()
this clears the flag and if you want set it again, you need to use interrupt()
to set the flag to true
so other code can detect that the thread was interrupted.
A simpler solution is to use Thread.currentThread().isInterrupted()
which doesn't clear the flag.
Upvotes: 2
Reputation: 16142
What happens is that Thread.interrupted() returns and clears the thread interrupted flag; the code just resets the flag at the end; essentially postponing thread interrupts for a while.
Upvotes: 0
Reputation: 121750
This is because Thread.interrupted()
not only checks that the interrupt flag is set on the current thread, it also clears it!
Therefore it is needed to re-enable it.
The better solution here is to use Thread.currentThread().isInterrupted()
, whih does not clear the interrupt flag.
And yes, it is only this: a flag. You don't "signal" a thread, in essence. When you receive an interrupted exception, it is because the callee will have detected that the interruption flag was set and thrown this exception (or "bubbled it up" from below). It doesn't happen "automagically".
In other words: in Java, thread interruption is a cooperative process.
Upvotes: 1