Kar

Kar started this conversation 3 months ago.

0

1

java

Java race condition and thread-safety issues—incorrect concurrent counter result

In a multithreaded Java program using a shared counter object, the final value after both threads run is often lower than expected (e.g. less than 20000). Why does this happen and how can I fix it?

Digiaru

Posted 3 months ago

This is a classic race condition: the count++ operation is not atomic—it breaks into read modify write steps that can interleave across threads, leading to missed increments (turn0search6 sneppets+5ZetCode+5Codefiner+5baeldung.com+2Medium+2Reddit+2). Without synchronization or atomic types, threads may overwrite each other’s updates. One thread could read the old value and write it back after the other has already incremented it. Fixes: • Use synchronized blocks or methods to enforce mutual exclusion: java Copy code public synchronized void increment() { count++; } • Use atomic types like AtomicInteger: java Copy code private AtomicInteger count = new AtomicInteger(0); count.incrementAndGet();