/** * 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 */ 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; }
进入后先检测前驱节点的状态ws。
下面是waitStatus的常量
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/** Marker to indicate a node is waiting in exclusive mode */ staticfinalNodeEXCLUSIVE=null;
/** waitStatus value to indicate thread has cancelled */ staticfinalintCANCELLED=1; /** waitStatus value to indicate successor's thread needs unparking */ staticfinalintSIGNAL= -1; /** waitStatus value to indicate thread is waiting on condition */ staticfinalintCONDITION= -2; /** * waitStatus value to indicate the next acquireShared should * unconditionally propagate */ staticfinalintPROPAGATE= -3;
privatestaticvoidsetBlocker(Thread t, Object arg) { // Even though volatile, hotspot doesn't need a write barrier here. UNSAFE.putObject(t, parkBlockerOffset, arg); }