Interpretation of WriteLock source code of ReentranReadWriteLock

//ReentrantReadWriteLock的WriteLock
//WriteLock's lock method

public void lock() {
            sync.acquire(1);
        }

 public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }


 protected final boolean tryAcquire(int acquires) {
          
            Thread current = Thread.currentThread();
	    //get state
            int c = getState();
            int w = exclusiveCount(c);
	    //If c is not 0, it means that there is currently a thread that has acquired the lock
            if (c != 0) {
                // (Note: if c != 0 and w == 0 then shared count != 0)
		// The current thread is not the currently running exclusive thread
                if (w == 0 || current != getExclusiveOwnerThread())
                    return false;
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                // Reentrant acquire
                setState(c + acquires);
                return true;
            }
            if (writerShouldBlock() ||
                !compareAndSetState(c, c + acquires))
                return false;
            setExclusiveOwnerThread(current);
            return true;
        }


 final boolean writerShouldBlock() {
            return false; // writers can always barge
        }


//WriteLock is simply to judge whether there is currently a thread occupying the lock, and if there is, join the queue to wait for wake-up. There is no direct occupation of running.


WriteLock's unlock method:
 public void unlock() {
            sync.release(1);
        }

 public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
//Set the state and set the exclusive thread to null
protected final boolean tryRelease(int releases) {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            int nextc = getState() - releases;
            boolean free = exclusiveCount(nextc) == 0;
            if (free)
                setExclusiveOwnerThread(null);
            setState(nextc);
            return free;
        }





//The other methods of WriteLock are basically the same as Reentrant. WriteLock itself is equivalent to ReentrantLock mutex.

Guess you like

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