/** * 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. */ //非公平tryAcquire方法,非公平模式下的tryAcquire实现会直接调用该方法。此外ReentrantLock的tryLock方法也会调用该方法 finalbooleannonfairTryAcquire(int acquires) { finalThreadcurrent= Thread.currentThread(); intc= getState(); //当资源为0时,说明没有线程持有锁 if (c == 0) { //通过CAS竞争方法,尝试更改资源状态 if (compareAndSetState(0, acquires)) { //竞争成功的线程获取锁,并绑定当前线程 setExclusiveOwnerThread(current); returntrue; } } //当资源不为0时,只有已持有锁的线程才会返回true,这就是可重入的具体含义 elseif (current == getExclusiveOwnerThread()) { intnextc= c + acquires; if (nextc < 0) //overflow thrownewError("Maximum lock count exceeded"); setState(nextc); returntrue; } returnfalse; }
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 } }
/** * 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) { //当资源状态为0,即当前没有线程持有锁时,首先检查队列中是否有节点存在,如果没有,才尝试获取,否则进入sync queue if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); returntrue; } } elseif (current == getExclusiveOwnerThread()) { intnextc= c + acquires; if (nextc < 0) thrownewError("Maximum lock count exceeded"); setState(nextc); returntrue; } returnfalse; } }
hasQueuedPredecessors方法如下,这是AQS的方法
1 2 3 4 5 6 7 8 9 10 11
publicfinalbooleanhasQueuedPredecessors() { //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. Nodet= tail; //Read fields in reverse initialization order Nodeh= head; Node s; //检查队列中位于第二位的节点所关联的线程是否是当前线程 return h != t && ((s = h.next) == null || s.thread != Thread.currentThread()); }
3 重要方法
ReentrantLock只有一个字段
1 2
/** Synchronizer providing all implementation mechanics */ privatefinal Sync sync;