Video in progress

How does ReadWriteLock work, and when does it really give you speed?

Many threads can hold the read lock at the same time, while the write lock is exclusive. It helps where reads are frequent, writes are rare and the reads take a relatively long time; for short operations it can even be slower than a plain lock.

📖 Answer

class RateTable {
    private final Map<String, BigDecimal> rates = new HashMap<>();
    private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock();

    BigDecimal get(String currency) {
        rw.readLock().lock();
        try {
            return rates.get(currency);
        } finally {
            rw.readLock().unlock();
        }
    }

    void reload(Map<String, BigDecimal> fresh) {
        rw.writeLock().lock();
        try {
            rates.clear();
            rates.putAll(fresh);
        } finally {
            rw.writeLock().unlock();
        }
    }
}

One thing to know: taking a read lock isn't free either, since a shared counter is updated with CAS inside. If the critical section is a few nanoseconds, on a many-core machine that very counter becomes the bottleneck, and you can't beat synchronized.

Other subtle points:

  • you can't "upgrade" from a read lock to a write lock: the thread deadlocks itself. The reverse (a downgrade) is possible;
  • with a constant stream of readers, a writer can wait a long time.

For the example above there is a simpler solution in practice: keep an immutable Map in a volatile field and replace it entirely in reload. Readers take no lock at all.