TGViewer
Coding Interview Preparation Coding Interview Preparation @coding_interview_preparation · 5.9K subscribers
Post #1366 318
🐛 SPOT THE BUG #2
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? 👇
More from @coding_interview_preparation
  1. Oct 8, 2026If you're prepping for system design interviews, this repo is gold It contains a curated,…
  2. Oct 6, 2026document post
  3. Oct 4, 2026💼 Why Your Resume Gets Rejected Before a Human Reads It You may have good skills and proj…
  4. Oct 2, 2026🧠 Coding Myths You Should Stop Believing There's a lot of advice online about learning to…
  5. Oct 1, 2026Most Asked Topics in AI Engineer Interviews Based on 2026 candidate reports
  6. Sep 30, 2026💼 What Companies Actually Look For in a Fresher Think companies only care about your CGPA…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →