假设场景
有10件商品,同时来30个人并发购买,不加锁的情况下会超出现超卖,加上lock锁后就防止了超卖
public class ReentrantLockTest1 {
private CyclicBarrier barrier = new CyclicBarrier(30);
private ReentrantLock lock = new ReentrantLock();
//商品数量
private int num = 10;
//购买商品
public void buy() {
try {
//栅栏同步所有线程 目的是规避线程的启动延迟时间
barrier.await();
lock.lock();
if (num > 0) {
System.out.println(Thread.currentThread().getName() + " 买到商品");
num--;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ReentrantLockTest1 test = new ReentrantLockTest1();
List<Thread> threadList = new ArrayList<>();
for (int i = 0; i < 30; i++) {
Thread thread = new Thread(() -> {
test.buy();
});
threadList.add(thread);
}
for (Thread thread : threadList) {
thread.start();
}
带着问题看源码
- ReentrantLock是怎么加锁和解锁的
- ReentrantLock是怎么实现可重入的
ReentrantLock是怎么加锁的? ReentrantLock#lock
/**
* Acquires the lock.
*(获取一个锁)
*
* <p>Acquires the lock if it is not held by another thread and returns
* immediately, setting the lock hold count to one.
*(获得锁如果它没有被另外一个线程持有,然后方法立刻返回,设置锁持有计数为1)
*
* <p>If the current thread already holds the lock then the hold
* count is incremented by one and the method returns immediately.
*(如果当前线程已经获得锁那么锁持有计数会被增加1然后方法立刻返回)
*
* <p>If the lock is held by another thread then the
* current thread becomes disabled for thread scheduling
* purposes and lies dormant until the lock has been acquired,
* at which time the lock hold count is set to one.
*(如果锁由另一个线程持有,则当前线程变为为线程调度目的禁用,并处于休眠状态,直到已获取锁,此时锁定保持计数设置为1)
*/
public void lock() {
sync.lock();
}
内部调用了sync的lock方法,可以看到ReentrantLock将加锁的功能托管给了内部的Sync类
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
/**
* Performs {@link Lock#lock}. The main reason for subclassing
* is to allow fast path for nonfair version.
*/
abstract void lock();
... 省略Sync剩余代码
查看ReentrantLock的默认构造方法,可以发现默认使用了NonfairSync(非公平锁)作为Sync类的实现
/**
* Creates an instance of {@code ReentrantLock}.
* This is equivalent to using {@code ReentrantLock(false)}.
*/
public ReentrantLock() {
sync = new NonfairSync();
}
查看NonfairSync(非公平锁)的sync方法
/**
* 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
//如果没有抢到锁则调用AbstractQueuedSynchronizer(aqs)的acquire方法
acquire(1);
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
调用compareAndSetState方法,尝试获取锁,如果没有线程持有锁将成功获取到锁并设置锁的所有者线程为当前线程,
否则将调用调用AbstractQueuedSynchronizer(aqs)的acquire方法进行获取锁
AbstractQueuedSynchronizer#acquire
/**
* Acquires in exclusive mode, ignoring interrupts. Implemented
* by invoking at least once {@link #tryAcquire},
* returning on success. Otherwise the thread is queued, possibly
* repeatedly blocking and unblocking, invoking {@link
* #tryAcquire} until success. This method can be used
* to implement method {@link Lock#lock}.
* (在独占模式下获取,忽略中断。通过调用至少一次tryAcquire来实现,返回成功。否则线程将排队,可能
* 反复阻塞和解除阻塞,调用tryAcquire直到成功。这个方法可以被用来实现Lock的lock方法)
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquire} but is otherwise uninterpreted and
* can represent anything you like.
* (acquire方法参数。此值传递给{@link#tryAcquire}但在其他方面不受解释,并且可以代表任何你喜欢的东西)
*/
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
AbstractQueuedSynchronizer#tryAcquire
/**
* Attempts to acquire in exclusive mode. This method should query
* if the state of the object permits it to be acquired in the
* exclusive mode, and if so to acquire it.
*(尝试以独占模式获取。此方法应检查在独占模式下对象的当前状态是否允许被获取锁,如果允许的话,就去获取它。)
*
* <p>This method is always invoked by the thread performing
* acquire. If this method reports failure, the acquire method
* may queue the thread, if it is not already queued, until it is
* signalled by a release from some other thread. This can be used
* to implement method {@link Lock#tryLock()}.
*(这个方法经常被线程执行acquire方法时调用。如果这个方法返回失败,如果线程尚未排队,acquire方法则可以将其排 * 队,直到它从其他线程释放的信号中唤醒。这可以用来实现Lock#tryLock方法)
*
* <p>The default
* implementation throws {@link UnsupportedOperationException}.
*(默认实现抛出UnsupportedOperationException)
*
* @param arg the acquire argument. This value is always the one
* passed to an acquire method, or is the value saved on entry
* to a condition wait. The value is otherwise uninterpreted
* and can represent anything you like.
*(acquire方法的参数,此值经常是传递给acquire方法的值,或者是condition wait下entry里的值。该值在其他方 * 面是不受解释的,可以表示任何您喜欢的内容)
* @return {@code true} if successful. Upon success, this object has
* been acquired.
*(如果成功将返回true。一旦成功,这个对象已经被获取)
* @throws IllegalMonitorStateException if acquiring would place this
* synchronizer in an illegal state. This exception must be
* thrown in a consistent fashion for synchronization to work
* correctly.
*(抛出IllegalMonitorStateException异常表示如果获取将使此同步器处于非法状态。必须以一致的方式引发此异 * 常,同步才能正常工作)
* @throws UnsupportedOperationException if exclusive mode is not supported
*(抛出UnsupportedOperationException异常表示不支持独占模式)
*/
protected boolean tryAcquire(int arg) {
throw new UnsupportedOperationException();
}
AbstractQueuedSynchronizer的tryAcquire默认抛出异常,表示这个方法需要子类去实现,查看NonfairSync的实现
NonfairSync#tryAcquire
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
调用了父类Sync的nonfairTryAcquire方法
Sync#nonfairTryAcquire
/**
* Performs non-fair tryLock. tryAcquire is implemented in
* subclasses, but both need nonfair try for trylock method.
* (非公平的tryLock, tryAcquire的子类实现,并且同时要满足实现trylock方法的非公平获取)
*/
final boolean nonfairTryAcquire(int acquires) {
//获取当前线程
final Thread current = Thread.currentThread();
//获取当前的状态 AbstractQueuedSynchronizer中的state
int c = getState();
//判断当前state状态是不是0,如果是0表示当前没有人持有锁,则进行抢占锁的操作
if (c == 0) {
//尝试原子修改state来获得锁
if (compareAndSetState(0, acquires)) {
//如果成功修改state为acquires,将锁的持有线程设置为当前线程
setExclusiveOwnerThread(current);
return true;
}
}
//如果锁已经被持有 并且持有锁的线程是当前线程 将state设置为 原来的state + acquires 这段代码是实 现可重入锁的关键
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;
}
回到AbstractQueuedSynchronizer的acquire方法
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
如果 tryAcquire 成功了,则方法结束,表示当前线程成功持有到锁,否则将调用 AbstractQueuedSynchronizer#acquireQueued 方法
acquireQueued的第一个参数Node, 其生成方法为AbstractQueuedSynchronizer#addWaiter
/**
* Creates and enqueues node for current thread and given mode.
* (创建并且将node放入队列)
* @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
* @return the new node
*/
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) {
//当前节点的前一个节点设置为tail节点
node.prev = pred;
//将当前节点设置为tail节点
if (compareAndSetTail(pred, node)) {
//前tail节点的next节点设置为当前节点
pred.next = node;
return node;
}
}
// 前面尝试快速入队失败,则降级为普通的入队操作
enq(node);
return node;
}
继续查看 AbstractQueuedSynchronizer#enq
/**
* Inserts node into queue, initializing if necessary. See picture above.
* @param node the node to insert
* @return node's predecessor
*/
private Node enq(final Node node) {
//经典的自旋加cas入队操作
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;
}
}
}
}
回来看AbstractQueuedSynchronizer#acquireQueued方法
/*
* Various flavors of acquire, varying in exclusive/shared and
* control modes. Each is mostly the same, but annoyingly
* different. Only a little bit of factoring is possible due to
* interactions of exception mechanics (including ensuring that we
* cancel if tryAcquire throws exception) and other control, at
* least not without hurting performance too much.
*/
/**
* Acquires in exclusive uninterruptible mode for thread already in
* queue. Used by condition wait methods as well as acquire.
*
* @param node the node
* @param arg the acquire argument
* @return {@code true} if interrupted while waiting
*/
final boolean acquireQueued(final Node node, int arg) {
//是否获取失败
boolean failed = true;
try {
//当前状态是否被中断了
boolean interrupted = false;
for (;;) {
//前一个node节点
final Node p = node.predecessor();
//如果前一个节点是head节点,则当前线程尝试获取锁
if (p == head && tryAcquire(arg)) {
//设置head节点为当前节点
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
//是否需要阻塞,如果需要阻塞的话就进行阻塞并且在阻塞结束后检查当前线程是否被中断了
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
//标记当前线程已被中断
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
这里分析一下shouldParkAfterFailedAcquire方法,首先先了解一下Node
节点状态 waitStatus
Node节点是对每一个等待获取资源的线程的封装,其包含了需要同步的线程本身及其等待状态,如是否被阻塞、是否等待唤醒、是否已经被取消等。变量waitStatus则表示当前Node结点的等待状态,共有5种取值CANCELLED、SIGNAL、CONDITION、PROPAGATE、0。
-
CANCELLED(1):表示当前结点已取消调度。当timeout或被中断(响应中断的情况下),会触发变更为此状态,进入该状态后的结点将不会再变化。
-
SIGNAL(-1):表示后继结点在等待当前结点唤醒。后继结点入队时,会将前继结点的状态更新为SIGNAL。
-
CONDITION(-2):表示结点等待在Condition上,当其他线程调用了Condition的signal()方法后,CONDITION状态的结点将从等待队列转移到同步队列中,等待获取同步锁。
-
PROPAGATE(-3):共享模式下,前继结点不仅会唤醒其后继结点,同时也可能会唤醒后继的后继结点。
-
0:新结点入队时的默认状态。
注意,负值表示结点处于有效等待状态,而正值表示结点已被取消。所以源码中很多地方用>0、<0来判断结点的状态是否正常。
/**
* Checks and updates status for a node that failed to acquire.
* Returns true if thread should block. This is the main signal
* control in all acquire loops. Requires that pred == node.prev.
*
* @param pred node's predecessor holding status
* @param node the node
* @return {@code true} if thread should block
*/
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
//Node.SIGNAL 表示后继结点在等待当前结点唤醒。后继结点入队时,会将前继结点的状态更新为SIGNAL
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
//状态值如果大于0表示节点已被取消,需要去除掉该节点
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 or PROPAGATE的状态下设置为SIGNAL状态,表示入队就绪可以被出队
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
接着查看阻塞线程的操作代码,可以看到底层是使用 LockSupport.park(this)来阻塞当前线程的
/**
* Convenience method to park and then check if interrupted
*
* @return {@code true} if interrupted
*/
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
到此为止ReentrantLock的lock方法解析完毕,接下去对应的分析ReentrantLock的unlock操作
ReentrantLock是怎么解锁的? ReentrantLock#unlock
/**
* Attempts to release this lock.
*
* <p>If the current thread is the holder of this lock then the hold
* count is decremented. If the hold count is now zero then the lock
* is released. If the current thread is not the holder of this
* lock then {@link IllegalMonitorStateException} is thrown.
* (如果当前线程是锁的持有者那么持有计数将减少。如果持有计数是0那么锁将被释放。如果当前线程不是锁的持有者,
* 那么将抛出IllegalMonitorStateException异常)
*
* @throws IllegalMonitorStateException if the current thread does not
* hold this lock
*/
public void unlock() {
sync.release(1);
}
sync#release实际是调用父类AbstractQueuedSynchronizer#release
/**
* Releases in exclusive mode. Implemented by unblocking one or
* more threads if {@link #tryRelease} returns true.
* This method can be used to implement method {@link Lock#unlock}.
* (在独占模式下释放。解锁一个或多个线程如果tryRelease返回true。这个方法可以用来实现Lock#unlock)
*
* @param arg the release argument. This value is conveyed to
* {@link #tryRelease} but is otherwise uninterpreted and
* can represent anything you like.
* @return the value returned from {@link #tryRelease}
*/
public final boolean release(int arg) {
//尝试释放锁
if (tryRelease(arg)) {
Node h = head;
//头指针不是空的 并且头指针的等待状态不是0
if (h != null && h.waitStatus != 0)
//唤醒线程
unparkSuccessor(h);
return true;
}
return false;
}
先看类AbstractQueuedSynchronizer#tryRelease
/**
* Attempts to set the state to reflect a release in exclusive
* mode.
*
* <p>This method is always invoked by the thread performing release.
*
* <p>The default implementation throws
* {@link UnsupportedOperationException}.
*
* @param arg the release argument. This value is always the one
* passed to a release method, or the current state value upon
* entry to a condition wait. The value is otherwise
* uninterpreted and can represent anything you like.
* @return {@code true} if this object is now in a fully released
* state, so that any waiting threads may attempt to acquire;
* and {@code false} otherwise.
* @throws IllegalMonitorStateException if releasing would place this
* synchronizer in an illegal state. This exception must be
* thrown in a consistent fashion for synchronization to work
* correctly.
* @throws UnsupportedOperationException if exclusive mode is not supported
*/
protected boolean tryRelease(int arg) {
throw new UnsupportedOperationException();
}
可以看到该方法同样需要子类实现
protected final boolean tryRelease(int releases) {
//当前状态值减去释放量 可重入锁的实现原理
int c = getState() - releases;
//如果当前线程不是锁的持有者抛出异常
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
//如果状态是0说明锁已经被释放
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
//跟新当前状态值
setState(c);
return free;
}
接着分析AbstractQueuedSynchronizer#unparkSuccessor
/**
* Wakes up node's successor, if one exists.
*
* @param node the node
*/
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.
*/
//传进来的head节点,head节点不是实际的锁持有者,而是它的下一个,并且要检查节点是否已经被取消了 (waitStatus > 0)或者是null
Node s = node.next;
//如果后继节点是null或者已经被取消 则从tail开始向前遍历找到一个可以被唤醒的节点,这段逻辑为什么这么写可 以查看文章 https://www.zhihu.com/question/50724462/answer/123776334
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);
}