All 15 Concurrency & Threads questions
More in Concurrency & Threads
Advertisement
Back to results for “JRE & Memory”
Java › Concurrency & Threads

What are the atomic classes in java.util.concurrent.atomic (AtomicInteger, AtomicLong, AtomicReference), and how do they achieve thread-safe operations without traditional locking?

Intermediate

Answer

Atomic classes use hardware-level compare-and-swap (CAS) instructions (a single atomic CPU operation that conditionally updates a value only if it still matches an expected prior value) to implement thread-safe increment/update operations without acquiring a traditional lock -- this lock-free approach avoids the overhead and contention of synchronized/ReentrantLock for simple single-variable atomic operations, generally performing better under moderate contention, though CAS-based operations can spin-retry under very high contention (many threads simultaneously attempting to update the same atomic variable), at which point traditional locking might actually perform comparably or better.
private final AtomicInteger counter = new AtomicInteger(0);

public void increment() {
    counter.incrementAndGet();  // atomic, thread-safe, no explicit lock needed
}

public int compareAndUpdate(int expected, int newValue) {
    return counter.compareAndSet(expected, newValue) ? newValue : counter.get();
}
Real-world example A high-throughput metrics collection system tracking a shared request counter across many concurrent request-handling threads uses AtomicLong instead of a synchronized increment method, achieving better throughput under the metrics system's specific access pattern by avoiding traditional lock acquisition/release overhead entirely for this simple counting operation.

Common follow-ups: How does compare-and-swap (CAS) work at the CPU instruction level to achieve atomicity without a traditional lock?;Under what contention conditions might a CAS-based atomic actually perform worse than a traditional lock?