Identify and fix thread-safety bugs in a market data handler
BehavioralModel answerLast updated
Spot concurrency flaws, atomicity gaps, and design issues in a multi-threaded price tracking class, then refactor it to be thread-safe.
Context
You're reviewing code written by a teammate. The class below is meant to handle live price updates for a stock ticker in a multi-threaded environment. Multiple threads call onUpdate concurrently as new market data arrives, while other threads read the latest price and the total number of updates received.
public class PriceProcessor {
private volatile double latestPrice;
private int updateCount = 0;
private String ticker = "AAPL";
public void onUpdate(double newPrice) {
latestPrice = newPrice;
updateCount++;
System.out.println("Updated " + ticker + " to " + latestPrice);
}
public double getLatestPrice() {
return latestPrice;
}
public int getUpdateCount() {
return updateCount;
}
}
Your Task
- Identify at least three significant problems with this implementation. Focus on thread-safety, atomicity, and design quality.
- Explain each problem clearly, including what can go wrong at runtime when multiple threads interact.
- Provide a corrected implementation that is thread-safe and addresses the design issues you identified. Use constructs from
java.util.concurrentwhere appropriate.
Be specific about why volatile on latestPrice alone doesn't solve the concurrency problems, and discuss what guarantees are missing.
Hints
Hint 1
The `volatile` keyword provides visibility but not atomicity—think about multi-step operations like increment.
Hint 2
Consider whether a reader can observe an inconsistent view when price and count are updated separately.
Hint 3
Evaluate whether side effects like console output belong in the critical path of a high-throughput data handler.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
A strong answer walks through each flaw methodically, explains the runtime failure mode with concrete thread interleavings, and produces a refactor that eliminates the root causes rather than just wrapping everything in synchronized.
Problem 1: updateCount lacks both visibility and atomicity
The field updateCount is a plain int with no synchronization. This creates two separate issues:
Visibility: Without volatile or a lock, writes to updateCount from one thread may never become visible to another thread reading getUpdateCount(). The Java Memory Model doesn't guarantee a happens-before relationship, so a reader can see stale values indefinitely or even have the JIT hoist the read out of a loop.
Atomicity: Even marking updateCount as volatile wouldn't be sufficient. The expression updateCount++ decomposes into three steps: read the current value, add one, write back. volatile makes each individual read and write visible but doesn't make the three-step sequence atomic. Two threads can interleave like this:
Thread A: read 10
Thread B: read 10
Thread A: write 11
Thread B: write 11 ← one update lost
Under load, the count falls behind the true number of updates. The fix is to use AtomicInteger or AtomicLong, which provides atomic read-modify-write operations like incrementAndGet(). Alternatively, use LongAdder for extremely high contention scenarios.
Problem 2: Updates to price and count are not atomic as a unit
Even if both fields were individually thread-safe, the class maintains an invariant—(latestPrice, updateCount) should represent a consistent snapshot—but updates them in separate steps with no coordination.
Torn reads: A reader can observe the new price with the old count, or vice versa. Calling getLatestPrice() followed by getUpdateCount() may return values from different updates entirely, making monitoring and debugging misleading.
Inconsistent log output: The println statement re-reads latestPrice from the field instead of using the local parameter newPrice. If Thread 1 writes 101.50 and Thread 2 immediately writes 102.00, Thread 1 might print "Updated AAPL to 102.00" because it reads the field after Thread 2 has modified it. In a trading system, incorrect audit logs are a serious defect.
No ordering guarantees: With concurrent writers, the last thread to complete its write wins, which may not correspond to the most recent market tick. Real market data feeds include sequence numbers or exchange timestamps to handle out-of-order delivery. You should acknowledge this limitation even if you don't fully solve it in the refactor.
Problem 3: Design and maintainability issues
Hard-coded ticker: The string "AAPL" is baked in, and the field isn't final. You can't reuse this class for other symbols or easily write unit tests with different tickers. The ticker should be injected via the constructor and marked final.
Single Responsibility Principle violation: The class both processes prices and logs to the console. System.out.println is synchronized internally and performs blocking I/O, which serializes all threads on a global lock. This adds latency in a critical path. Move side effects to an injected callback or use an asynchronous logger.
Using double for financial data: Binary floating-point types can't represent most decimal prices exactly (e.g., 0.1 has no exact representation). Use BigDecimal or represent prices as integer cents/ticks (long).
No input validation: The method accepts NaN, negative, or zero prices without complaint. These should be rejected.
Not designed for safe use: The class isn't final, and there's no documentation of its thread-safety contract. Fields like ticker could be accidentally modified by a subclass or external code.
Refactored Implementation
The cleanest approach is to model the state as an immutable snapshot and publish it atomically using AtomicReference. Each update replaces the entire snapshot in one indivisible step, which fixes visibility, atomicity, and torn reads together without explicit locks.
import java.math.BigDecimal;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
/**
* Thread-safe price processor. All state is published atomically
* as an immutable Snapshot.
*/
public final class PriceProcessor {
public record Snapshot(String ticker, BigDecimal latestPrice, long updateCount) {}
private final String ticker;
private final AtomicReference<Snapshot> state;
private final Consumer<Snapshot> listener;
public PriceProcessor(String ticker, Consumer<Snapshot> listener) {
if (ticker == null || ticker.isBlank()) {
throw new IllegalArgumentException("ticker must be non-blank");
}
this.ticker = ticker;
this.listener = Objects.requireNonNull(listener, "listener");
this.state = new AtomicReference<>(new Snapshot(ticker, null, 0L));
}
public Snapshot onUpdate(BigDecimal newPrice) {
Objects.requireNonNull(newPrice, "newPrice");
if (newPrice.signum() <= 0) {
throw new IllegalArgumentException("price must be positive: " + newPrice);
}
// The lambda must be pure; it may execute multiple times under CAS contention.
Snapshot updated = state.updateAndGet(
prev -> new Snapshot(ticker, newPrice, prev.updateCount() + 1)
);
// Invoke side effects outside the atomic update.
listener.accept(updated);
return updated;
}
/** Returns a consistent snapshot of price and count. */
public Snapshot snapshot() {
return state.get();
}
public BigDecimal getLatestPrice() {
return state.get().latestPrice();
}
public long getUpdateCount() {
return state.get().updateCount();
}
public String getTicker() {
return ticker;
}
}
Usage example:
PriceProcessor processor = new PriceProcessor(
"AAPL",
snapshot -> logger.info("Updated {} to {}", snapshot.ticker(), snapshot.latestPrice())
);
processor.onUpdate(new BigDecimal("150.25"));
In tests, you can pass a no-op lambda or one that captures values for assertions.
Key Points to Emphasize
- The update function passed to
updateAndGetmust be pure (no side effects), because the CAS loop may retry it multiple times under contention. - The listener receives the exact snapshot this thread produced, so the logged price is always accurate.
- Listener invocations from different threads can still arrive out of order. If strict ordering matters, funnel updates through a single writer thread (e.g., a per-ticker single-threaded executor).
- Using
longfor the count avoids overflow in practice (would take centuries at millions of updates per second).
An alternative solution using synchronized methods that guard both fields and invoke the listener outside the lock is also acceptable. Explain your choice: lock-based approaches are simpler but can become bottlenecks; lock-free designs scale better but are harder to reason about.
Edge Cases and Extensions
- Uninitialized reads: Readers calling
getLatestPrice()before the first update receivenull. Document this behavior or returnOptional<BigDecimal>. - Listener exceptions: If the listener throws, the state has already been updated. Decide whether to catch and log the exception or let it propagate.
- Out-of-sequence ticks: If order matters, include a sequence number in the snapshot and use a CAS that rejects stale updates.
- High read frequency: This design is efficient for readers—one volatile load returns both price and count in a consistent snapshot.
Common Follow-Up: Heavy Computation Before Updating
Q: What if you need to run an expensive calculation (e.g., computing a derived metric) before updating the state?
A: Perform the computation outside any lock or atomic operation, using only the input parameters. Once the result is ready, publish it atomically. Never hold a lock during expensive work. If the computation depends on the previous state and a CAS loop would redo the work on every retry, prefer a single-writer architecture: route updates through a per-ticker single-threaded executor or a lock-free queue (like Disruptor). This also preserves tick ordering naturally.
Complexity
Time: O(1) per update in the uncontended case; O(k) under contention where k is the number of retries (typically very low). Reads are always O(1).
Space: O(1) per instance.