0Pricing
Java Academy · Lesson

Atomic Variables: Lock-Free Updates

Use AtomicInteger, AtomicLong, and AtomicReference for thread-safe counters without locks.

The Problem with Non-Atomic Operations

Simple increment count++ is NOT thread-safe — it's three operations: read, add, write. Concurrent threads can interleave these, causing lost updates. Atomic variables solve this without locks.

// UNSAFE:
int count = 0;
// Thread A reads count=0, Thread B reads count=0
// Both write 1 — second update lost!
count++; // NOT thread-safe

// SAFE:
import java.util.concurrent.atomic.*;
AtomicInteger atomicCount = new AtomicInteger(0);
atomicCount.incrementAndGet(); // atomic, lock-free

AtomicInteger Basics

AtomicInteger provides integer operations that are guaranteed to be atomic using CPU compare-and-swap (CAS) instructions — no locks needed.

AtomicInteger counter = new AtomicInteger(0);

counter.set(10);                   // set to 10
System.out.println(counter.get()); // 10

int prev = counter.getAndIncrement(); // returns 10, sets to 11
int curr = counter.incrementAndGet(); // sets to 12, returns 12
counter.addAndGet(5);                 // adds 5, returns 17
counter.decrementAndGet();            // subtracts 1, returns 16

All lessons in this course

  1. ReentrantLock vs synchronized
  2. ReadWriteLock for Reader-Writer Scenarios
  3. Atomic Variables: Lock-Free Updates
  4. StampedLock and Optimistic Reads
← Back to Java Academy