Volatile

Volatile Keyword

The volatile modifier is used to inform the JVM that a variable’s value may be changed by multiple threads. It ensures that every thread reads the latest value directly from main memory instead of using a cached copy.

Key Points

  • Applicable only for variables
  • Used in multithreading to avoid data inconsistency
  • Ensures visibility of changes across threads

If multiple threads modify a variable, there may be data inconsistency. Using volatile ensures all threads see the updated value.

Advantages

  • Solves data inconsistency (visibility problem)

Disadvantages

  • No mutual exclusion (not thread-safe for operations)
  • May impact performance
Note: final means value never changes, whereas volatile means value may change frequently. Hence, final + volatile is illegal.

Example

public class MyRunnable implements Runnable {

    private volatile boolean active;

    public void run() {
        active = true;
        while (active) {
        }
    }

    public void stop() {
        active = false;
    }
}

Memory Visibility

In multithreading, each thread may have its own cached copy of variables. Updates made by one thread may not be immediately visible to others.

Processors often use write buffers, so updates are delayed before reaching main memory. This causes visibility problems.

The volatile keyword ensures that updates are directly written to main memory and are visible to all threads immediately.

Volatile vs Synchronization

  • Mutual Exclusion: Only one thread executes at a time (provided by synchronized)
  • Visibility: Changes are visible to all threads (provided by volatile)

synchronized provides both mutual exclusion and visibility but affects performance.

volatile provides only visibility, not mutual exclusion. It is useful when multiple threads can run simultaneously but must see updated values.

0 Comments