1.ReentrantLock的简介
ReentrantLock是concurrent包下的一个类,也是我们平常加锁使用的,ReentrantLock使用起来比较灵活。我们有时也用synchronized加锁。但是synchronized比较局限,只能修饰方法和代码块。ReentrantLock里最核心的就是AbstractQueuedSynchronizer,其实在并发编程里AbstractQueuedSynchronizer 是核心的地方,很多类都引用到AbstractQueuedSynchronizer。
2.我们看下ReentrantLock的构成
而公平FairSync和非公平NonfairSync都继承了Sync,而Sync继承了AbstractQueuedSynchronizer。所以很多并发核心的东西都继承了AQS。AQS接下来会去探索。先说下ReentrantLock的源码。接下说下ReentrantLock的使用。
3.ReentrantLock的使用
package Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {
private final ReentrantLock reentrantLock = new ReentrantLock();
private int count;
public void method() {
try {
reentrantLock.lock();
for (int i = 0; i <1000 ; i++) {
count ++ ;
}
System.out.println(Thread.currentThread().getName() + "----" + count);
} catch (Exception e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
}
public static void main(String[] args) throws Exception {
ReentrantLockExample reentrantLockExample = new ReentrantLockExample();
for (int i = 0; i < 10; i++) {
new Thread(reentrantLockExample::method).start();
}
Thread.sleep(10000);
}
}
结果如下,我们可以看到结果增加没有问题。线程是安全的。
没有加lock,我们可以发现,并不是我们想要的结果:
4.ReentrantLock源码分析
4.1 lock() 方法
直接看公平锁源码
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
final void lock() {
acquire(1);//模板模式调用AQS的acquire方法
}
/**
* 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方法,进入之后会调用FairSync的lock方法,然后我们发现这块其实用到了模板方法。会去调用AQS的模板方法acquire。我们看下源码:
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
在AQS里我们可以发现其实它会去调用子类的tryAcquire方法,这个方法锁的可重入的设计,也就是AQS的state值,这个属性可以说是ReentrantLock的灵魂设计。简简单单的通过一个字段就完成了加锁和解锁,保证每次只能一个线程能够执行。
/**
* The synchronization state.
*/
private volatile int state;
/**
* Returns the current value of synchronization state.
* This operation has memory semantics of a {@code volatile} read.
* @return current state value
*/
protected final int getState() {
return state;
}
/**
* Sets the value of synchronization state.
* This operation has memory semantics of a {@code volatile} write.
* @param newState the new state value
*/
protected final void setState(int newState) {
state = newState;
}
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
//获取当前状态
int c = getState();
//当state等于零时才进行设置当前线程并设置状态,并设置独占锁。
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
// 如果不为零,并且是当前线程继续加锁,则设置状态加1,以便释放锁的时候保持state没琐时一直为零。这也是ReentrantLock是可重入锁的原因。
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
接着看hasQueuedPredecessors()方法,这也是公平锁和非公平锁的区别,如果有新的线程获取锁,会把线程放入到链表的最后,不会去首先执行tryAcquire获取锁。
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 order
Node h = head;
Node s;
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}
接着回到AQS的tryAcquire方法的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;
//CAS设置到尾结点
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return 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;
}
}
}
}
acquireQueued保证线程在入队列之前再尝试获取一次锁。但是公平锁是先入队列的hasQueuedPredecessors方法做了限制,非公平锁是可以再次获取的。
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;
}
//如果未获取成功,则执行下面的方法,设置节点状态,并park暂停当前线程,当被唤醒时继续执行for循环
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
我们接下来看下shouldParkAfterFailedAcquire的方法,这里面涉及到节点的状态值。等待唤醒,取消等等。此方法执行成功之后会暂停线程方法
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
/*
* 跳过取消的节点
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
// 节点初始状态未-0 ,所以需要把初始节点设置为-1,变为等待唤醒。
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
private final boolean parkAndCheckInterrupt() {
//暂停线程,当唤醒是继续执行for循环
LockSupport.park(this);
return Thread.interrupted();
}
4.2 unlock() 方法
unlock调用是的AQS的release方法
public void unlock() {
sync.release(1);
}
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的tryRelease方法
protected final boolean tryRelease(int releases) {
// 将state减去1
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
// 如果为0将独占线程设置为null
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
然后就是唤醒线程,首先会把头节点状态设置为0,并从尾部向前查询。找到最靠近头部小于等于0的节点并唤醒。
private void unparkSuccessor(Node node) {
/*
* If status is negative (i.e., possibly needing signal) try
* to clear in anticipation of signalling. It is OK if this
* fails or if status is changed by waiting thread.
*/
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
/*
* Thread to unpark is held in successor, which is normally
* just the next node. But if cancelled or apparently null,
* traverse backwards from tail to find the actual
* non-cancelled successor.
*/
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);
}