What is Atomic Variable in Java: Explanation and Example
atomic variable in Java is a special kind of variable that supports safe, lock-free, thread-safe operations on single values. It ensures that operations like increment or update happen completely without interruption, preventing data errors in multi-threaded programs.How It Works
Imagine you have a shared counter that many people want to update at the same time. If they all try to change it at once, the final count might be wrong because their actions overlap. An atomic variable acts like a magic counter that only lets one person change it at a time, but without using slow locks.
It uses special CPU instructions to make sure each change is done fully before another starts. This means threads can safely update the variable without waiting in line, making programs faster and correct.
Example
This example shows how to use AtomicInteger to safely increment a number from multiple threads.
import java.util.concurrent.atomic.AtomicInteger; public class AtomicExample { private static AtomicInteger count = new AtomicInteger(0); public static void main(String[] args) throws InterruptedException { Runnable task = () -> { for (int i = 0; i < 1000; i++) { count.incrementAndGet(); } }; Thread thread1 = new Thread(task); Thread thread2 = new Thread(task); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.println("Final count: " + count.get()); } }
When to Use
Use atomic variables when you need to update simple values like counters or flags safely in programs where many threads run at the same time. They are perfect when you want fast, thread-safe updates without the overhead of locking.
For example, counting user clicks on a website, tracking how many tasks finished in a thread pool, or managing simple shared states in concurrent applications.
Key Points
- Atomic variables provide thread-safe operations without locks.
- They use low-level CPU instructions for fast updates.
- Common classes include
AtomicInteger,AtomicLong, andAtomicReference. - Ideal for simple shared data in multi-threaded programs.