ReentrantLock 如何保证重入
SunRan

公平锁:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// java.util.concurrent.locks.ReentrantLock.FairSync#tryAcquire
if (c == 0) {
if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}

非公平锁:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// java.util.concurrent.locks.ReentrantLock.Sync#nonfairTryAcquire
if (c == 0) {
if (compareAndSetState(0, acquires)){
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}

从上面这两段都可以看到,有一个同步状态State来控制整体可重入的情况。StateVolatile修饰的,用于保证一定的可见性和有序性。

1
2
// java.util.concurrent.locks.AbstractQueuedSynchronizer
private volatile int state;

接下来看 State这个字段主要的过程:

  1. State初始化的时候为0,表示没有任何线程持有锁。
  2. 当有线程持有该锁时,值就会在原来的基础上+1,同一个线程多次获得锁是,就会多次+1,这里就是可重入的概念。
  3. 解锁也是对这个字段-1,一直到0,此线程对锁释放。
  • 本文标题:ReentrantLock 如何保证重入
  • 本文作者:SunRan
  • 创建时间:2022-01-06 15:51:43
  • 本文链接:https://lksun.cn/2022/01/06/ReentrantLock 如何保证重入/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论