实例化
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
fair为true是公平锁,false为false是非公平锁。
公平锁的lock()方法
final void lock() {
acquire(1);
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
tryAcquire 尝试获取独占锁
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;
}
先获取同步对象的状态getState();
如果状态是0,还没有被线程占用。
hasQueuedPredecessors();看看同步队列中是否有等待的线程,如果有,获取锁失败(独占锁肯定失败,共享锁不一定)。
如果没有使用compareAndSetState(0, acquires);使用cas的方式把状态从0改为1;
把获取到资源的线程调用setExclusiveOwnerThread(current);也就是设置当前的独占线程设置为当前的线程;
else if (current == getExclusiveOwnerThread())
如果状态不是0,判断是否还是当前的线程(也就是ExclusiveOwnerThread);如果是让state加1,int nextc = c + acquires;
如果tryAcquire(arg)失败,就会把当前的线程添加到CLH队列中。
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;
}
node.prev = pred;
if (pred != null)如果CLH队列中有节点的话
把当前节点的前置节点指向好。
使用cas把当前节点放到CLH队列的尾部compareAndSetTail(pred, node);
如果CLH队列中没有节点的话调用enq(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;
}
}
}
}
先初始化一个空的Node节点作为head节点compareAndSetHead(new Node());
然后再把新节点添加到空的节点的后面;
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);
}
}
把刚添加到队列中的Thread节点,准备阻塞,然后等待获取锁。
拿到当前节点的前置节点final Node p = node.predecessor();先判断if (p == head && tryAcquire(arg)) 前置节点是否已经变成head节点,如果变成head节点,这时候再去尝试获取锁。
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;
}
if (ws == Node.SIGNAL)如果当前节点的前驱节点是signal,当前节点可以被阻塞;
if (ws > 0) 如果前驱节点大于0,这个前驱节点就会被移除队列,
当前驱节点的waitStatus的状态是0或者PROPAGATE时,使用cas将其设置为SIGNAL,然后当前节点才可以park。
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
阻塞当前节点,并返回当前节点的阻塞状态。
公平锁的unlock方法
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
如果当前线程不等于获取独占锁的线程,那么抛出异常
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
如果c==0 把获取独占锁的线程设置为null;
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);
}
如果后一个节点是null或者waitStatus大于0,那么就从尾部开始遍历,找到正常阻塞的一个节点。