Ch8-Java Lock 之 ReentrantReadWriteLock

Ch8-Java Lock 之 ReentrantReadWriteLock

January 21, 2020
Java | JUC
java

java.util.concurrent.locks.ReentrantReadWriteLock

1. 重要变量 #

ReentrantReadWriteLock 中的 Sync 继承自 AQS,因此其临界资源为 AQS 中的 state 变量。ReentrantLock 将 state 高 16 位记录读锁状态(次数,包括重入次数),低 16 位记录写锁状态(次数,包括重入次数)。

2. 核心接口 #

public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable {
    private final ReentrantReadWriteLock.ReadLock readerLock;
    private final ReentrantReadWriteLock.WriteLock writerLock;
    final Sync sync; // sync = fair ? new FairSync() : new NonfairSync();

    abstract static class Sync extends AbstractQueuedSynchronizer {
        protected final boolean tryAcquire(int acquires);
        protected final boolean tryRelease(int releases);
        protected final int tryAcquireShared(int unused);
        protected final boolean tryReleaseShared(int unused);

        final boolean tryWriteLock();
        final boolean tryReadLock();
    }

    static final class NonfairSync extends Sync {
        final boolean writerShouldBlock();
        final boolean readerShouldBlock();
    }

    static final class FairSync extends Sync {
        final boolean writerShouldBlock();
        final boolean readerShouldBlock();
    }

    public static class ReadLock implements Lock, java.io.Serializable {
        protected ReadLock(ReentrantReadWriteLock lock);
        public void lock();
        public void unlock();
    }

    public static class WriteLock implements Lock, java.io.Serializable {
        protected WriteLock(ReentrantReadWriteLock lock);
        public void lock();
        public void unlock();
    }
}

3. 参考文献 #