Atomic Variables in Java: AtomicInteger, AtomicLong and CAS Explained
-
Last Updated: October 21, 2026
-
By: javahandson
-
Series

Atomic variables in Java give lock-free, thread-safe updates. Learn AtomicInteger, AtomicLong, AtomicReference, CAS, and when LongAdder wins under contention.
Atomic variables in Java let many threads update one shared value safely, and they do it without any lock. They live in the java.util.concurrent.atomic package. Classes like AtomicInteger, AtomicLong and AtomicReference are the stars here.
You may already know that volatile makes a variable visible across threads. But visibility is only half the story. A counter shared by many threads needs more than that. This is exactly the gap atomic variables fill.
In this guide we will build that idea from the ground up. We start with the bug, then meet the atomic classes, then open up the CAS trick that makes them tick. By the end you will build a lock-free counter and know when to use one.
Let us start with a story. Picture an online store with one phone left in stock. Two buyers tap “Buy” at the same instant. Both threads read the stock count as 1. Both check that 1 is greater than 0, so both say yes. Then both reduce the count by one. You just sold one phone twice, and your stock reads minus one.
That bug is a race condition, and it comes from a value that two threads change at once. Now the question is simple. Does volatile save us here? Sadly, no. Let us see why.
The volatile keyword tells the JVM that a variable can change at any time. Every read goes to main memory, and every write lands there too. So one thread always sees the latest value another thread wrote. That part is genuinely solved.
Here is the catch. volatile gives you visibility, but not atomicity. These are two different promises, and people mix them up all the time. For the full mechanics of visibility and the happens-before rule, the dedicated guide volatile Keyword in Java Explained covers it in depth. We will not repeat that ground here.
Take a simple line like count++. It looks like one action. The CPU actually treats it as three separate steps.
Now imagine two threads run count++ at the same moment. Both read the value 5. Both add one and get 6. After that, both write 6 back. You expected 7, but you got 6. One update just vanished into thin air. We call this a lost update.
A volatile int does not help here. Each read and each write is visible, sure. Yet the three steps still happen apart, so two threads still overlap. Visibility cannot glue the steps into one action.
| 💡 Interview Insight A favourite interview trap: “If I make my counter volatile, is count++ thread-safe?” The honest answer is no. volatile fixes visibility, not the read-modify-write race. Name atomic variables or a lock as the real fix and you win the point. |
One classic fix is synchronized. You wrap the increment in a lock, so only one thread runs it at a time. It works, and it is correct. Yet locks come at a price.
For a single counter, a full lock often feels heavy. Imagine stopping an entire checkout line just to add one to a number. This is where atomic variables step in with a lighter touch.
Atomic variables are small wrapper classes. Each one holds a single value, such as an int, a long, a boolean, or an object reference. The real magic sits in their methods. Every update runs as one unbreakable step.
In plain words, no other thread ever sees a half-finished update. A thread reads either the old value or the new value, never something stuck in between. Best of all, this happens with no lock at all.
Think of a turnstile at a metro station. People pass through one at a time, and the counter clicks up by one on each pass. Even with a crowd pushing in, the count stays exact, because each click is a tiny self-contained action. An atomic variable works the same way. The increment is one clean click that cannot be split.
How is this different from a normal variable? A plain int lets threads read and write freely, so their steps overlap. An atomic int wraps the read-modify-write into a single guarded move. That one change removes the lost-update bug entirely.
Here are the members of the family you will meet most often.
All of them sit in the java.util.concurrent.atomic package. They have been part of Java since version 5, so you can use them almost everywhere.
Let us meet the three classes you will reach for the most. They share nearly the same set of methods, so learning one teaches you the rest.
AtomicInteger and AtomicLong are built for counters, IDs, and running totals. Both give you the same handy methods. Here is a quick taste.
AtomicInteger counter = new AtomicInteger(0); counter.incrementAndGet(); // adds 1, returns the new value (1) counter.getAndIncrement(); // returns the old value, then adds 1 counter.addAndGet(5); // adds 5, returns the new value counter.get(); // reads the current value counter.set(100); // sets a brand new value
Each of these calls is atomic on its own. So incrementAndGet() does the read, the add, and the write as one single step. The lost-update problem from before simply cannot happen here.
The names follow a tidy rule. A method starting with get returns the old value first. A method ending in Get returns the new value. Keep that in mind and you will never guess wrong.
One method pair is a quiet workhorse: getAndAdd and addAndGet. Say a service hands out ID blocks of 100. One call to getAndAdd(100) reserves the next block and tells you where it started, all in a single safe move.
The table below is a small cheat sheet of the methods you will use day to day.
| Method | What it does |
|---|---|
| get() | Returns the current value. |
| set(v) | Sets the value to v. |
| incrementAndGet() | Adds 1, then returns the updated value. |
| getAndIncrement() | Returns the old value, then adds 1. |
| addAndGet(d) | Adds d, then returns the updated value. |
| getAndSet(v) | Sets the value to v, then returns the old value. |
| updateAndGet(fn) | Applies a function, then returns the new value. |
| compareAndSet(expect, update) | Sets to update only if the current value equals expect. |
Sometimes you just need a safe on-off switch. AtomicBoolean is that switch. Its best use is a guard that must run once, no matter how many threads arrive together.
AtomicBoolean initialized = new AtomicBoolean(false);
public void initOnce() {
if (initialized.compareAndSet(false, true)) {
// this block runs exactly once, even under a crowd of threads
loadConfig();
}
}Many threads may call initOnce() together. Only the very first one flips the flag from false to true. That single winner runs loadConfig(), and everyone else fails the check and moves on.
Numbers are not the only things we share. Sometimes we share a whole object, such as a config holder, a cache snapshot, or a node in a data structure. AtomicReference lets you swap that object safely.
AtomicReference<String> currentUser = new AtomicReference<>("guest");
// swap to "admin" only if the value is still "guest"
boolean changed = currentUser.compareAndSet("guest", "admin");This trick is very handy with immutable objects. You build a fresh object, then swap the reference in one atomic move. There is no lock, and there is never a half-updated object on view.
| 💡 Interview Insight AtomicReference shines with immutable data. Instead of editing a shared object in place, create a new one and compareAndSet the reference. Interviewers love this pattern because it skips locks and keeps the old object safe to read. |
So far I kept saying “without a lock”. You may be wondering how that is even possible. The secret is a tiny operation called compare-and-swap, or CAS for short.
CAS takes three inputs.
Then it runs them as one atomic step. First it checks whether the current value matches the expected value. If they match, it writes the new value and reports success. If they differ, it changes nothing and reports failure.
On modern hardware this whole check-and-write is a single CPU instruction, called CMPXCHG on x86 chips. Nothing can slip in between the check and the write. That is the reason CAS needs no lock.

A single CAS can fail, and that is perfectly fine. Failure simply means another thread got there first. So we try again with the fresh value. This retry pattern is the beating heart of lock-free code.
Think of it like editing a shared online document. You grab the current version, make your change, and press save. If someone saved just before you, your save is rejected. You then pull the latest version and try once more. Nobody is ever locked out; you simply retry until your change sticks.
| 💡 Interview Insight CAS is optimistic. It assumes there is no conflict and only retries when one actually shows up. A lock is pessimistic — it blocks first, just in case. Being able to explain that difference is a strong signal in any concurrency interview. |
You never call CMPXCHG yourself. Java reaches it for you through low-level helpers, once called sun.misc.Unsafe and now wrapped by VarHandle in modern versions. Every atomic class uses this path under the hood. When you call incrementAndGet(), Java runs a CAS loop quietly in the background. You get clean code, and the retry stays invisible.
Let us make this real. We will count hits from many threads, first the easy way, and then the manual way so you can watch the CAS loop in action.
import java.util.concurrent.atomic.AtomicInteger;
public class HitCounter {
private final AtomicInteger hits = new AtomicInteger(0);
public void recordHit() {
hits.incrementAndGet(); // atomic and lock-free
}
public int totalHits() {
return hits.get();
}
}That is the whole class. No synchronized, no lock object, no wait or notify. Just one atomic field and a safe increment.
Talk is cheap, so let us hammer the counter from fifty threads. Each thread records a thousand hits. A correct counter must land on exactly fifty thousand.
import java.util.concurrent.*;
HitCounter counter = new HitCounter();
ExecutorService pool = Executors.newFixedThreadPool(50);
for (int t = 0; t < 50; t++) {
pool.submit(() -> {
for (int i = 0; i < 1000; i++) {
counter.recordHit();
}
});
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.MINUTES);
System.out.println(counter.totalHits()); // always prints 50000Run it as many times as you like. The answer stays fifty thousand, every single time. Swap the AtomicInteger for a plain int and the number drops below fifty thousand on most runs. That missing count is the lost update, caught red-handed.
Now let us peek at what incrementAndGet() roughly does inside. Writing it by hand makes the retry loop crystal clear.
public int incrementManually(AtomicInteger counter) {
int oldValue;
int newValue;
do {
oldValue = counter.get(); // read the latest value
newValue = oldValue + 1; // compute the next value
} while (!counter.compareAndSet(oldValue, newValue));
// keep looping until the swap finally succeeds
return newValue;
}Read the loop slowly. First we read the current value. Next we compute the value we want. Then we ask CAS to swap, but only if nothing changed meanwhile. If another thread slipped in, CAS returns false and we go around again. Sooner or later our swap wins and we leave the loop.
You will rarely write this by hand. Still, seeing it once removes all the mystery around the phrase lock-free. The library hides this exact loop inside every atomic method.
| 💡 Interview Insight Be ready to write this CAS loop on a whiteboard. The classic follow-up is, “What if CAS keeps failing again and again?” Under extreme contention a thread can retry many times and burn CPU. That weak spot is the perfect lead-in to LongAdder. |
People often mix these three tools up. Each one solves a slightly different problem, so a quick comparison helps a lot.
| Tool | Visibility? | Atomic update? | Blocks threads? | Best for |
|---|---|---|---|---|
| volatile | Yes | No | No | Simple flags with one writer. |
| Atomic classes | Yes | Yes, for one value | No | Counters, IDs, reference swaps. |
| synchronized / Lock | Yes | Yes, for any block | Yes | Multi-step or multi-field updates. |
Read the table from left to right and the choice becomes clear. Use volatile for a flag. Pick an atomic class for a single shared value. Reach for a lock when you must update several things together as one unit.
There is no single winner, and that nuance matters in interviews. When threads rarely clash, atomics usually win, because a successful CAS is cheaper than taking a lock. When threads clash a lot, CAS keeps failing and retrying, so a lock can sometimes pull ahead.
So the honest rule is: measure, do not guess. Start with an atomic for a single value. If a profiler shows that one hot counter is choking under contention, move to LongAdder, which we meet next.
AtomicLong is excellent, but it has one weak spot under very heavy load. When hundreds of threads hit the same atomic value, they all fight over one memory cell. Most of their CAS attempts fail and retry, so throughput drops.
LongAdder solves this with a smart trick. It spreads the work across several internal cells, so threads rarely collide. You call sum() when you want the total. Pick LongAdder for hot, write-heavy counters like request metrics. Stick with AtomicLong when you need the exact value at every instant, or when contention stays low.
A close cousin, LongAccumulator, follows the same idea but lets you plug in your own combine rule, such as max or min across threads.
Theory is nice, but where do these classes actually show up? Here are common spots from real codebases.
Notice the common thread. Each case is a single value that many threads touch. That is the sweet spot for atomics, and it is where they beat a heavy lock.
Each atomic method is atomic by itself. But two separate calls are not atomic together. A get() followed by a set() leaves a tiny gap where another thread can act. When you need both steps as one unit, use compareAndSet() or updateAndGet() with a function.
// risky: two steps with a gap in between int v = counter.get(); counter.set(v * 2); // another thread may change counter right here // safe: one atomic step counter.updateAndGet(x -> x * 2);
CAS checks the value, not the history. Suppose a value goes from A to B and back to A. Your CAS still sees A and succeeds, even though things moved around in between. Most counters do not care about this at all. A few lock-free structures do, though, and for them AtomicStampedReference adds a version stamp to catch the change.
Atomic variables fit a single value updated by many threads. They are not a full replacement for locks. When you must change several related fields together as one unit, a lock or a concurrent collection is the cleaner choice.
| 💡 Interview Insight If an interviewer asks when NOT to use atomics, say this: when you must update several related variables together. One atomic per field does not make the group atomic. That job belongs to a lock, or to a redesign around a single immutable object swapped through AtomicReference. |
Reach for incrementAndGet or updateAndGet before you hand-roll a CAS loop. The library versions are tested, tuned, and clear to read. Save the manual loop for the rare case where you truly need custom logic inside the retry.
A: Atomic variables in Java are wrapper classes in the java.util.concurrent.atomic package that let many threads update one shared value safely, without any lock. Each update runs as a single, unbreakable step, so no thread ever sees a half-finished change.
A: Because count++ is really three steps: read, add, then write. volatile makes each read and write visible across threads, but it does not join the three steps into one action. Two threads can still overlap and lose an update. An atomic variable or a lock fixes this.
A: CAS is a single CPU instruction that updates a value only if it still matches an expected old value. If it matches, CAS writes the new value and reports success. If not, it changes nothing and reports failure, so the code retries. This is how atomic classes stay thread-safe without locks.
A: Use LongAdder when many threads write to the same counter very often, such as request metrics. It spreads writes across several cells, so threads rarely collide. Stick with AtomicLong when contention is low or you need the exact value at every instant.
A: No. Atomic variables fit a single shared value updated by many threads. When you must update several related fields together as one unit, you still need a lock or a concurrent collection. One atomic per field does not make the whole group atomic.
A: All of them live in java.util.concurrent.atomic, including AtomicInteger, AtomicLong, AtomicBoolean, AtomicReference, and the array versions. They have been available since Java 5.
Atomic variables in Java give you fast, lock-free updates for shared single values. They close the gap that volatile leaves open, the gap between seeing a value and safely changing it.
Here is the short version to carry with you.
Keep these classes in your toolkit for counters, flags, IDs, and reference swaps. Reach for a lock only when a single value is simply not enough.