protectedfinalbooleanisHeldExclusively() { // 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() { returnnewConditionObject(); }
/** * Reconstitutes the instance from a stream (that is, deserializes it). */ privatevoidreadObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); setState(0); // reset to unlocked state } }
/** * Performs lock. Try immediate barge, backing up to normal * acquire on failure. */ finalvoidlock() { if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); }
/** * Fair version of tryAcquire. Don't grant access unless * recursive call or no waiters or is first. */ protectedfinalbooleantryAcquire(int acquires) { finalThreadcurrent= Thread.currentThread(); intc= getState(); if (c == 0) { if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) {//公平锁在这里要先通过hasQueuedPredecessors方法判断该节点前置节点是否是head setExclusiveOwnerThread(current); returntrue; } } elseif (current == getExclusiveOwnerThread()) { intnextc= c + acquires; if (nextc < 0) thrownewError("Maximum lock count exceeded"); setState(nextc); returntrue; } returnfalse; } }
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()); }
privatestaticbooleanshouldParkAfterFailedAcquire(Node pred, Node node) { intws= pred.waitStatus; if (ws == Node.SIGNAL) /* * This node has already set status asking a release * to signal it, so it can safely park. */ returntrue; 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); } returnfalse; }
intws= node.waitStatus; if (ws < 0) compareAndSetWaitStatus(node, ws, 0);
Nodes= node.next; if (s == null || s.waitStatus > 0) { s = null; for (Nodet= tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } if (s != null) LockSupport.unpark(s.thread); }
unparkSuccessor主要是唤醒下一个线程,如果下一个线程已经取消掉了,则从tail一直往前推,直到不满足循环要求,退出循环(这个地方不是找到正常的节点就退出循环,而是要到不满足(t != null && t != node)的时候(即找到当前节点下一个正常的节点)才退出循环),如果这个时候找到正常的节点了就唤醒,没有就直接返回