本文主要是介绍【并发基础】ReentrantLock详解(二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在之前的AQS详解
、Condition详解
和ReentrantLock详解(一)
中我们分析了同步队列、condition队列和ReentrantLock中的同步器的底层原理,最后我们通过ReentrantLock对外的接口将整个流程串一遍,思路能够更为清晰,以便对Java的并发有进一步的理解。
构造方法
public ReentrantLock() {sync = new NonfairSync();
}public ReentrantLock(boolean fair) {sync = fair ? new FairSync() : new NonfairSync();
}
ReentrantLock默认创建的是非公平同步器,通过重载方法的fair参数可以指定公平策略。
lock()
public void lock() {sync.lock();
}
方法详解
//公平同步器
final void lock() {acquire(1);
}//非公平同步器
final void lock() {if (compareAndSetState(0, 1))setExclusiveOwnerThread(Thread.currentThread());elseacquire(1);
}
- 公平同步器的lock方法直接调用AQS的acquire(int)方法,即表明ReentrantLock是独占锁,同时表明lock方法不响应中断;
- 非公平同步器直接通过CAS尝试更新AQS的state变量,如果更新成功则表示当前线程获取到锁,否则同样调用acquire(int)方法。
AQS的acquire(int)会调用ReentrantLock的自定义同步器实现的tryAcquire方法,这里我们重点分析该方法,其他的已经在AQS详解中分析过。
//公平同步器
protected final boolean tryAcquire(int acquires) {final Thread current = Thread.currentThread();int c = getState();//0表示锁未被锁定if (c == 0) {//hasQueuedPredecessors判断当前线程是否是下一个可执行结点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;
}public final boolean hasQueuedPredecessors() {// The correctness of this depends on head being initialized// before tail and on head.next being accurate if the current// thread is first in queue.Node t = tail; // Read fields in reverse initialization orderNode h = head;Node s;return h != t &&((s = h.next) == null || s.thread != Thread.currentThread());
}
//非公平同步器
protected final boolean tryAcquire(int acquires) {return nonfairTryAcquire(acquires);
}//该方法由父类Sync实现
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) // overflowthrow new Error("Maximum lock count exceeded");setState(nextc);return true;}return false;}
由源码可知,在ReentrantLock中,使用AQS的state变量来判断锁是否被锁定,当state为0时,则表示锁未被锁定;当state不为0时,则表示锁已被某个线程持有,state的数值仅仅表示持有线程重入的次数,不可能有其他线程持有锁,因为ReentrantLock是独占的。
公平同步器和非公平同步器的实现差异仅仅在于是否调用了AQS的hasQueuedPredecessors方法
-
公平同步器调用hasQueuedPredecessors方法,判断当前线程是否是下一个可执行结点,然后才会使用CAS更新state状态。同时,只有state为0时,更新才能成功。当前线程如果已经持有该锁,则增加state的值,表示重入次数,当释放锁时会逐渐减少state的值,当state的值为0时才表示线程真正释放了锁。
-
非公平同步器直接使用CAS尝试更新state变量,其他的与公平同步器类似。
余下的就进入到了AQS的流程:
- 当获取锁成功后,当前进程会进行自我中断,当前状态处于非阻塞状态,因此仅仅是线程的中断标志被修改为true而已;
- 获取失败后,将当前线程构造为一个结点加入到同步队列的队尾中,自旋尝试获取锁,此时公平锁非公平锁的处理逻辑已经算是相同的了,因为AQS的acquireQueued方法需要判断当前结点的前驱结点是否为头结点,是头结点才会再次调用自定义同步器的tryAcquire方法。
lockInterruptibly()
public void lockInterruptibly() throws InterruptedException {sync.acquireInterruptibly(1);
}
该方法响应中断,调用AQS的acquireInterruptibly(int)方法
public final void acquireInterruptibly(int arg) throws InterruptedException {if (Thread.interrupted())throw new InterruptedException();if (!tryAcquire(arg))doAcquireInterruptibly(arg);
}
tryAcquire(arg)表明支持公平和非公平策略。doAcquireInterruptibly方法也是自旋尝试获取锁,获取不到则找到某个安全点进行等待,不过其响应中断,会抛出InterruptedException异常。
tryLock()
public boolean tryLock() {return sync.nonfairTryAcquire(1);
}
ReentrantLock的tryLock方法调用Sync的nonfairTryAcquire方法,该方法是非公平的,无论初始化时选择何种公平策略。
tryLock(long, TimeUnit)
public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
该方法调用AQS的tryAcquireNanos方法,支持响应中断和超时时间。
同时,其采用的公平策略,由初始化的fair参数决定。
public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException {if (Thread.interrupted())throw new InterruptedException();return tryAcquire(arg) || doAcquireNanos(arg, nanosTimeout);
}
这里详细分析下doAcquireNanos方法:
private boolean doAcquireNanos(int arg, long nanosTimeout) throws InterruptedException {if (nanosTimeout <= 0L)return false;//计算超时时间点final long deadline = System.nanoTime() + nanosTimeout;//将当前结点加入同步队列final Node node = addWaiter(Node.EXCLUSIVE);boolean failed = true;try {for (;;) {final Node p = node.predecessor();if (p == head && tryAcquire(arg)) {setHead(node);p.next = null; // help GCfailed = false;return true;}//超时则结束自旋,返回falsenanosTimeout = deadline - System.nanoTime();if (nanosTimeout <= 0L)return false;if (shouldParkAfterFailedAcquire(p, node) &&nanosTimeout > spinForTimeoutThreshold)LockSupport.parkNanos(this, nanosTimeout);if (Thread.interrupted())throw new InterruptedException();}} finally {if (failed)cancelAcquire(node);}
}
unlock()
public void unlock() {sync.release(1);
}
ReentrantLock的自定义同步器都未实现release方法,因此这里直接调用父类AQS的方法。
public final boolean release(int arg) {if (tryRelease(arg)) {Node h = head;if (h != null && h.waitStatus != 0)unparkSuccessor(h);return true;}return false;
}
ReentrantLock的自定义同步器Sync类实现了tryRelease方法:
protected final boolean tryRelease(int releases) {int c = getState() - releases;//当前线程未持有该锁,抛出IllegalMonitorStateException异常if (Thread.currentThread() != getExclusiveOwnerThread())throw new IllegalMonitorStateException();boolean free = false;//state减为0时,表示当前线程释放该锁if (c == 0) {free = true;setExclusiveOwnerThread(null);}setState(c);return free;
}
当前线程释放锁之后,会唤醒后继结点,头结点的waitStatus为0时表示已经唤醒过后继结点。
AQS的unparkSuccessor方法如下:
private void unparkSuccessor(Node node) {int ws = node.waitStatus;//将头结点的状态置为0if (ws < 0)compareAndSetWaitStatus(node, ws, 0);Node s = node.next;if (s == null || s.waitStatus > 0) {s = null;//从尾结点开始查找一个距离最近的可唤醒结点for (Node t = tail; t != null && t != node; t = t.prev)if (t.waitStatus <= 0)s = t;}if (s != null)LockSupport.unpark(s.thread);
}
小结
ReentrantLock是独占锁,同一时刻只有一个线程可以获得锁,其具体实现就是让同步队列中的头结点独占资源(将state加1,state代表重入次数),执行完任务后才会释放资源(将state减1),如果释放资源后state减到0则表示释放锁,然后会唤醒头结点的后继结点,后继结点对应的线程就有了获取资源的资格。
在公平锁的策略下,一定是后继结点获得资源;如果是非公平锁策略,其他线程调用lock
方法时,会立即去尝试获取资源,获取不成功才会添加到同步队列尾部,非公平策略可以增加吞吐量,但是存在线程饥饿的可能性。
同步队列的数据结构如下图:
如果此时同步队列的头结点线程调用Condition
对象的await
方法,会新建结点添加到等待队列的尾部,并且释放掉线程占有的全部资源(将state置为0),同时唤醒后继结点,后继结点会尝试获取资源,如果后继结点获取到资源,则将后继结点设置为新的头结点,意味着旧头结点出队列。
当同步队列的头节点调用signal
方法时(只有获取锁的线程才能调用signal
方法,而且signal
不释放锁),等待队列的头结点会出队列,并加入到同步队列的尾部,然后按照同步队列的逻辑等待获取锁。sianalAll
方法逻辑类似,只是操作对象是整个等待队列的结点。
这篇关于【并发基础】ReentrantLock详解(二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!