Synchronization Patterns • Read-Write LocksMedium⏱️ ~2 min
Read-Write Lock Variants and Trade-offs
Decision Guide
Different read-write lock implementations make different fairness and performance trade-offs. Know which one you are using.
Reader-Preference Locks
New readers can enter as long as at least one reader is inside. Writers wait until all readers finish. Pro: Maximum read throughput. Con: Writers can starve under load.
Writer-Preference Locks
When a writer is waiting, no new readers are admitted. Existing readers finish, then writer enters. Pro: Writers have bounded latency. Con: Readers may starve if writes are frequent.
Lock Variant Comparison
Fair (FIFO) Locks
Requests are served in arrival order. A waiting writer blocks subsequent readers. A waiting reader blocks subsequent writers. Pro: No starvation possible. Con: Lower throughput because requests serialize.
Language/Library Defaults
Java ReentrantReadWriteLock: Configurable - fair mode available. Default is non-fair.
pthread_rwlock: Implementation-defined. Often writer-preference but check your platform.
Go sync.RWMutex: Writer-preference. Writers block new readers.
Choose Wisely: Know your read/write ratio. 1000:1 reads? Reader-preference is fine. Critical writes that must not wait? Use writer-preference or fair. When in doubt, prefer fair - starvation bugs are nasty.
💡 Key Takeaways
✓Reader-preference: maximum read concurrency, writers may starve. Good for read-heavy, tolerant of write delays.
✓Writer-preference: writers get priority, readers may starve. Good when writes are critical and time-sensitive.
✓Fair/FIFO: no starvation, strict ordering. Lower throughput but predictable latency for all.
✓Java ReentrantReadWriteLock has fair mode option. pthread varies by platform. Go RWMutex is writer-preference.
✓Match the lock type to your workload. Wrong choice leads to starvation bugs or unnecessary performance loss.
📌 Examples
1Web cache (1000:1 read ratio): Reader-preference is fine. Cache refresh can wait for a gap in traffic.
2Audit log (writes must complete): Writer-preference ensures logs are written promptly even under read load.
3Shared document editing: Fair lock ensures no user waits indefinitely regardless of operation type.