🔷 ReentrantLock
2022年10月10日
- Java
🔷 ReentrantLock
1. 类注释
- 提供 2 种策略
- 公平模式
- 性能受到一定影响
- 可防止饥饿
- 保证公平性
- 非公平模式
- 顺序无法保证
- 公平模式
2. 类图
public class ReentrantLock implements Lock, java.io.Serializable {
// ...
}
3. 属性
private static final long serialVersionUID = 7373984872572414699L;
/** Synchronizer providing all implementation mechanics */
private final Sync sync;
4. 内部类
/**
* 继承自 AQS 的抽象类
*/
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
/**
* 抽象方法
*/
abstract void lock();
/**
* 非公平方式尝试获取锁
* 只要 c == 0 就参与竞争;若本身就是已经获锁的线程,修改 c 值
* 获锁成功,则返回 true
*/
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) { // c == 0 说明没有前置节点,CAS 修改 state 状态
if (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;
}
return false;
}
// 释放锁,若释放后 c == 0 返回 true;否则返回 false
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException(); // 当前线程非获锁线程,抛出异常
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
protected final boolean isHeldExclusively() {
return getExclusiveOwnerThread() == Thread.currentThread();
}
final ConditionObject newCondition() {
return new ConditionObject(); // 实现了 Condition 的类
}
// Methods relayed from outer class
final Thread getOwner() {
return getState() == 0 ? null : getExclusiveOwnerThread();
}
final int getHoldCount() {
return isHeldExclusively() ? getState() : 0;
}
final boolean isLocked() {
return getState() != 0;
}
/**
* 序列化相关
*/
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
setState(0); // reset to unlocked state
}
}
/**
* 非公平锁的实现类
*/
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
/**
* 只要 c == 0 就尝试 CAS 设置 c == 1,可以看出这里不管 CLH 在有没有等待的线程,都参与竞争
*/
final void lock() {
if (compareAndSetState(0, 1)) // 当前线程参与竞争
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1); // 竞争失败,入队
}
// 尝试获锁,只要 c == 0 就参与竞争 或 本身就是已经获锁的线程
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
/**
* 公平锁的实现类
*/
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
final void lock() {
acquire(1); // 不参与竞争,入队
}
/**
* 在尝试获锁前,需要保证 c == 0 且 CLH 队列无前置节点
*/
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
// c == 0 的情况下,且
// CLH 中没有前置节点,且
// 成功修改 c 的状态
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;
}
return false;
}
}
// 是 AQS 类的方法
// 有前置节点在队列中,返回 true
// 队列为空,或当前节点就是头节点,返回 false
public final boolean hasQueuedPredecessors() {
Node t = tail; // Read fields in reverse initialization order
Node h = head;
Node s;
return h != t && ((s = h.next) == null || s.thread != Thread.currentThread());
}
5. 构造函数
/**
* 默认创建非公平锁
*/
public ReentrantLock() {
sync = new NonfairSync();
}
/**
* 设置创建 公平锁 还是 非公平锁
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
6. 常见方法
lock()
public void lock() {
sync.lock(); // 调用的是 NonfairSync || FairSync 的方法
}
lockInterruptibly()
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1); // 调用的是 AQS 的方法
}
tryLock()
public boolean tryLock() {
return sync.nonfairTryAcquire(1); // 调用的是 非公平的尝试获锁,不论是公平锁还是非公平锁
}
tryLock(long timeout, TimeUnit unit)
public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout)); // AQS 的 方法
}
unlock()
public void unlock() {
sync.release(1); // AQS 的方法
}
newCondition()
public Condition newCondition() {
return sync.newCondition(); // Sync 的方法
}