Read-write lock notes
Overview
Read-write locks are divided into read locks and write locks.
- Read locks can coexist without write locks
- Write locks can only exist one at a time, and while read locks exist, read locks cannot exist
ReentrantReadWriteLock
Analysis of the principle of read-write lock through ReentrantReadWriteLock
initialization
private ReadWriteLock lock = new ReentrantReadWriteLock();
private Lock readLock = lock.readLock();
private Lock writeLock = lock.writeLock();
Like ReentrantLock, ReentrantReadWriteLock also uses AQS as a synchronizer, and also provides two forms of fairness and unfairness. WriteLock uses AQS acquire
and release
methods, and ReadLock uses AQS acquireShared
and releaseShared
methods.
Further explanation is given next