我们知道Java中实现锁的方式有synchronized,lock两种方式,synchronized是基于JVM层面实现。从Java1.5之后,我们可以通过API的方式实现锁了,即lock锁。下面我们深入了解lock是如何实现锁机制的。这里我们以ReentrantLock为例
首先我们看一下类的结构
我们再看看Lock接口中定义了那些方法
void lock();
void lockInterruptibly() throws InterruptedException;
boolean tryLock();
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
void unlock();
Condition newCondition();
OK,我们获取锁,释放锁的方法都在这个接口类中定义好了。那么ReentrantLock只需要实现这几个方法就行了。ReentrantLock提供了两种构造方法:
//我们使用默认无参构造方法用的是非公平锁的方式。
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
sync成员变量是ReentrantLock中定义的一个抽象的静态内部类
abstract static class Sync extends AbstractQueuedSynchronizer {
abstract void lock();
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
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;
}
return 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;
}
...
}
Sync有两个实现类NonfairSync(非公平锁),FairSync(公平锁):
/**
* Sync object for non-fair locks
*/
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
/**
* Performs lock. Try immediate barge, backing up to normal
* acquire on failure.
*/
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
/**
* Sync object for fair locks
*/
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
final void lock() {
acquire(1);
}
/**
* Fair version of tryAcquire. Don't grant access unless
* recursive call or no waiters or is first.
*/
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
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;
}
return false;
}
}
ReentrantLock实现lock()的方法:
public void lock() {
sync.lock();
}
首先我们先分析一下非公平模式下,锁的大体流程:
接下来,我们用源代码一步步分许上面的流程:
假设我们现在有A,B两个线程,同时调用ReentrantLock的lock方法
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
假设A线程首先执行 if (compareAndSetState(0, 1))
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
stateOffset即state在内存中的偏移量,这时A线程将state状态成功的从0改为1,接着执行方法
protected final void setExclusiveOwnerThread(Thread thread) {
exclusiveOwnerThread = thread;
}
将线程A设置成独享的线程。第一次获取锁的方式很简单,没什么好说的,总结下来就是通过CAS比较AQS中state,如果是0就更新值为1同时将当前线程赋值给exclusiveOwnerThread 结束。
接着线程B执行lock,首先if (compareAndSetState(0, 1))
这时state的值为1,更新不成功走到else逻辑中执行acquire(1);
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
在acquire(1)
执行if条件中线程B不死心,想再尝试获取一下锁,于是执行了
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
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;
}
return false;
}
如果在执行这个方法前线程A执行完成释放了锁,这时B就能成功获取lock,如果A没有释放锁,返回false,那么tryAcquire失败,执行acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
这里有两个方法,我们先分析addWaiter()
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
第一步先创建了一个Node,我们先看看这个Node的数据结构有啥东西:
static final class Node {
/** Marker to indicate a node is waiting in shared mode */
static final Node SHARED = new Node();
/** Marker to indicate a node is waiting in exclusive mode */
static final Node EXCLUSIVE = null;
/** waitStatus value to indicate thread has cancelled */
static final int CANCELLED = 1;
/** waitStatus value to indicate successor's thread needs unparking */
static final int SIGNAL = -1;
/** waitStatus value to indicate thread is waiting on condition */
static final int CONDITION = -2;
/**
* waitStatus value to indicate the next acquireShared should
* unconditionally propagate
*/
static final int PROPAGATE = -3;
volatile int waitStatus;
volatile Node prev;
volatile Node next;
volatile Thread thread;
Node nextWaiter;
}
这是个双向链表的数据结构,我们在AQS类中的成员变量中也看到了,头节点与尾节点
private transient volatile Node head;
private transient volatile Node tail;
那么再来看addWaiter
方法好理解了,首先将我们线程B封装成一个Node对象,此时tail节点为null,所以执行enq(node)
方法
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
这个方法里有个自旋逻辑,第一次自旋,如果tail==null,先构建一个新的node, 让tail和head节点都指向该node对象
第二次自旋tail != null, 将线程B的node节点的前置节点设置成head(tail)节点,然后进行CAS操作将tail节点设置成线程B的node节点
所以一句话总结enq方法就是完成双向链表的初始化的,并将节点添加到尾部。那么如果这时第三个线程来执行
addWaiter方法,tail就不为null, 执行代码块
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
这段代码就是将node添加到链表尾部,并将tail指向新的node。
接着下一步执行:
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
又是一个自旋,好吧,一步步分析。第一次自旋获取node的前置节点p,如果节点p是head节点,线程B想:“呀~我是第一个节点,不行我要再尝试获取一下锁,万一人家已经释放锁了,我就不用park了”,tryAcquire返回true,成功获取锁,这时设置head
private void setHead(Node node) {
head = node;
node.thread = null;
node.prev = null;
}
如果获取失败,那咋办呢,线程不能一直占着CPU资源不干事呀?没办法那就挂起线程,把CPU释放了,安静的排队去。。。
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
return true;
if (ws > 0) {
//循环将状态>0(CANCELLED)的前置节点从链表中移除
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
线程B的pre节点为head,head的waitStatus为0所以走这段逻辑,做CAS操作将head的waitStatus设置为SIGNAL的值-1
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
第一次自旋调用shouldParkAfterFailedAcquire
返回false,接着开始第二次自旋执行这时head的waitStatus== Node.SIGNAL
直接返回true。这时才挂起B线程
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
至此,线程B终于安静的躺在链表中,等待线程A执行完成释放锁后,将它给唤醒!
那么,线程A执行完成如何释放锁资源的呢,别着急,接着往下探。
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return 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;
}
相信现在大家看到这里,对上面的代码,应该没有什么疑惑了把,如果还有,那就将上面的分析再看一遍?。重点看一下唤醒线程的方法
private void unparkSuccessor(Node node) {
//head的waitStatus为-1,现将-1设置为0
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
//获取线程B的node节点
Node s = node.next;
if (s == null || s.waitStatus > 0) {
s = null;
//从后往前找waitStatus小于0的节点
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
LockSupport.unpark(s.thread);//唤起线程
}
好了,到这里已经带着大家把Lock的整个锁的获取与释放全部分析了一遍,希望对家有帮助。如果有什么不对的地方,欢迎指正。
若要转载,请表明出处!