LockInterruptibly simple inquiry about the method of ReentrantLock

Today, watching Lock, know that compared to synchronized, more than a fair lock, interruptible and other excellent performance.

But when it comes interruptible this feature, see a lot of blog is so described:

"Synchronized keyword with different threads can acquire a lock to respond to the interrupt, when the acquired lock the thread is interrupted, interrupt exception will be thrown, while the lock is released."

My understanding is that it should be when the lock has not been obtained thread is interrupted, interrupt exception will be thrown.

Read the source code under lockInterruptibly () of

level one

public void lockInterruptibly() throws InterruptedException {

    sync.acquireInterruptibly (. 1); 
}
The second layer
public final void acquireInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (!tryAcquire(arg))
doAcquireInterruptibly(arg);
}
Layer 3
private void doAcquireInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.EXCLUSIVE);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}


In fact, when you call lockInterruptibly (), the second layer to determine whether the current thread interrupt Thread.interrupted () If so, throw an exception
And a third layer for (;;) loop to determine whether the current thread has been interrupted flag. (Code identification characters section) 

so it is not understood by many of the blog, said this case.


Summary: lock in can interrupt feature is based on lockInterruptibly () method, which is for those who did not compete in the lock, and can be called external interrupt () to interrupt, so as to achieve not wait for lock resources, and not to compete lock

Guess you like

Origin www.cnblogs.com/xlblog/p/11531191.html