0Pricing
Java Academy · Lesson

Atomic Variables: Lock-Free Updates

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

Atomic Variables: Lock-Free Updates is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

compareAndSet: The CAS Operation

compareAndSet(expected, update) atomically updates the value only if it currently equals the expected value. Returns true if successful. This is the foundation of all lock-free algorithms.

AtomicInteger ai = new AtomicInteger(5);

boolean updated = ai.compareAndSet(5, 10); // current==5? set to 10
System.out.println(updated); // true
System.out.println(ai.get()); // 10

boolean failed = ai.compareAndSet(5, 20); // current==10, not 5 → fails
System.out.println(failed); // false
System.out.println(ai.get()); // still 10

AtomicLong for Counters

AtomicLong is the 64-bit equivalent. Common for sequence generators and hit counters:

AtomicLong seq = new AtomicLong(0);

// Thread-safe sequence generator:
long nextId() {
    return seq.incrementAndGet();
}

System.out.println(nextId()); // 1
System.out.println(nextId()); // 2
System.out.println(nextId()); // 3

AtomicBoolean

Thread-safe boolean flag. Commonly used for one-time initialization or shutdown signals:

AtomicBoolean initialized = new AtomicBoolean(false);

void initOnce() {
    // compareAndSet: only first caller succeeds
    if (initialized.compareAndSet(false, true)) {
        System.out.println("Initializing...");
        // perform expensive init
    } else {
        System.out.println("Already initialized");
    }
}

AtomicReference

AtomicReference<V> provides atomic updates to an object reference. Used to implement lock-free data structures:

import java.util.concurrent.atomic.*;

record Config(String host, int port) {}

AtomicReference<Config> configRef =
    new AtomicReference<>(new Config("localhost", 8080));

// Hot-swap the configuration atomically:
Config oldConfig = configRef.get();
Config newConfig = new Config("prod.example.com", 443);

boolean swapped = configRef.compareAndSet(oldConfig, newConfig);
System.out.println(swapped); // true
System.out.println(configRef.get()); // Config[host=prod.example.com, port=443]

updateAndGet / getAndUpdate

Apply a function atomically using a CAS retry loop internally:

AtomicInteger value = new AtomicInteger(10);

// Apply function atomically: square the value
int newVal = value.updateAndGet(x -> x * x);
System.out.println(newVal); // 100

// Get old, then apply:
int old = value.getAndUpdate(x -> x + 1);
System.out.println(old);   // 100
System.out.println(value.get()); // 101

accumulateAndGet

Combine current value with a given value using a function:

AtomicInteger max = new AtomicInteger(0);

// Keep running maximum:
max.accumulateAndGet(42, Math::max); // max(0, 42) = 42
max.accumulateAndGet(15, Math::max); // max(42, 15) = 42
max.accumulateAndGet(99, Math::max); // max(42, 99) = 99

System.out.println(max.get()); // 99

LongAdder for High-Contention Counters

Under high thread contention, AtomicLong's CAS retries can hurt performance. LongAdder uses multiple cells to reduce contention:

import java.util.concurrent.atomic.*;

LongAdder adder = new LongAdder();

// Multiple threads can call add() with minimal contention:
adder.increment();
adder.add(5);
adder.increment();

System.out.println(adder.sum()); // 7
// Note: sum() is NOT atomic with add() — use only when no concurrent adds

Atomic Arrays

AtomicIntegerArray / AtomicLongArray provide atomic operations on individual array elements:

AtomicIntegerArray arr = new AtomicIntegerArray(5);

arr.set(0, 10);
arr.incrementAndGet(0);
arr.compareAndSet(2, 0, 42); // index 2: if 0, set 42

System.out.println(arr.get(0)); // 11
System.out.println(arr.get(2)); // 42

When to Use Atomics vs Locks

Use atomic variables when:

  • Single-variable updates (counters, flags, references)
  • Low contention scenarios
  • Lock-free performance is important

Use locks when:

  • Multiple variables must be updated atomically
  • Complex conditional logic is needed
  • Very high contention (CAS retries hurt)

Quick Check

What does compareAndSet(expected, update) guarantee?

Recap: Atomic Variables

Key takeaways:

  • Atomic types use CPU CAS instructions — lock-free and thread-safe
  • AtomicInteger/Long/Boolean/Reference for single-variable atomicity
  • compareAndSet is the foundation of lock-free algorithms
  • updateAndGet/accumulateAndGet for functional updates
  • LongAdder for high-contention counter scenarios

Frequently asked questions

Is the “Atomic Variables: Lock-Free Updates” lesson free?

Yes — the full text of “Atomic Variables: Lock-Free Updates” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Atomic Variables: Lock-Free Updates”?

Use AtomicInteger, AtomicLong, and AtomicReference for thread-safe counters without locks. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Atomic Variables: Lock-Free Updates” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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