1. 简介

  • ReentrantLocksynchronized关键字一样是可重入的独占锁,不过ReentrantLock提供比synchronized关键字更加灵活的获取锁和释放锁操作,并且支持等待多个条件,但ReentrantLock必须手动释放锁,否则很有可能造成死锁。在JDK6之后,synchronized加入了偏向锁、轻量级锁、自适应自旋、锁粗化、锁消除多种优化措施使它的性能提高了很多,通常情况下表现一般比ReentrantLock好,所以在能使用synchronized功能完成的操作时,尽量不要用ReentrantLock

  • ReentrantLock中大部分方法是间接调用了AbstractQueuedSynchronizer的方法,所以要想进一步探究其实现可以看看上一篇文章AbstractQueuedSynchronizer源码解析

2. 实现

继承关系

ReentrantLock实现了Lock接口

1
public class ReentrantLock implements Lock, java.io.Serializable {}

Lock接口提供了锁最基本的几个方法,实现该接口的类都重写了这些方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface Lock {
// 阻塞获取锁
void lock();
// 阻塞获取锁,可响应中断抛出异常
void lockInterruptibly() throws InterruptedException;
// 尝试获取锁
boolean tryLock();
// 尝试在指定时间内获取锁,获取不到则阻塞直到获取到锁返回true或超时返回false
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
// 释放锁
void unlock();
// 创建一个等待条件,获取锁的线程可以等待条件
Condition newCondition();
}

属性

ReentrantLock中最重要的属性就是syncsync是个实现抽象队列同步器AbstractQueuedSynchronizer抽象方法tryAcquiretryRelease的类的对象,其中tryAcquire方法决定了是否公平、重入的特性,而tryRelease方法对公平与非公平重入锁都适用。ReentrantLock中方法的实现基本都是调用sync的方法。

1
private final Sync sync;
Sync类继承关系
Sync类继承关系

Sync

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;

// 添加抽象方法lock
abstract void lock();

// 添加非公平获取尝试同步状态的方法,该方法体现非公平性与重入特性
final boolean nonfairTryAcquire(int acquires) {
// 获取当前线程
final Thread current = Thread.currentThread();
// 获取当前同步状态
int c = getState();
// 如果没有线程获取同步状态
if (c == 0) {
// 使用CAS方法获取同步状态,这里体现非公平性,因为没有判断等待队列里是否有其他线程在等待获取同步状态
if (compareAndSetState(0, acquires)) {
// 获取成功则设置独占线程
setExclusiveOwnerThread(current);
return true;
}
} // 否则当前线程已经获取过同步状态
else if (current == getExclusiveOwnerThread()) {
// 直接在原基础状态值加上acquires,体现重入性
int nextc = c + acquires;
// 如果nextc小于0表示线程获取锁的次数已经超过最大值
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
// 设置新的同步状态
setState(nextc);
return true;
}
return false;
}

// 重写tryRelease方法,对应公平与非公平锁都适用,体现重入性
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() {
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
return getExclusiveOwnerThread() == Thread.currentThread();
}

// 创建等待条件
final ConditionObject newCondition() {
return new ConditionObject();
}

// 获取独占锁的线程
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
}
}

### NonfairSync

// 非公平锁
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;

final void lock() {
// 如果当前线程能直接获取同步状态,则设置当前线程为独占线程
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else // 否则再调用acquire获取同步状态
acquire(1);
}

// 重写tryAcquire方法,调用nonfairTryAcquire方法
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}

FairSync

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;

final void lock() {
acquire(1);
}

// 重写tryAcquire方法,该方法体现公平性与重入特性
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
// 如果还没有线程获取同步状态
if (c == 0) {
// 判断等待队列中是否有后继线程,没有再使用CAS方法获取同步状态,
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
// 获取成功设置当前线程为独占线程
setExclusiveOwnerThread(current);
return true;
}
} // 否则当前线程已经获取过同步状态
else if (current == getExclusiveOwnerThread()) {
// 直接在原基础状态值加上acquires,体现重入性
int nextc = c + acquires;
// 如果nextc小于0表示线程获取锁的次数已经超过最大值
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
// 设置新的同步状态
setState(nextc);
return true;
}
return false;
}
}

构造函数

1
2
3
4
5
6
7
8
9
// 默认创建非公平锁
public ReentrantLock() {
sync = new NonfairSync();
}

// 根据指定参数创建公平或非公平锁
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}

获取锁方法

以下获取锁的方法都是调用Sync类的方法或或从抽象队列同步器继承的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 阻塞获取锁
public void lock() {
sync.lock();
}

// 中断获取锁
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}

// 尝试获取锁
public boolean tryLock() {
return sync.nonfairTryAcquire(1);
}

// 超时获取锁
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}

释放锁方法

1
2
3
public void unlock() {
sync.release(1);
}