0%

ReentrantLock源码学习

前言:JUC包,ReentrantLock源码学习

简介

ReentrantLock实现Lock接口,内部类继承了AQS,是一种可重入的独占锁,支持公平锁和非公平锁两种方式。

常用方法

lock():获取锁,获取不到会等待

unlock():释放锁

ReentrantLock(boolean):构造方法,布尔参数决定公平或不公平,默认false

类图

image-20200105220117835

image-20200105220128914

简单应用

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
/**
* @author shency
* @description: TODO
* @date: 2019/11/29
*/
public class MyThread implements Runnable{
ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
lock.lock();
System.out.println(Thread.currentThread().getName()+"获得锁");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"释放锁");
lock.unlock();
}
}

/**
* @author shency
* @description: TODO
* @date: 2019/11/29
*/
public class ReentrantLockTest {

public static void main(String[] args) {
MyThread myThead = new MyThread();
for(int i=0;i<100;i++){
new Thread(myThead).start();
}
}
}

源码学习

Sync

image-20200105220144040

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
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;

abstract void lock();
// 不公平,获取锁
final boolean nonfairTryAcquire(int acquires) {
// 获取当前线程
final Thread current = Thread.currentThread();
// 获取state
int c = getState();
// stat等于0,表示可以获得锁
if (c == 0) {
// CAS 设置State值为1(lock方法中传入的acquires固定为1)
if (compareAndSetState(0, acquires)) {
// 设置获得独占锁的线程为当前线程
setExclusiveOwnerThread(current);
return true;
}
}
// 如果当前线程已经获得锁,再次获得锁(可重入锁)
else if (current == getExclusiveOwnerThread()) {
// state++(lock方法中传入的acquires固定为1)
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
// 释放锁
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
// 只有当前线程能释放锁,否则抛出异常
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
// state==0才能释放锁
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
// 判断当前线程是否获得独占锁
protected final boolean isHeldExclusively() {
return getExclusiveOwnerThread() == Thread.currentThread();
}
// 创建Condition对象
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
// 获取锁
final void lock() {
// CAS设置将State从0设为1成功,则获取锁,失败调用AQS的acquire方法
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
// 重写AQS的tryAcquire方法
protected final boolean tryAcquire(int acquires) {
// 调用Sync nonfairTryAcquire方法,以不公平模式获取资源
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
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
// 获取锁,公平模式直接调用AQS的acquire方法
final void lock() {
acquire(1);
}
// 重写AQS的tryAcquire方法,公平
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
// c==0,标识目前锁尚未被其他线程获取
if (c == 0) {
// 调用AQS hasQueuedPredecessors方法,如果当前线程在CLH队列中有最高优先级才能执行获取锁的方法,这里就是公平锁与不公平锁的区别
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;
}
}

构造方法

默认不公平模式

1
2
3
4
5
6
7
public ReentrantLock() {
sync = new NonfairSync();
}

public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}

getHoldCount

返回加锁次数

1
2
3
public int getHoldCount() {
return sync.getHoldCount();
}

getOwner

返回获得锁的线程

1
2
3
protected Thread getOwner() {
return sync.getOwner();
}

getQueuedThreads

返回CLH队列的线程集合

1
2
3
protected Collection<Thread> getQueuedThreads() {
return sync.getQueuedThreads();
}

getQueueLength

返回CLH队列长度

1
2
3
public final int getQueueLength() {
return sync.getQueueLength();
}

getWaitingThreads

返回Condition队列的线程集合

1
2
3
4
5
6
7
protected Collection<Thread> getWaitingThreads(Condition condition) {
if (condition == null)
throw new NullPointerException();
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
throw new IllegalArgumentException("not owner");
return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
}

getWaitQueueLength

返回Condition队列长度

1
2
3
4
5
6
7
public int getWaitQueueLength(Condition condition) {
if (condition == null)
throw new NullPointerException();
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
throw new IllegalArgumentException("not owner");
return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
}

hasQueuedThread

判断线程是否在CLH队列中

1
2
3
public final boolean hasQueuedThread(Thread thread) {
return sync.isQueued(thread);
}

hasQueuedThreads

判断CLH队列是否有元素(线程)

1
2
3
public final boolean hasQueuedThreads() {
return sync.hasQueuedThreads();
}

hasWaiters

判断Condition队列是否有元素(线程)

1
2
3
4
5
6
7
public boolean hasWaiters(Condition condition) {
if (condition == null)
throw new NullPointerException();
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
throw new IllegalArgumentException("not owner");
return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
}

isFair

判断是否公平锁

1
2
3
public final boolean isFair() {
return sync instanceof FairSync;
}

isHeldByCurrentThread

判断当前线程是否获取到锁

1
2
3
public boolean isHeldByCurrentThread() {
return sync.isHeldExclusively();
}

isLocked

判断是否锁定

1
2
3
public boolean isLocked() {
return sync.isLocked();
}

lock

常用方法,获取锁

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

lockInterruptibly

同lock,可响应异常

1
2
3
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}

newCondition

创建Condition对象

1
2
3
public Condition newCondition() {
return sync.newCondition();
}

toString

转化为String格式

1
2
3
4
5
6
public String toString() {
Thread o = sync.getOwner();
return super.toString() + ((o == null) ?
"[Unlocked]" :
"[Locked by thread " + o.getName() + "]");
}

tryLock

调用Sync的nonfairTryAcquire获取锁

1
2
3
public boolean tryLock() {
return sync.nonfairTryAcquire(1);
}

限时的tryLock

1
2
3
4
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}

unlock

释放锁

1
2
3
public void unlock() {
sync.release(1);
}
-------------本文结束感谢您的阅读-------------