Java Atomic vs Volatile vs Synchronized
Last Updated :
20 Aug, 2025
When working with multithreading in Java, ensuring thread safety becomes crucial. Java provides different mechanisms like synchronized, volatile and atomic variables to handle shared data across threads. While all three serve the purpose of synchronization in some way, they differ in how they achieve mutual exclusion, visibility and atomicity.
Synchronized
The synchronized keyword in Java is used to control access to shared resources among multiple threads. It can be applied to methods or blocks of code. When a method or block is declared as synchronized, only one thread can execute it on a given object at a time. This ensures data consistency and prevents race conditions.
Working of Synchronized Modifier:
- It can be applied to methods or blocks of code.
- When a method or block is synchronized, only one thread can execute it on a given object at any time.
- Every object in Java has an intrinsic lock associated with it. A thread must acquire this lock before entering a synchronized method or block.
- Synchronized code blocks may lead to thread contention, which can negatively impact performance, especially with excessive synchronization.
Volatile
The volatile keyword in Java ensures that all threads have a consistent view of a variable's value. It prevents caching of the variable's value by threads, ensuring that updates to the variable are immediately visible to other threads.
Working of Volatile Modifier:
- It applies only to variables.
- volatile guarantees visibility i.e. any write to a volatile variable is immediately visible to other threads.
- It does not guarantee atomicity, meaning operations like count++ (read-modify-write operations) can still result in inconsistent values.
Atomic Modifier
Atomic classes, such as AtomicInteger, are part of the java.util.concurrent.atomic package. These classes provide thread-safe operations on variables without the need for synchronization. They use low-level atomic operations like compare-and-swap (CAS) to ensure thread safety.
Working of Atomic Modifier:
- Atomic operations ensure atomicity of the read-modify-write actions on variables.
- These classes are lock-free and more efficient than synchronized blocks because they avoid the overhead of acquiring locks.
- Atomic operations are performed using methods like incrementAndGet(), compareAndSet() and getAndSet().
Synchronized vs Volatile vs Atomic
| Feature | Synchronized | Volatile | Atomic |
|---|
| Applies to | Methods/blocks | Variables | Variables |
| Purpose | Ensures mutual exclusion & consistency (via locks) | Ensures visibility (no atomicity) | Provides atomic operations (no locks) |
| Performance | Lower (due to locking) | Higher than synchronized | Higher than both synchronized & volatile |
| Concurrency | Prone to deadlocks/livelocks | Immune (no locks) | Immune (no locks) |
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java