← Back to Chapters

Atomic Variables

⚛️ Atomic Variables

? Quick Overview

Atomic variables in Java provide a way to perform thread-safe operations on single variables without using explicit synchronization. They are part of the java.util.concurrent.atomic package and are widely used in high-performance, multi-threaded applications.

? Key Concepts

  • Lock-free and thread-safe operations
  • Uses low-level CPU instructions (CAS – Compare And Swap)
  • Better performance than synchronized blocks in many cases
  • Works on single variables, not multiple related variables

? Syntax / Theory

Common atomic classes provided by Java:

  • AtomicInteger
  • AtomicLong
  • AtomicBoolean
  • AtomicReference

Atomic variables ensure visibility and atomicity without blocking other threads.

? Code Example(s)

? View Code Example
// Demonstrates AtomicInteger for thread-safe counting
import java.util.concurrent.atomic.AtomicInteger;

class AtomicDemo {
static AtomicInteger counter = new AtomicInteger(0);

public static void main(String[] args) {
Runnable task = () -> {
for(int i = 0; i < 1000; i++) {
counter.incrementAndGet();
}
};

Thread t1 = new Thread(task);
Thread t2 = new Thread(task);

t1.start();
t2.start();
}
}

? Interactive: How CAS (Compare-And-Swap) Works

Atomic variables rely on CAS. They only update memory if the value hasn't changed since you last read it.

? Shared Memory (RAM)

0

Real value seen by all threads

? Your Thread

Expected: 0
New: 1
Ready to update...

? Live Output / Explanation

Explanation

Both threads increment the same AtomicInteger. The method incrementAndGet() guarantees that each increment is atomic, so no updates are lost, even without synchronized.

✅ Tips & Best Practices

  • Use atomic variables for simple shared counters or flags
  • Prefer atomic classes over synchronized for better scalability
  • Do not use atomic variables for complex multi-step logic
  • Combine with higher-level concurrency utilities when needed

? Try It Yourself / Practice Tasks

  • Create a program using AtomicBoolean to control thread execution
  • Replace a synchronized counter with AtomicLong
  • Experiment with compareAndSet() method