The 30 second answer
A read-write lock lets many readers proceed together while a writer gets exclusive access, so it helps when reads vastly outnumber writes and each read takes a while. Otherwise a plain lock is simpler and often faster. A blocking queue is the standard producer-consumer handoff: producers put, consumers take, and a bounded capacity gives you backpressure.
ReadWriteLock. ReentrantReadWriteLock holds a pair of locks: many threads may hold the read lock at once, the write lock is exclusive. It pays off for a structure read constantly and rebuilt rarely, such as an in-memory routing table or a configuration snapshot, where readers do real work under the lock. Costs and caveats from the Javadoc and practice:
- It does not impose reader or writer preference by default; in non-fair mode a continuously contended lock can postpone some threads indefinitely. A fair mode exists at a throughput cost.
- A thread holding the read lock cannot upgrade to the write lock; trying deadlocks. Downgrading, acquiring the read lock before releasing the write lock, is allowed.
- If writes are frequent or critical sections tiny, the extra bookkeeping makes it slower than a single
ReentrantLock.
A routing table read on every request and rebuilt rarely:
private final ReadWriteLock rw = new ReentrantReadWriteLock();
private final Map<String, String> routes = new HashMap<>();
String lookup(String key) {
rw.readLock().lock(); // many readers at once
try { return routes.get(key); }
finally { rw.readLock().unlock(); }
}
void rebuild(Map<String, String> fresh) {
rw.writeLock().lock(); // exclusive: waits for readers to leave
try { routes.clear(); routes.putAll(fresh); }
finally { rw.writeLock().unlock(); }
}Alternatives: an immutable snapshot swapped through a volatile or AtomicReference field gives readers no locking at all; StampedLock offers optimistic reads.
Worked example: optimistic reads via AtomicReference (runnable, Java 21+). Each item holds an immutable snapshot of its value plus a version. Readers load the reference once and get a consistent value and version with no lock. Writers read the current version, do their work, and publish with compareAndSet only if nothing changed in between; on a conflict they retry.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
public class OptimisticPrice {
// (1) Immutable snapshot: a value plus the version it was written at.
record Versioned(long priceCents, long version) {}
// (2) One AtomicReference per item holds the current snapshot.
private final AtomicReference<Versioned> current =
new AtomicReference<>(new Versioned(1_000, 0));
// (3) Reader: load the reference once, then read value and version from
// that same snapshot. No lock; they can never be torn or mismatched.
Versioned read() {
return current.get();
}
// (4) Writer: read the version, do the work, publish only if nobody else
// published in between; otherwise abort this attempt and retry.
Versioned applyDiscount(int percent) {
while (true) {
Versioned seen = current.get(); // read current version
long newPrice = seen.priceCents() * (100 - percent) / 100; // work on the snapshot
Versioned next = new Versioned(newPrice, seen.version() + 1);
// compareAndSet succeeds only if the reference is still the one we read,
// i.e. the version is unchanged. Snapshots are immutable and never reused,
// so reference identity == version identity.
if (current.compareAndSet(seen, next)) return next;
// Lost the race: someone published a newer version. Loop and redo the work.
}
}
public static void main(String[] args) throws Exception {
OptimisticPrice p = new OptimisticPrice();
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int i = 0; i < 1_000; i++) pool.submit(() -> p.applyDiscount(0)); // 1,000 contended writes
for (int i = 0; i < 1_000; i++) pool.submit(p::read); // lock-free reads
}
Versioned v = p.read();
System.out.println("price=" + v.priceCents() + " version=" + v.version()); // version=1000: no write lost
}
}How this differs from the immutable snapshot swap. A snapshot swap replaces the entire dataset at once: the writer builds a whole new copy, such as the full routing table, and readers switch to it in one reference write. Optimistic reads version individual items instead, so writers to different items never conflict, and a writer that loses a race on the same item simply retries. StampedLock.tryOptimisticRead is the lock-based version of the same idea: read without locking, then call validate and retry under a read lock if a write happened.
Worked example: immutable snapshot swap via AtomicReference (runnable, Java 21+). The whole dataset lives in one immutable snapshot. Readers load the reference once and read from that snapshot with no lock. The writer builds a completely new copy and publishes it in one atomic reference write, so every reader sees either the old catalog or the new one, never a mix.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
public class CatalogSnapshot {
// (1) Immutable snapshot of the WHOLE dataset: all prices plus a version.
record Catalog(Map<String, Long> prices, long version) {
Catalog { prices = Map.copyOf(prices); } // defensive copy: nobody can mutate it later
}
// (2) One AtomicReference holds the current full snapshot.
private final AtomicReference<Catalog> current =
new AtomicReference<>(new Catalog(Map.of("shoe", 5_000L, "shirt", 2_000L), 0));
// (3) Reader: load the reference once, then read everything from that snapshot.
// No lock; a reader never sees a half-rebuilt catalog.
long priceOf(String sku) {
Catalog c = current.get();
return c.prices().getOrDefault(sku, -1L);
}
// (4) Writer: build a completely new snapshot (copy-on-write), then publish it
// with one atomic swap that replaces the whole dataset at once.
void reload(Map<String, Long> freshPrices) {
while (true) {
Catalog old = current.get();
Catalog next = new Catalog(freshPrices, old.version() + 1); // new copy, old one untouched
if (current.compareAndSet(old, next)) return; // swap only if no other writer swapped first
// Lost the race: another writer published a newer catalog. Loop and rebuild.
}
}
public static void main(String[] args) throws Exception {
CatalogSnapshot store = new CatalogSnapshot();
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
List<Future<Long>> reads = new ArrayList<>();
for (int i = 0; i < 10_000; i++) {
if (i == 5_000) // one writer swaps in a new catalog while readers keep running
pool.submit(() -> store.reload(Map.of("shoe", 4_500L, "shirt", 1_800L, "hat", 900L)));
reads.add(pool.submit(() -> store.priceOf("shoe"))); // readers never wait for the writer
}
Set<Long> seen = new TreeSet<>();
for (Future<Long> f : reads) seen.add(f.get());
// Each read returned either the old or the new full catalog, never a mix.
System.out.println("shoe prices seen by readers: " + seen);
}
System.out.println("final version=" + store.current.get().version() + " hat=" + store.priceOf("hat"));
}
}Verified with OpenJDK 21.0.13: across runs the readers saw only the old shoe price, 5000, or the new one, 4500, and the final catalog was version 1 with the new hat entry. Every write copies the entire dataset, so this suits data that is read constantly and reloaded rarely, such as configuration or a routing table. For frequent small updates, use the per-item optimistic version above.
BlockingQueue. The Javadoc says implementations are designed primarily for producer-consumer queues. put blocks when a bounded queue is full and take blocks when it is empty, so a slow consumer slows producers instead of exhausting memory. offer and poll with timeouts avoid blocking forever. A BlockingQueue does not accept null, because null signals failure from poll. Choose ArrayBlockingQueue for a fixed bound, LinkedBlockingQueue with an explicit capacity, or SynchronousQueue for direct handoff.
Example use. An indexing worker that reads change events, batches them, and sends bulk requests: producers put events on a bounded queue, one or more consumers drain up to N events or wait up to T milliseconds, then send a batch. When the search cluster slows down, the queue fills and the producers slow down too.
final BlockingQueue<String> events = new ArrayBlockingQueue<>(10_000); // bound = backpressure
void produce(String event) throws InterruptedException {
events.put(event); // blocks when the queue is full
}
List<String> nextBatch(int max, long waitMs) throws InterruptedException {
List<String> batch = new ArrayList<>(max);
String first = events.poll(waitMs, TimeUnit.MILLISECONDS); // wait up to T for the first event
if (first == null) return batch;
batch.add(first);
events.drainTo(batch, max - 1); // take whatever else is ready, up to N
return batch;
}
Sources (5)
- ReentrantReadWriteLock Javadoc (Java 21)docs.oracle.com
- BlockingQueue Javadoc (Java 21)docs.oracle.com
- AtomicReference Javadoc (Java 21): compareAndSetdocs.oracle.com
- StampedLock Javadoc (Java 21): optimistic readsdocs.oracle.com
- Zalando Engineering: Interview preparation tips for Java developers (June 2016)engineering.zalando.com