java并发--ReentrantLock简单分析

xiaoxiao2025-09-03  231

ReentrantLock是java中并发包里的互斥锁,包含公平和非公平两种方式。内部是基于AQS实现的。实现了两个接口,Lock和Serializable。内部有个抽象类叫Sync。

private final Sync sync; /** * Base of synchronization control for this lock. Subclassed * into fair and nonfair versions below. Uses AQS state to * represent the number of holds on the lock. */ abstract static class Sync extends AbstractQueuedSynchronizer {

Sync集成了AQS,主要是负责锁的功能实现,在内部有两个实现类FairSync和NonFairSync,即公平锁和非公平锁。ReentrantLock的无参构造方法实例处理的就是NonFairSync,这个也是大部分时候使用的锁。

下面来看看ReentrantLock.lock方法

public void lock() { sync.lock(); }

可以看到,ReentrantLock是直接委托给内部的sync设置加锁功能。

sync.lock是一个抽象方法,下面我们看常用的NonFairSync.lock方法

final void lock() { if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); }

方法很简单,

首先用CAS把state设置为1,是否成功,成功的话就把当前线程设置为锁的拥有者不成功的话就调用acquire(1);  acquire是在AQS里定义的, public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }

可以看到,acquire首先会调用tryAcquire方法,AQS并不实现tryAcquire方法,tryAcquire方法要各个子类实现,我们来看NonFairSync的tryAcquire方法  

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; }

NonFairSync把tryAcquire直接转发到了nonfairTryAcquire方法。nonfairTryAcquire首先判断是否已经解锁,已经解锁的话就去尝试加锁,加锁成功的话就直接放回true。未解锁的话就判断这次操作是不是该线程重入操作,是重入操作的话就判断重入的操作次数是不是已经达到了Integer.MAX_VALUE,达到了就直接抛出异常,不然就再累加次数在把值设置给state属性。 下面再来看看acquireQueued(addWaiter(Node.EXCLUSIVE), arg)方法,没有获取到锁的线程阻塞的效果就是acquireQueued方法里的for循环。 addWaiter(Node.EXCLUSIVE)

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; }

---待更新

 

转载请注明原文地址: https://www.6miu.com/read-5035684.html

最新回复(0)