Understanding Java's ReentrantReadWriteLock: Concepts, Implementation, and Usage
This article explains Java's ReentrantReadWriteLock, covering the motivation for read‑write locks, their properties, a simple implementation example, lock upgrade and downgrade mechanisms, the internal AQS‑based design, fairness modes, and the roles of ReadLock and WriteLock classes.
Java's synchronized and ReentrantLock are exclusive locks; to improve concurrency, read‑write locks allow multiple readers while writers remain exclusive.
The article describes the concept of read‑write locks, their properties (multiple concurrent readers, writer exclusion), and conditions for acquiring read or write locks.
A simple read‑write lock implementation is presented with four methods: acquireReadLock() , releaseReadLock() , acquireWriteLock() , releaseWriteLock() , illustrating lock acquisition and release logic.
Lock upgrade (read to write) and downgrade (write to read) are explained, including the requirement that the upgrading thread be the sole reader.
The JDK's ReentrantReadWriteLock class diagram is shown; it implements Serializable and ReadWriteLock, with internal Sync extending AbstractQueuedSynchronizer, supporting fair and non‑fair modes via FairSync and NonfairSync.
ReadLock and WriteLock are inner classes implementing Lock; WriteLock overrides tryAcquire and tryRelease , while ReadLock overrides tryAcquireShared and tryReleaseShared , both relying on the shared AQS state where high 16 bits represent read count and low 16 bits represent write count.
Fairness is controlled by readerShouldBlock and writerShouldBlock methods; in fair mode threads queue in order, while non‑fair mode allows writers to bypass the queue under certain conditions.
Finally, an example demonstrates using ReentrantReadWriteLock to protect a TreeMap with read operations guarded by the read lock and write/clear operations by the write lock.
The article concludes that ReentrantReadWriteLock provides a powerful shared‑exclusive locking mechanism based on AQS, supporting both fairness policies and lock upgrading/downgrading.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.