KatInterview

Identify and fix thread-safety bugs in a market data handler

BehavioralModel answer
MediumModel answerBehavioralconcurrencycode-reviewjava

Last 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

  1. Identify at least three significant problems with this implementation. Focus on thread-safety, atomicity, and design quality.
  2. Explain each problem clearly, including what can go wrong at runtime when multiple threads interact.
  3. Provide a corrected implementation that is thread-safe and addresses the design issues you identified. Use constructs from java.util.concurrent where 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.