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();
/** * Performs non-fair tryLock. tryAcquire is implemented in * subclasses, but both need nonfair try for trylock method. */ 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) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; }
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; }
protected final boolean isHeldExclusively() { // While we must in general read state before owner, // we don't need to do so to check if current thread is owner return getExclusiveOwnerThread() == Thread.currentThread(); }
final ConditionObject newCondition() { return new ConditionObject(); }
final int getHoldCount() { return isHeldExclusively() ? getState() : 0; }
final boolean isLocked() { return getState() != 0; }
/** * Reconstitutes the instance from a stream (that is, deserializes it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); setState(0); // reset to unlocked state } }
public ReentrantLock() { sync = new NonfairSync(); }
/** * Creates an instance of {@code ReentrantLock} with the * given fairness policy. * * @param fair {@code true} if this lock should use a fair ordering policy */ public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); }
static final class FairSync extends Sync { private static final long serialVersionUID = -3000897897090466540L;
final void lock() { acquire(1); }
/** * 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; } }
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() { //不排队直接CAS替换操作。 if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); }
protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState();//持有锁的线程个数 if (c == 0) {//没有线程获取到锁 if (!hasQueuedPredecessors() && //判断当前线程在队列里边,它前边是否有线程正在执行,排队,保证锁的获取是公平的 compareAndSetState(0, acquires)) {//CAS成功,把0改成1成功,意味着获取锁成功 setExclusiveOwnerThread(current);//设置排它锁,表示当前线程正在执行 return true; } } //当前线程是否是排他线程的拥有者 else if (current == getExclusiveOwnerThread()) { //加和,比如由1变成2 int nextc = c + acquires; if (nextc < 0) throw new Error("Maximum lock count exceeded"); //重新CAS设置 setState(nextc); return true; } return false; }
hasQueuedPredecessors判断当前线程在队列里边,它前边是否有线程
1 2 3 4 5 6 7 8 9 10
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()); }
NonfairSync的lock实现:
1 2 3 4 5 6 7 8 9 10 11 12 13
final void lock() { //不排队直接CAS替换操作。CAS替换 if (compareAndSetState(0, 1)) //设置排他 setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); }
protected final boolean tryAcquire(int acquires) { //调用父类的nonfairTryAcquire获取。 return nonfairTryAcquire(acquires); }
Syn的nonfairTryAcquire:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) {//没有线程持有锁 //非公平锁的获取,直接CAS替换,不会判断等待队列有没有线程。 if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } 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; }
Node的状态值
Node里边有几个成员变量是Node的状态值: static final Node SHARED = new Node(); //共享锁 static final Node EXCLUSIVE = null;//排它锁 static final int CANCELLED = 1;//被取消掉 static final int SIGNAL = -1;// static final int CONDITION = -2; static final int PROPAGATE = -3;//
//Wakes up node's successor, if one exists. //如果当前线程的后继存在,那么唤醒后继线程 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); }
LockSupport.unpark实现:
1 2 3 4 5
//os.linux.vm.oslinux.cpp=>parker.unpark public static void unpark(Thread thread) { if (thread != null) UNSAFE.unpark(thread);//negative方法 }
tryRelease会使用 FairSync父类Syn的重写的tryRelease方法
FairSync的unlock实现:
1 2 3 4 5 6 7 8 9 10 11 12
protected final boolean tryRelease(int releases) { int c = getState() - releases;//状态减一,比如由2变成1 if (Thread.currentThread() != getExclusiveOwnerThread())//A线程获取到了锁,必须是由A释放锁 throw new IllegalMonitorStateException(); boolean free = false; if (c == 0) {//当前没有线程持有锁 free = true;//锁是自由的状态 setExclusiveOwnerThread(null);//排它锁持有者设置为空 } setState(c);//CAS设置state return free;//为false,是重入状态,true是自由状态 }