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());
}
}