What is ReadWriteLock, and when should you use it?
ReadWriteLock maintains a pair of locks: a shared read lock, which any number of threads can hold at the same time as long as no thread holds the write lock, and an exclusive write lock, which blocks every other reader and writer while it's held. It is well suited to workloads where reads vastly outnumber writes, for example 95 percent reads and 5 percent writes, because allowing concurrent reads gives a real throughput improvement compared with a plain synchronized block, which serializes even read-only access. Typical use cases include in-memory caches, configuration maps, and lookup tables that change rarely but are read constantly. One caution is that under sustained heavy write contention, readers can end up starved, waiting a long time for their turn. As of Java 8, StampedLock with its optimistic-read mode offers an even faster alternative for very read-heavy workloads.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response