Difference Volatile and Atomic Variables
In Java, both volatile and atomic variables are used for achieving thread safety in concurrent programming, but they differ in their behavior and usage.

Table of Contents
Volatile Variables
- Volatile is a keyword in Java used to declare variables whose value may be modified by different threads.
- When a variable is declared as volatile, any thread that reads the variable always gets the most recent value written to it by any other thread.
- Volatile ensures visibility of changes across threads, meaning that changes made by one thread to a volatile variable are immediately visible to other threads.
- However, volatile does not provide atomicity or synchronization for compound actions, such as incrementing a counter, which may involve multiple steps.
Atomic Variables
- Atomic variables are special variables provided by the java.util.concurrent.atomic package that support atomic operations on their values.
- These variables provide atomicity guarantees for compound actions, such as read-modify-write operations like incrementing a counter.
- Atomic variables use low-level CPU instructions (compare-and-swap or CAS operations) to ensure that updates to the variable’s value are atomic and thread-safe.
- Unlike volatile, atomic variables provide both visibility and atomicity guarantees, making them suitable for scenarios where compound actions need to be performed atomically and thread-safely.
Example
java
import java.util.concurrent.atomic.AtomicInteger;
public class VolatileVsAtomicExample {
private volatile int volatileCounter = 0;
private AtomicInteger atomicCounter = new AtomicInteger(0);
// Increment volatile counter
public void incrementVolatileCounter() {
volatileCounter++;
}
// Increment atomic counter
public void incrementAtomicCounter() {
atomicCounter.incrementAndGet();
}
// Get volatile counter value
public int getVolatileCounter() {
return volatileCounter;
}
// Get atomic counter value
public int getAtomicCounter() {
return atomicCounter.get();
}
}
In this example, we have a class volatile and atomic variables with two counters: volatileCounter and atomicCounter. The volatileCounter is declared as volatile, and the atomicCounter is an instance of AtomicInteger, an atomic variable. The incrementVolatileCounter() method increments the volatileCounter using the ++ operator, which is not atomic and may lead to race conditions. On the other hand, the incrementAtomicCounter() method increments the atomicCounter using the atomic incrementAndGet() method, ensuring atomicity and thread safety.