ReentrantLockd's fair lock method implements source code analysis


//ReetrantLock fair lock source code analysis:
/** The fair lock calls the method in FairSync and the unfair lock has fewer steps to judge the current state
 That is, the unfair lock thread can directly enter the execution queue at this time.
*/
 final void lock() {
            acquire(1);
        }

//The difference from the unfair lock is that the hasQueuedPredecessors method is called to determine whether the queue is empty
  protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
    }

/**
When the head node is not equal to the tail node and the second node is empty (it will be empty when the head node has just been initialized but the next method has not been called)
Or the thread of the second node is not the current thread. then the queue is not empty.
*/
  public final String hasQueuedPredecessors() {
        
        Node t = tail;
        Node h = head;
        Node s;
        return h != t &&
            ((s = h.next) == null || s.thread != Thread.currentThread());
    }


/**
Fair locks are also not absolutely fair. If thread A fails to call tryAcquire but does not have time to call the addWaiter method (not yet queued)
But at this time, thread C comes in and finds that the queue is empty, so it executes directly.

In the fair lock, the subsequent threads have to wait in line, so it is less efficient than the unfair lock.
*/


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326570287&siteId=291194637