1. Class definition

static final class FairSync extends Sync
Copy the code

You can see this in the class definition

  • FairSync is a static inner class in ReentrantLock and uses the final modifier to indicate that it is not inheritable
  • FairSync inherited the Sync, it shows that FairSync also AbstractQueuedSynchronizer subclasses

2. Field attributes

// Serialize the version number
private static final long serialVersionUID = -3000897897090466540L;
Copy the code

Method 3.

The lock method

/ / lock
final void lock(a) {
    		/ / call AbstractQueuedSynchronizer acquire method
    		// Try to acquire the lock first, fail to enter the queue
            acquire(1);
        }
Copy the code

TryAcquire method

// Try to get the lock method, override the parent class method
protected final boolean tryAcquire(int acquires) {
    		// Get the current thread
            final Thread current = Thread.currentThread();
    		// Get the status value
            int c = getState();
            if (c == 0) {
                //c equals 0, which means that no thread currently holds the lock, but maybe the last thread just released the lock
                // If the lock is fair, we should check whether there are waiting nodes in front of the queue. If there are waiting nodes in front of the queue, we should let the first node acquire the lock
                // If not, CAS changes the state value to obtain the lock and sets the thread holding the lock to the current thread
                if(! hasQueuedPredecessors() && compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true; }}// If the current thread has acquired the lock, it means that the lock is re-entered
    		// Just increment state by 1
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
    		// Return false if no lock was obtained
            return false;
        }
Copy the code