In short Atomic variables in Java are classes that provide lock-free, thread-safe operations on single variables.
Normally, when multiple threads access a shared variable (like a counter), you might use the synchronized keyword to prevent data corruption. Atomic variables provide a more efficient alternative.
The Problem:
Consider a simple counter: count++. Even though it looks like one step, the CPU actually performs three:
- Read the current value.
- Modify it (add 1).
- Write it back.
If two threads do this at the exact same time, they might both read "5," both increment it to "6," and save "6." One update is lost.
Compare-And-Swap (CAS)
Atomic variables don't use "locks" (which can be slow because they make threads wait). Instead, they use a low-level CPU instruction called CAS
Compare: The thread checks if the current value is still what it expected.
Swap: If it matches, it updates the value. If it doesn't match (meaning another thread changed it), it fails and usually tries again.
Why use them?
- They are generally faster than synchronized blocks because they avoid the overhead of "parking" and "waking up" threads.
- You don't have to worry about manual locking or deadlocks.
- They are perfect for small, specific updates to single values.
Top comments (0)