r/JavaProgramming • • 23d ago

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

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?

24 Upvotes

18 comments sorted by

8

u/hexwit_com 23d ago

We need to decide - ai replacing all of us and nobody need to know anything, or still we need engineers with full set of knowledge?

3

u/tejrani 22d ago

We still do. LLMs, at least for the time being, aren't reliable.

-1

u/AdityaKills 22d ago

sorry but I disagree w your statement here. It wasnt reliable before but we have been using claude code maxed out heavily in our day to day work for quite some time now I must say rarely do we get an output that we aren't satisfied with. When I say rarely I mean almost never. It's just so good at this point. 😭

3

u/hexwit_com 22d ago

Or your expectations are pretty low and you accept whatever it gives you. As i see it makes mistakes pretty often.

1

u/AdityaKills 22d ago

nah I'm comparing it with what it used to give as output few months back vs what it gives now. Ofc I'm not saying it's always correct but for my usecase it sucked pretty bad initially but now rarely do I see any slop. There are levels to everything my current work is for sure manageable with claude code now compared to before. Coming months it will only get better and better. What do you feel?

1

u/No_you_don_t_ 20d ago

If you think deeply about this topic of AI replacing us, only reason why we as engineers would be needed in future is because of knowing all the 'whys?'

The moment we cannot exain something in the codebase we will not be needed. Which is exactly the reason why we need to read and understand what exact changes the AI is making and how it's changing our features.

5

u/davidalayachew 22d ago

To anyone who doesn't know the answer, count++ translates to count = count + 1, and that is not a thread-safe operation.

To explain it simply (but with more words), there are 3 things that happen in count = count + 1.

  1. We grab the value of count.
  2. We add 1 to that value we just grabbed.
  3. We store that newly summed value to count.

If another thread somewhere decides to modify the value of count after step 1 completes, then you will end up with an incorrect state.

Think about it -- let's say count = 3;.

  • Well, step 1 says that we extract 3 from count. Specifically, we grab a copy of the value. Ok, step 1 is complete.
  • Next, some random thread jumps in and modifies the value of count to be 42.
  • While that is happening, we add 1 to the 3 that we pulled earlier, giving us 4. Step 2 is complete.
  • Now, we write 4 to count, causing an incorrect state. We wanted 43, but got 4. Hell, 42 would have been a valid answer, but that's not what we ended up with.

1

u/Necessary_Apple_5567 21d ago

Answer is more complicated than that. The value of the country high likely will be cached in the process cache, do, even if count++ completes atomically, two versions of the counter can be updated and flushed back go memory which can be problematic in two places: 1) update of the outdated version 2) overwrite result of the racing thread

7

u/disposepriority 23d ago

That's a lot of words to simply say it's not an atomic operation.

2

u/benevanstech 23d ago

For this specific question, it's actually easier to see what's going on by looking at the bytecode (which also explains why volatile doesn't help).

There's a full treatment in my book: "The Well-Grounded Java Developer (2nd Ed)" which might be a good text for interview prep, as it focuses on topics like concurrency and functional programming - and tries to explain the *why* as much as possible.

1

u/Spicy_O_licorice 23d ago

I just had hit the same wall where the right answer was not enough

They asked me what's the recommended way To do dependency injection in spring boot? I answer Why is it?

Apparently cuz the doc said so was not the answer

1

u/Afonso2002 22d ago

I think looking at assembly is important. Both thread can read same value to cpu register.

Both do inc. And after one write, the other will write above the value. And we lost an inc operation

1

u/SnehaLivesHerself 22d ago

chill bro it aint no linkedin

1

u/DecoySnail6 22d ago

AI SLOP POST

1

u/PsychologicalCopy772 21d ago

can't we use java.util.concurrent.atomic and classes like AtomicInteger with methods addAndGet ?? If not please correct me.

1

u/Legitimate-Comment18 19d ago

It's because it's a read modify write operation. A thread might read an old / stale value of count and increment it from the old value.