Mastering Java CAS: How AtomicInteger Achieves Lock‑Free Concurrency

This article explains the fundamentals of Compare‑And‑Swap (CAS), its implementation in Java through the Unsafe class, demonstrates AtomicInteger's lock‑free operations, and discusses CAS drawbacks such as spin‑wait overhead, single‑variable limitation, and the ABA problem with mitigation strategies.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
Mastering Java CAS: How AtomicInteger Achieves Lock‑Free Concurrency

In high‑concurrency scenarios, traditional synchronization using synchronized or Lock incurs significant performance overhead due to heavyweight locking. The article introduces Compare‑And‑Swap (CAS) as a lock‑free, optimistic‑locking alternative that many interview questions and real‑world systems rely on.

What is CAS?

CAS stands for Compare And Swap . It is a CPU‑supported atomic instruction that reads a memory location, compares its current value with an expected value, and, if they match, writes a new value. This operation is atomic and enables non‑blocking synchronization.

In Java, CAS underpins classes like AtomicInteger, ConcurrentHashMap, etc. Java itself does not implement CAS directly; it delegates to native code via the Unsafe class (e.g., compareAndSwapInt), which invokes the underlying CPU instruction.

CAS Workflow

The process involves three values: the original value A read before computation, the new value B calculated by business logic, and the current memory value C read again before committing. If A equals C , the update succeeds; otherwise, the operation retries.

CAS operation flowchart
CAS operation flowchart

Using CAS with AtomicInteger

Without CAS, a thread‑safe increment might use a synchronized method:

public class ThreadSafeTest {
    public static volatile int i = 0;
    public synchronized void increase() {
        i++;
    }
}

With CAS, the same logic becomes concise and lightweight:

public class ThreadSafeTest {
    private final AtomicInteger counter = new AtomicInteger(0);
    public int increase() {
        return counter.addAndGet(1);
    }
}

AtomicInteger provides several atomic APIs such as get(), getAndSet(), getAndIncrement(), getAndAdd(int delta), and lazySet(int newValue).

Core Implementation

The key part of AtomicInteger is:

public final int incrementAndGet() {
    return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}

During class initialization, Unsafe.objectFieldOffset obtains the memory offset of the value field. The getAndAddInt method performs a CAS loop:

public final int getAndAddInt(Object obj, long offset, int delta) {
    int prev;
    do {
        prev = this.getIntVolatile(obj, offset);
    } while (!this.compareAndSwapInt(obj, offset, prev, prev + delta));
    return prev;
}

This loop embodies a spin‑wait: if the CAS fails because another thread modified the value, the method retries until it succeeds.

Unsafe and CAS Mechanics

sun.misc.Unsafe

exposes low‑level operations such as memory access and CAS primitives. Although powerful, it is intended for JDK internal use and not for regular application code.

The CAS operation ultimately maps to a native CPU instruction (e.g., cmpxchg on x86), guaranteeing atomicity.

Drawbacks of CAS

Long spin loops can cause high CPU consumption when contention is heavy.

CAS only guarantees atomicity for a single variable; complex updates involving multiple variables require additional coordination.

The ABA problem: a value may change from A to B and back to A, misleading a CAS check. Solutions include versioned stamps (e.g., AtomicStampedReference) or adding a counter.

ABA Example

Thread P1 reads A, gets pre‑empted, P2 changes the value to B then back to A, and P1 proceeds, falsely assuming no change.

Summary

The article covers CAS concepts, the basic workflow, how AtomicInteger leverages CAS via Unsafe, and the limitations of CAS such as spin‑wait overhead, single‑variable restriction, and the ABA issue, along with common mitigation techniques.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CASlock‑freeunsafeABA problemAtomicInteger
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.