I am trying to understand how ReentrantLock works in java.
Lets consider a simple example below :
private ReentrantLock lock;
public void foo() {
lock.lock();
try{
...
}finally {
lock.unlock();
}
}
I was trying to figure out the call hierarchy of lock() method.
public void lock() {
sync.lock();
}
For FairSync :
final void lock() {
acquire(1);
}
For NonFairSync :
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
Both lock() methods call acquire() method with argument as 1.
In AbstractQueuedSynchronizer class :
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
static void selfInterrupt() {
Thread.currentThread().interrupt();
}
If current thread cannot acquire a resource (i.e. some another thread has acquired this resource) , then current thread has to wait. In this case ReentrantLock calls selfInterrupt() method.
Now my question is how interrupt() method can stop a thread which is equivalent to wait() method in synchronized ?
Also , after the resource has been released by another thread, how currentThread start automatically? ( After calling unlock() method by another thread which is internally calling sync.release(1);
)
I also tried to figure out how interrupt() method works from here but unable to find answer to my questions.