ReentrantLock源码解读
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ReentrantLock源码解读相关的知识,希望对你有一定的参考价值。
public class ReentrantLock implements Lock, java.io.Serializable { //ReentrantLock 有两种锁:公平锁,非公平锁 private final Sync sync; //并发包基本 都是基于aqs abstract static class Sync extends AbstractQueuedSynchronizer {...} //非公平锁 static final class NonfairSync extends Sync {...} //公平锁 static final class FairSync extends Sync {...} //默认非公平锁 public ReentrantLock() { sync = new NonfairSync(); } public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); }
}
先看看lock方法(非公平为例):
public void lock() { sync.lock(); } final void lock() { //这边首先要知道 state 是个锁定标志,0 说明是空闲 //如果空闲,修改为 1,设置当前线程获取锁 if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else //获取锁 acquire(1); } public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }
从字面理解:尝试获取锁,如果失败,则加入获取锁的队列,加入之前 需要先创建node节点 ,默认是独占式的,这边先声明aqs有两种锁模式(共享式,独占式),这里可以看到ReentrantLock是独占式的;
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()) { //考虑到ReentrantLock可以重入锁 ,获取锁跟释放锁都是成双成对出现, //对上线做一个校验,如果重入锁 返回true int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; }
如果获取 锁失败,回到acquire()方法,加入 获取锁队列,先看增加节点的方法:
private Node addWaiter(Node mode) { Node node = new Node(Thread.currentThread(), mode); Node pred = tail; if (pred != null) { //如果尾部node不为空,则把新增的node加到尾部,添加也是基于CAS //如果添加失败,说明出现并发,走enq node.prev = pred; if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } enq(node); return node; } private Node enq(final Node node) { //如果是FIFO,是从head的下个node开始 !! for (;;) { //这里是死循环,确保把新增的节点加到tail Node t = tail; if (t == null) { //如果尾部为空,new一个node为头部,尾部也为这个头部的节点 if (compareAndSetHead(new Node())) tail = head; } else { //把新增node加到尾部 node.prev = t; if (compareAndSetTail(t, node)) { t.next = node; return t; } } } }
节点创建完,然后是加到 队列
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()) //如果需要,借助JUC包下的LockSopport类的静态方法Park挂起当前线程。 //直到被唤醒。 interrupted = true; } } finally { if (failed) cancelAcquire(node); } } private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { int ws = pred.waitStatus; if (ws == Node.SIGNAL) return true; if (ws > 0) { do { node.prev = pred = pred.prev; } while (pred.waitStatus > 0); pred.next = node; } else { compareAndSetWaitStatus(pred, ws, Node.SIGNAL); } return false; } public static void park(Object blocker) { Thread t = Thread.currentThread(); setBlocker(t, blocker); unsafe.park(false, 0L);//0:永久 setBlocker(t, null); }
上面有提到Node,其实它是 aqs很重要的内部 结构
abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable { private transient volatile Node head; private transient volatile Node tail; private volatile int state; static final class Node { static final Node SHARED = new Node(); static final Node EXCLUSIVE = null; static final int CANCELLED = 1;//节点取消 static final int SIGNAL = -1;//节点等待触发 static final int CONDITION = -2;//节点等待条件 static final int PROPAGATE = -3;//节点状态需要向后传播。 //有上面四种状态 只有当前节点的前一个节点为SIGNAL时,才能当前节点才能被挂起。 volatile int waitStatus; volatile Node prev; volatile Node next; volatile Thread thread; Node nextWaiter; }
本文出自 “11898338” 博客,谢绝转载!
以上是关于ReentrantLock源码解读的主要内容,如果未能解决你的问题,请参考以下文章