Language: Java
java
public class Counter {
private int count;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
// Used across 10 threads simultaneously calling increment()
What breaks under concurrent access? 👇
.
.
.
The bug:
count++ is NOT atomic. It's actually three operations: read, increment, write. Two threads can read the same value, both increment it, and both write back the same result - losing an update. With 10 threads hammering this, your final count will almost always be less than expected.Fixed version:
java
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
Alternative fix: mark
increment() as synchronized, though that's slower under high contention than AtomicInteger.This is one of the most common concurrency bugs in real production systems, not just interviews. Ever debugged something like this in the wild? 👇