Kar

Kar started this conversation 4 days ago.

0

1

java

Concurrency Pitfall: Race Condition on Shared Counter Without Synchronization or Volatile

I use a shared integer counter with count++ across threads. Even though I spawn many threads that increment it, the final value is consistently too low. Why?

Kar

Posted 4 days ago

count++ is not atomic—as it splits into read, modify, write, allowing race conditions. Additionally without volatile, threads may not see the updated value due to caching/memory model issues ([turn0search14]turn0search24]). Fixes: • Use synchronized keyword or ReentrantLock to serialize access. • Or use thread-safe classes like AtomicInteger: java Copy code private final AtomicInteger counter = new AtomicInteger(); counter.incrementAndGet(); • If using double-checked locking, mark instance field as volatile to ensure safe publication.