Understanding AtomicInteger: Optimistic Locking and CAS in Java
AtomicInteger provides a thread‑safe, lock‑free counter in Java by employing optimistic locking and CAS operations, offering higher efficiency than synchronized blocks; the article explains its motivation, usage examples, underlying Unsafe mechanisms, volatile semantics, and key methods such as incrementAndGet and compareAndSet.
1. Why introduce AtomicInteger?
When discussing thread safety, synchronized and Lock are often mentioned, but they are pessimistic locks that allow only one thread at a time and can be inefficient; optimistic locking avoids locking by retrying on conflict, and AtomicInteger implements this, offering higher efficiency.
AtomicInteger guarantees thread safety using optimistic locking, making it more efficient than pessimistic locks.
When multiple threads perform CAS on a variable, only one succeeds while others fail and can retry or give up.
2. AtomicInteger principle analysis
2.1 Specific usage
To count web page visits, a simple count++ is not thread‑safe.
Lock‑based implementation:
class Counter {
private volatile int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}AtomicInteger implementation:
class Counter {
//使用AtomicInteger之后,不需要加锁,也可以实现线程安全。
private AtomicInteger count = new AtomicInteger();
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}2.2 Underlying mechanism
AtomicInteger defines a static Unsafe instance and a valueOffset that points to the memory offset of the internal volatile int field.
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset(
AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}Unsafe is a JDK internal class that provides low‑level operations such as compareAndSwapInt .
sun.misc.Unsafe is an internal JDK utility that exposes unsafe operations to Java code, enabling platform‑specific functionality without native code.
The volatile int value field ensures visibility and prevents reordering.
private volatile int value;Volatile guarantees two main features: preventing reordering and providing memory visibility.
Memory visibility means that when one thread updates a shared variable, other threads can see the updated value.
AtomicInteger’s key methods include incrementAndGet() (equivalent to i++ ) and getAndAdd() (equivalent to i+=n ).
The source of incrementAndGet() shows a loop that reads the current value, computes the next value, and uses compareAndSet to atomically update it.
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}The compareAndSet method performs a CAS operation via Unsafe , comparing the expected value with the current memory value and updating it if they match.
Each CAS reads the value at the memory offset, compares it with the expected value, and updates it only if they are equal; otherwise the operation fails and can be retried.
This lock‑free approach guarantees atomicity without additional synchronization.
Other atomic classes such as AtomicLong and AtomicBoolean share the same principle.
3. Simple explanation
(1) The volatile keyword on the value field ensures visibility across threads; each thread reads the latest value from main memory.
(2) Unsafe provides the atomic CAS operation, so users do not need extra synchronization; compareAndSetInt is a native‑implemented CAS.
The principle is: compare the memory value with the expected one; if they match, assign the new value and return true , otherwise return false .
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.