A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
publicclassReentrantLockimplementsLock, java.io.Serializable { /** Synchronizer providing all implementation mechanics */ privatefinal Sync sync;//which extends the AQS. abstractstaticclassSyncextendsAbstractQueuedSynchronizer {//AQS实现,主要🔒逻辑 }
// Sync object for non-fair locks 非公平锁 staticfinalclassNonfairSyncextendsSync {
// Performs lock. Try immediate barge, backing up to normal acquire on failure. finalvoidlock() { if (compareAndSetState(0, 1))//barge:冲撞,尝试获取锁🔒 setExclusiveOwnerThread(Thread.currentThread());//成功ok else acquire(1);//tryAcquire()==>加入AQS队列 }
// 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)) {//尝试获取锁 setExclusiveOwnerThread(current);//ok returntrue; } } elseif (current == getExclusiveOwnerThread()) {//重入锁 intnextc= c + acquires;//state++ if (nextc < 0) thrownewError("Maximum lock count exceeded");//32位有符号正数 setState(nextc); returntrue; } returnfalse; } } publicReentrantLock() { sync = newNonfairSync();} publicReentrantLock(boolean fair) { sync = fair ? newFairSync() : newNonfairSync(); }
// methods: whose implementation is based on the AbstractQueuedSynchronizer$Sync. publicvoidlock() { sync.lock();} //Acquires the lock unless the current thread is interrupted. publicvoidlockInterruptibly()throws InterruptedException { sync.acquireInterruptibly(1); }
//Acquires the lock only if it is not held by another thread at the time of invocation. publicbooleantryLock() { return sync.nonfairTryAcquire(1); } publicvoidunlock() { sync.release(1); }
//conditions public Condition newCondition() { return sync.newCondition(); } publicbooleanhasWaiters(Condition condition) { if (condition == null) thrownewNullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) thrownewIllegalArgumentException("not owner"); return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); } publicintgetWaitQueueLength(Condition condition) { if (condition == null) thrownewNullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) thrownewIllegalArgumentException("not owner"); return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); } }
/** * 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 {
abstractvoidlock();//implementation in Subclasses(Fair/NonfairSync)
/** * Performs non-fair tryLock. * tryAcquire is implemented in subclasses, but both need nonfair try for trylock method. */ finalbooleannonfairTryAcquire(int acquires) { finalThreadcurrent= Thread.currentThread(); intc= getState(); if (c == 0) {//ok, 无锁直接尝试 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(int releases) { intc= getState() - releases; if (Thread.currentThread() != getExclusiveOwnerThread()) thrownewIllegalMonitorStateException(); booleanfree=false; if (c == 0) {//仅当🔒完全能释放 return ture. free = true; setExclusiveOwnerThread(null); } setState(c); return free; } finalintgetHoldCount() { return isHeldExclusively() ? getState() : 0; }