/** * Performs {@link Lock#lock}. The main reason for subclassing * is to allow fast path for nonfair version. */ //抽象方法,由子类自行实现如何 lock abstractvoidlock();
/** * Performs non-fair tryLock. tryAcquire is implemented in * subclasses, but both need nonfair try for trylock method. */ /** * 非公平的尝试获取锁 * 一般来说,tryAcquire 由子类自行实现的,但 ReentrantLock 中的 * tryLock 方法中都需要调用该非公平的尝试锁方法 * 返回值表示是否获取锁状态成功 */ finalbooleannonfairTryAcquire(int acquires){ //获取当前线程 final Thread current = Thread.currentThread(); //获取当前的锁状态 int c = getState(); if (c == 0) { //如果 c == 0,即锁为「空闲」状态,尝试通过 cas 的方式修改所状态 if (compareAndSetState(0, acquires)) { //cas 成功,则修改占用了锁的线程的值为当前线程,并返回获取锁状态成功 setExclusiveOwnerThread(current); returntrue; } } //else 说明 c != 0,说明锁已经被某个线程占用了 //则判断被占用的线程是否为当前线程 elseif (current == getExclusiveOwnerThread()) { //如果锁被占用的线程是当前线程 //如果 nextc < 0 说明超过 Int 的最大值溢出了,则抛出异常 //否则将 state 的值修改为原来的值 + acquires 的值 //这里不需要用 cas 的方式修改 state 的值是因为 if 中 已经判断了当前线程,所以不存在竞争 //最后返回 true 表示获取锁成功(即获取重入锁成功) int nextc = c + acquires; if (nextc < 0) // overflow thrownew Error("Maximum lock count exceeded"); setState(nextc); returntrue; } //走到这里说明当前锁状态被别的线程占领了,则返回 false returnfalse; }
/** * 尝试释放锁状态 * 返回值表示是否完全释放了锁状态 */ protectedfinalbooleantryRelease(int releases){ //根据当前 state 和 releases 的值相减得到新的 state 值 c int c = getState() - releases; if (Thread.currentThread() != getExclusiveOwnerThread()) //如果当前线程非占用了锁的线程,并且来释放锁,则抛出异常 thrownew IllegalMonitorStateException(); //初始化 free 变量为 false,只有在当前线程完全将锁释放了之后才会置为 true(因为有可重入的状态) boolean free = false; if (c == 0) { free = true; //更改占用锁的线程为 null setExclusiveOwnerThread(null); } //更新 state 的值 setState(c); //返回 free return free; }
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(){ returnnew ConditionObject(); }
/** * 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){ final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); returntrue; } } elseif (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) thrownew Error("Maximum lock count exceeded"); setState(nextc); returntrue; } returnfalse; } }