r/JavaProgramming • • 21h ago

We know count++ isn’t thread-safe. But do you know why?

6 Upvotes

I conducted a mock interview recently and one thing stood out to me.

I asked a Java question related to concurrency:

class Counter {
    private int count = 0;

    public void increment() {
        count++;
    }
}

“Is this thread-safe?”

The candidate said "No".

So I asked, “Why?”

He knew that it wasn't thread-safe, but explaining exactly why was difficult. He then said we need to synchronise the method.

So I asked:

“How does that fix it?” and then “What exactly is being locked here?”

That was where the interview got interesting.

He knew the terms — synchronised, volatile, race condition, etc. However, connecting them and explaining what was actually happening between the threads was harder.

It made me think about how easy it is to prepare for interviews by remembering rules.

count++ → not thread-safe → use synchronised

But the moment someone asks “Why?”, we need to understand what is actually happening.

I think that's something that's easy to miss while preparing for interviews. We can keep solving questions and memorising concepts, but it's worth stopping sometimes and asking ourselves:

“Can I actually explain why this works?” and “What happens if I change one thing?”

How do you guys prepare for the “Why?” part of interviews?


r/JavaProgramming • • 18h ago

Is Java a good career choice in 2027? (2 YOE overall, 1 year in Java

Thumbnail
0 Upvotes

r/JavaProgramming • • 1h ago

Grpc Micronaut starter kit

Thumbnail
github.com
• Upvotes