compare and swap 比较并交换,比如现在两个线程同时去获取一个资源,这个资源对象值为0的一瞬间,ab线程都读到了,此时两条线程认为当前状态的值为0,于是他们各自会产生两个值,oldvalue代表读到的资源状态值,newvalue代表想要更新的值。此时ab线程争抢去修改资源对象的值,然后占用。假设a线程先获得时间片,将oldvalue与资源状态值进行compare发现一致,于是将资源对象的值swap为newvalue,而b线程晚了一步,此时资源对象的值已经被a线程修改为了1,所以b线程在compare的时候发现和自己预期的oldvalue值不一样,所以放弃swap操作,但实际应用中,不会让b线程就此放弃,通常会使其进行自旋,不断重试,通常会配置自旋次数防止死循环。
/**
* Head of the wait queue, lazily initialized. Except for
* initialization, it is modified only via method setHead. Note:
* If head exists, its waitStatus is guaranteed not to be
* CANCELLED.
* */privatetransientvolatileNodehead;/**
* Tail of the wait queue, lazily initialized. Modified only via
* method enq to add new wait node.
*/privatetransientvolatileNodetail;/**
* The synchronization state.
* */privatevolatileintstate;
staticfinalclassNode{/** Marker to indicate a node is waiting in shared mode */staticfinalNodeSHARED=newNode();/** 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;/**
* 等待状态 上面的枚举值
* */volatileintwaitStatus;/**
* 前指针
* */volatileNodeprev;/**
* 后指针
*/volatileNodenext;/**
* The thread that enqueued this node. Initialized on
* construction and nulled out after use.
* 线程对象
* */volatileThreadthread;/**
*
* */NodenextWaiter;}
/**
* Creates an instance of {@code ReentrantLock}.
* This is equivalent to using {@code ReentrantLock(false)}.
*/publicReentrantLock(){sync=newNonfairSync();}/**
* Creates an instance of {@code ReentrantLock} with the
* given fairness policy.
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/publicReentrantLock(booleanfair){sync=fair?newFairSync():newNonfairSync();}
/**
* Base of synchronization control for this lock. Subclassed
* into fair and nonfair versions below. Uses AQS state to
* represent the number of holds on the lock.
*
* */abstractstaticclassSyncextendsAbstractQueuedSynchronizer{privatestaticfinallongserialVersionUID=-5179523762034025860L;/**
* Performs {@link Lock#lock}. The main reason for subclassing
* is to allow fast path for nonfair version.
* */abstractvoidlock();/**
* Performs non-fair tryLock. tryAcquire is implemented in
* subclasses, but both need nonfair try for trylock method.
* */finalbooleannonfairTryAcquire(intacquires){finalThreadcurrent=Thread.currentThread();intc=getState();if(c==0){if(compareAndSetState(0,acquires)){setExclusiveOwnerThread(current);returntrue;}}elseif(current==getExclusiveOwnerThread()){intnextc=c+acquires;if(nextc<0)// overflow thrownewError("Maximum lock count exceeded");setState(nextc);returntrue;}returnfalse;}protectedfinalbooleantryRelease(intreleases){intc=getState()-releases;if(Thread.currentThread()!=getExclusiveOwnerThread())thrownewIllegalMonitorStateException();booleanfree=false;if(c==0){free=true;setExclusiveOwnerThread(null);}setState(c);returnfree;}protectedfinalbooleanisHeldExclusively(){// While we must in general read state before owner, // we don't need to do so to check if current thread is owner returngetExclusiveOwnerThread()==Thread.currentThread();}finalConditionObjectnewCondition(){returnnewConditionObject();}// Methods relayed from outer class finalThreadgetOwner(){returngetState()==0?null:getExclusiveOwnerThread();}finalintgetHoldCount(){returnisHeldExclusively()?getState():0;}finalbooleanisLocked(){returngetState()!=0;}/**
* Reconstitutes the instance from a stream (that is, deserializes it).
* */privatevoidreadObject(java.io.ObjectInputStreams)throwsjava.io.IOException,ClassNotFoundException{s.defaultReadObject();setState(0);// reset to unlocked state }}
/**
* Sync object for non-fair locks
* */staticfinalclassNonfairSyncextendsSync{privatestaticfinallongserialVersionUID=7316153563782823691L;/**
* Performs lock. Try immediate barge, backing up to normal
* acquire on failure.
* */finalvoidlock(){if(compareAndSetState(0,1))setExclusiveOwnerThread(Thread.currentThread());elseacquire(1);}protectedfinalbooleantryAcquire(intacquires){returnnonfairTryAcquire(acquires);}}