Course contentsShow
← Java
Lesson 2685 of 2,87049. Synchronization and LockingFree lesson

volatile Does Not Provide Atomicity for Compound Actions

Understand that volatile count++ is still a race condition because increment is three separate operations: read, modify, write.

volatile Does Not Provide Atomicity for Compound Actions

What you'll learn: Why marking a variable volatile doesn't make operations like count++ thread-safe.

The Core Misunderstanding

Many developers assume that if they mark a shared counter as volatile, increment operations like count++ become thread-safe. This is false. While volatile guarantees visibility (every thread sees the latest value), it does not make compound actions atomic.

Why count++ Is Still a Race Condition

Even with a volatile int count, the expression count++ involves three distinct operations:

  1. Read the current value of count from memory
  2. Modify that value (add 1)
  3. Write the new value back to memory

Between any two of these steps, another thread can jump in and perform the same three steps, leading to lost updates—exactly the race condition we've studied before.

A Concrete Scenario

volatile int count = 0;

// Thread A reads count = 0
// Thread B reads count = 0
// Thread A increments to 1, writes back
// Thread B increments to 1 (from its read of 0), writes back
// Result: count = 1 (should be 2!)

The volatile keyword ensures each read sees the most recent write, but it cannot bundle these three operations into a single, indivisible action.

What volatile Actually Does

Remember: volatile establishes a happens-before relationship for individual reads and writes. It prevents caching issues. But atomicity—making multiple steps execute as one—requires synchronization or atomic classes, not volatile alone.

Key Takeaway: volatile guarantees visibility and ordering for single read/write operations, but compound actions like count++ remain non-atomic and subject to race conditions. Use synchronized blocks or atomic variables for thread-safe increments.