/**
* 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}.
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquire} but is otherwise uninterpreted and
* can represent anything you like.
*/
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
一、acquire的三个步骤
先看看当前线程能否获得资源,如果能获得资源,就不用调用acquireQueued了。
1.尝试获取——tryAcquire方法
{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#acquire(int)},以排它的方式获得锁,对中断不敏感,完成synchronized语义。
1.尝试获取<br/>
{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#tryAcquire(int)}
更改状态
2.{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#tryAcquire(int)}
失败会入队列
{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#acquire(int)}包括了
获取锁失败+入队列操作/成功获取锁操作
<p/>
2.入队列addWaiter
新的节点从队尾插入,用compareAndSetTail保证原子性。node的模式是Node.EXCLUSIVE。.只有没获取到锁的线程才会入队列。
这里有一个fast-path,直接先试一次原子设置tail。
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;
}
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;
}
}
}
}
3关于acquire中的acquireQueued方法
自旋获取锁的过程。
判断当前节点的前驱节点。
需要获取当前节点的前驱节点的状态,当前驱节点是头结点并且当前节点(线程)能够获取状态(tryAcquire方法成功),
代表该当前节点占有锁,如果满足上述条件,那么代表能够占有锁,根据节点对锁占有的含义,设置头结点为当前节点(setHead)。
如果没有满足上述条件,调用parkAndCheckInterrupt方法使得当前线程disabled,直到unpark调用,Thread的interrupt调用,然后重新轮训去尝试上述操作。
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())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
即使前驱节点是头结点,但是tryAcquire方法也未必会成功,对于
偏向锁(非公平锁)来说新来一个节点会优先去tryAcquire竞争锁资源,如果成功了,那么这个前驱为头结点的节点进行tryAcquire就会失败。
4.修改前驱节点状态shouldParkAfterFailedAcquire
如果前驱没有被初始化过(值为0),把前驱的状态修改为Node.SIGNAL。
如果前驱节点是CANCELLED(1),跳过该节点,向前找到状态不是CANCELLED的那个节点作为当前节点的前驱。
如果状态是0或者PROPAGATE,原子操作设置node的状态为SIGNAL,但是暂且不park,再重试一次看是否能获得锁。(为什么)
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.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
5.头结点
头结点在初始化的时候是new出来的,无论何时,头结点的thread和prev属性都是null。二、关于acquire方法总结
1. 状态的维护;需要在锁定时,需要维护一个状态(int类型),而对状态的操作是原子和非阻塞的,
通过同步器提供的对状态访问的方法对状态进行操纵,并且利用compareAndSet来确保原子性的修改。
2. 状态的获取;
当前驱节点是头结点,并且成功的修改了状态(tryAcquire方法成功),当前线程或者说节点,就被设置为头节点。
3.修改前驱状态信息
{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#shouldParkAfterFailedAcquire},
如果前驱没有被初始化过(值为0),把前驱的状态修改为Node.SIGNAL。
4. sync队列的维护。
在获取资源未果的过程中条件不符合的情况下(前驱节点不是头节点或者没有获取到资源)进入睡眠状态,
停止线程调度器对当前节点线程的调度,
{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#parkAndCheckInterrupt()}