LLD Guide · Module 1: Foundations · Lesson 01.02
Thread-Safety Essentials for LLD Problems
The five concurrency bugs graders catch, and the Java tools that prevent them.
By Cruscible Engineering · Published
Your solution passes every scenario when you test it by hand, then fails on submit. Nine times out of ten, the grader called it from many threads at once.
Chapter 2 of the LLD Guide. Chapter 1 explained that the grader runs concurrent scenarios. This chapter is about surviving them.
1. Why it matters here
Real systems take concurrent requests, so the grader does too: many threads call your object at the same moment, and then a check runs. It might check a counter, a remaining capacity, a balance, or that no id was handed out twice. If two threads interleave badly even once, the check fails.
The goal is not "use lots of locks". The goal is that every invariant in the brief holds no matter how calls interleave.
2. Bug 1: check-then-act
The most common race. Two threads both see a free spot, and both take it:
// ❌ Broken under concurrency
public boolean park(String plate) {
if (freeSpots > 0) { // thread A and B both read 1
freeSpots--; // both decrement: -1
parked.add(plate);
return true;
}
return false;
}
Figure: Two threads parking in the last free spot, without and with a lock
- Without a lock: both threads read freeSpots = 1, both take the spot, and freeSpots becomes -1.
- With a lock: thread A checks and takes the spot while B waits; B then sees 0 and returns false.
The check and the act must be one atomic step. The simplest fix is to lock the whole operation:
private final Object lock = new Object();
public boolean park(String plate) {
synchronized (lock) {
if (freeSpots == 0) return false;
freeSpots--;
parked.add(plate);
return true;
}
}
💡 Tip: Start with one lock around every method that reads and writes shared state. It is correct, and for most LLD problems it is fast enough. Optimise only if the performance part of your score says so.
3. Bug 2: "thread-safe" collections used unsafely
ConcurrentHashMap makes each individual call safe, not a sequence of calls:
// ❌ Two threads can both miss and both insert
if (!counts.containsKey(user)) {
counts.put(user, 0);
}
counts.put(user, counts.get(user) + 1); // lost updates
Use the atomic compound methods instead:
counts.merge(user, 1, Integer::sum); // atomic increment
sessions.computeIfAbsent(id, k -> new Session(k)); // create once
stock.computeIfPresent(sku, (k, v) -> v > 0 ? v - 1 : v); // atomic, never below 0
⚠️ Trap: Keep the function you pass to
computeshort and free of side effects. Don't call another method that touches the same map from inside it.
4. Bug 3: counters and ids
count++ on a plain long is three steps: read, add, write. Use an atomic:
private final AtomicLong nextId = new AtomicLong(1);
public long createTicket() {
return nextId.getAndIncrement(); // unique across threads
}
AtomicInteger, AtomicLong and LongAdder cover counters, ids and statistics. LongAdder is faster when many threads only add and you read rarely.
5. Bug 4: state spread over two structures
Most real bugs live here. An LRU cache has a map and a recency list. A booking system has a seat map and a waitlist. Both structures must change together, or another thread can see one updated and the other not:
// Map and list always change under the same lock
private final Map<String, Node> index = new HashMap<>();
private final Deque<Node> order = new ArrayDeque<>();
private final ReentrantLock lock = new ReentrantLock();
public void put(String key, String value) {
lock.lock();
try {
Node old = index.remove(key);
if (old != null) order.remove(old); // O(n) here; the LRU walkthrough makes it O(1)
Node n = new Node(key, value);
index.put(key, n);
order.addFirst(n);
if (index.size() > capacity) {
Node lru = order.removeLast();
index.remove(lru.key);
}
} finally {
lock.unlock();
}
}
⚠️ Trap: Using two separate concurrent collections does not make this safe. Safety comes from one lock covering both changes.
6. Bug 5: holding a lock while doing slow work
A single lock is fine until one thread holds it during a slow call, a Redis round trip or a SQL query, and every other thread queues behind it. Two rules:
- Keep critical sections small. Compute outside the lock, and lock only to read or publish shared state.
- Don't hold a Java lock across a database call if the database can do the coordination itself. A conditional
UPDATEor a Lua script is atomic on the server and doesn't block your other threads. Chapters 3 and 4 cover how.
When reads far outnumber writes, a ReentrantReadWriteLock lets readers proceed in parallel:
private final ReadWriteLock rw = new ReentrantReadWriteLock();
public Config get(String key) {
rw.readLock().lock();
try { return configs.get(key); } finally { rw.readLock().unlock(); }
}
public void set(String key, Config c) {
rw.writeLock().lock();
try { configs.put(key, c); } finally { rw.writeLock().unlock(); }
}
7. Visibility: the bug you can't see
Without synchronization, one thread may never see another thread's write. A plain boolean open flag in a circuit breaker can be read stale indefinitely. Any field that is read and written by different threads must be either:
- accessed only under the same lock, or
volatile(for a single value that is set and read, never read-modify-written), or- an
Atomic*.
8. A checklist before you submit
- Every field: who writes it, who reads it, and under which lock?
- Every
if (...)followed by a write: is the pair atomic? - Every invariant in the brief: can two interleaved calls break it?
- Every lock: is it released in
finally? - Every lock: is anything slow happening while it's held?
You can test it yourself before submitting: start 50 threads that each call your method 1,000 times, then check the invariant.
ExecutorService pool = Executors.newFixedThreadPool(50);
for (int i = 0; i < 50_000; i++) {
final int n = i; // lambdas need an effectively final copy
pool.submit(() -> cache.put("k" + (n % 100), "v"));
}
pool.shutdown();
pool.awaitTermination(30, TimeUnit.SECONDS);
// assert: the size never exceeds capacity, and no exception was thrown
Further reading
ConcurrentHashMap(Java 17 API)ReentrantLock(Java 17 API)ReentrantReadWriteLock(Java 17 API)AtomicLong(Java 17 API)- Java memory model: threads and locks (JLS 17, chapter 17)
Takeaways
- Atomicity is about operations, not data structures: make each contract method one atomic step.
- One lock around everything is a correct starting point, and usually a sufficient one.
- Don't hold Java locks across Redis or SQL calls. Let the server do it atomically instead.
Try it yourself: Build an LRU Cache (two structures, one lock) and Build a Railway Reservation System (capacity invariants under concurrent booking).