Java Thread Safety: Race Conditions, volatile, Atomic Classes and synchronized (OCP 21)
Thread safety for the OCP 21 exam: why ++ loses updates, what volatile does and doesn't do, AtomicInteger and the other atomic classes, synchronized blocks and methods, which object is the lock, reentrancy and the BLOCKED state.
kvi5hnuCode Sprout team member10 min readOn this page
Threads share the heap. When two threads read and change the same field at the same time, the result depends on how the scheduler interleaves them. Code is thread-safe when it behaves correctly however its threads are interleaved. This article covers the tools for that which the exam tests most: volatile, the atomic classes and synchronized. Article 81 adds the Lock framework and other coordination tools.
The problem: ++ is not one step
Picture a box office where several clerks sell tickets and each sale runs sold++ on a shared field:
class BoxOffice {
private int sold;
void sell() { sold++; } // NOT thread-safe
}
sold++ looks like one operation, but it's three: read the field, add one, write it back. If clerk A reads 7 and clerk B reads 7 before A has written, both write 8. Two tickets were sold, but the counter went up by one. That's a lost update, and the situation that causes it is a race condition: the result depends on the timing of threads.

Run four threads that each call sell() 250,000 times and you'll almost always get less than 1,000,000. The output varies from run to run, which is what makes these bugs so hard to find. If ten tasks each run System.out.print(++sold + " "), the numbers can come out in any order, and some can repeat while others are missing.
An operation is atomic if no other thread can see it half done or interleave with it. For the long and double types, even a plain read or write isn't guaranteed to be atomic unless the field is volatile.
volatile: visibility, not atomicity
Without help, a thread may keep using a value it has already read (for example, one cached in a register) and never see another thread's write. The volatile modifier on a field guarantees that:
- every read sees the most recent write by any thread, and
- writes before a volatile write are visible to a thread that later reads that volatile field.
That makes it right for a simple flag that one thread sets and others read:
private static volatile boolean doorsOpen = true;
// usher thread
while (doorsOpen) { /* keep working */ }
// main thread, later
doorsOpen = false; // the usher will see this and stop
volatile does not make sold++ safe. The read and the write are each visible, but another thread can still slip in between them. The complete example below shows a volatile int losing updates just like a plain one.
Rules for where volatile can go:
- It applies only to fields, static or instance.
- It can't be used on local variables, methods or classes.
- It can't be combined with
final. That's a compile error, because a final field never changes, so there's nothing to make visible.
Atomic classes
The package java.util.concurrent.atomic has classes whose methods read and update a value as one indivisible step:
| Class | Holds |
|---|---|
AtomicBoolean | a boolean |
AtomicInteger | an int |
AtomicLong | a long |
AtomicReference<V> | an object reference |
There are also array versions (AtomicIntegerArray, and others) and LongAdder, which is faster than AtomicLong for counters that many threads update.
Common methods. Each row starts again from an AtomicInteger holding 10:
| Method | Works like | Returns | Value after |
|---|---|---|---|
get() | reading the value | 10 | 10 |
set(20) | value = 20 | (void) | 20 |
getAndSet(20) | sets, returns the old value | 10 | 20 |
incrementAndGet() | ++value | 11 | 11 |
getAndIncrement() | value++ | 10 | 11 |
decrementAndGet() | --value | 9 | 9 |
getAndDecrement() | value-- | 10 | 9 |
addAndGet(5) / getAndAdd(5) | value += 5 | 15 / 10 | 15 |
compareAndSet(10, 40) | sets to 40 only if the value is still 10 | true | 40 |
updateAndGet(x -> x * 2) | applies a function atomically | 20 | 20 |
accumulateAndGet(7, Math::max) | combines the value with 7 | 10 | 10 |
The name tells you what's returned: getAndX returns the value before the change, and xAndGet returns the value after it. That's the same idea as postfix and prefix ++.
private final AtomicInteger sold = new AtomicInteger();
void sell() { sold.incrementAndGet(); } // thread-safe, never loses a sale
Things to remember about atomic classes:
- You can't use operators on them.
sold++on anAtomicIntegerdoesn't compile. AtomicBooleanhas no increment methods.- They don't override
equals(), sonew AtomicInteger(5).equals(new AtomicInteger(5))isfalse.toString()does print the value. - Atomic classes protect one variable. Updating two atomic fields one after the other isn't atomic as a pair. Another thread can see the first change without the second.
synchronized: one thread at a time
To make a group of statements behave as a unit, use a monitor, also called a lock. Every Java object has one built-in lock. A synchronized block names the object whose lock it uses:
private final Object counterLock = new Object();
private int sold;
void sellAndAnnounce() {
synchronized (counterLock) {
sold++;
System.out.println("ticket " + sold); // increment and print stay together
}
}
How it works:
- A thread reaching the block tries to acquire the object's lock.
- If another thread holds it, this thread goes into the
BLOCKEDstate until the lock is free. - When it gets the lock, it runs the block. Other threads wanting the same lock wait.
- Leaving the block, normally or by an exception, releases the lock automatically.
synchronized also gives visibility: everything one thread did inside the block is visible to the next thread that acquires the same lock.
A common exam trap is synchronizing the wrong code:
for (int i = 0; i < 10; i++) {
synchronized (office) {
service.submit(() -> office.sell()); // only the SUBMIT is synchronized
}
}
This loop submits the tasks one at a time, but the tasks themselves still run sell() at the same time. The lock must be taken inside the code that the worker threads run.
What you can lock on
- Any object reference. A primitive like
synchronized (count)with anintis a compile error. - Not
null. Locking onnullthrows aNullPointerExceptionat run time. - Not shared or value-based objects. Locking on an
Integer(value-based) makes javac warn[identity] attempt to synchronize on an instance of a value-based class. Locking on aStringliteral compiles silently, but literals are interned and shared across the whole JVM, so unrelated code may lock the same object. Use a privatefinal Object.
synchronized methods
The synchronized modifier on a method synchronizes the whole method body:
| You write | Same as | Lock used |
|---|---|---|
synchronized void sell() { ... } | void sell() { synchronized (this) { ... } } | the instance (this) |
static synchronized void audit() { ... } | static void audit() { synchronized (BoxOffice.class) { ... } } | the Class object |
So:
- two synchronized instance methods on the same object exclude each other, but on different objects they don't;
- a static synchronized method uses the class lock, so it doesn't exclude an instance synchronized method, and vice versa;
synchronizedis a modifier only for methods and blocks. It's a compile error on fields, constructors, abstract methods and interface methods.
Locks are reentrant
A thread that already holds a lock can enter other code synchronized on that same lock. For example, a synchronized method can call another synchronized method on this, or call itself recursively, without blocking itself. The lock is released when the outermost block exits.
What's current
- Java 21 virtual threads: in Java 21, a virtual thread that blocks inside a
synchronizedblock stays pinned to its carrier platform thread, which reduces scalability. Java 21 advice was to useReentrantLock(article 81) around blocking code in virtual threads. Java 24 (JEP 491) removed most of this pinning, sosynchronizedis fine with virtual threads on current JDKs. The exam is based on Java 21, but it doesn't test pinning. LongAdderandLongAccumulator(Java 8) beatAtomicLongfor counters under heavy contention.- Lambda-based atomic methods (
updateAndGet,accumulateAndGet) have existed since Java 8. - The exam doesn't test the
VarHandleAPI (Java 9), which offers lower-level atomic operations.
Exam traps from this article
A complete example
A box-office counter is updated a million times by four threads in several ways. The program shows a plain int and a volatile int losing updates, then AtomicInteger, a synchronized block and LongAdder getting every update, while locking on a new object each time fails. It walks through the atomic methods, stops a thread with a volatile flag, prints ticket numbers in order using synchronized, checks which lock synchronized methods hold with Thread.holdsLock, shows reentrancy, and catches a thread in the BLOCKED state.
The racy runs are repeated up to ten times and print only whether any run lost an update, because the exact lost count changes every time.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class Solution {
// ---- shared state used by the demos ----
private int plainSold; // no protection at all
private volatile int volatileSold; // visible to all threads, but ++ is still two steps
private final AtomicInteger atomicSold = new AtomicInteger();
private int lockedSold; // protected by synchronized (gate)
private final Object gate = new Object(); // final: never swapped while threads use it
private static volatile boolean doorsOpen = true; // stop flag read by another thread
/** Runs the same action on 4 threads, 250_000 times each, and waits for all of them. */
static void hammer(Runnable action) {
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
for (int t = 0; t < 4; t++)
pool.execute(() -> { for (int i = 0; i < 250_000; i++) action.run(); });
}
}
/** Repeats a racy experiment a few times; true if any run lost updates. */
static boolean losesUpdates(java.util.function.IntSupplier experiment) {
for (int run = 0; run < 10; run++)
if (experiment.getAsInt() < 1_000_000) return true;
return false;
}
// ---- synchronized methods and the lock they use ----
synchronized boolean instanceLockHeld() { // same as synchronized (this) { ... }
return Thread.holdsLock(this) && !Thread.holdsLock(Solution.class);
}
static synchronized boolean staticLockHeld() { // same as synchronized (Solution.class) { ... }
return Thread.holdsLock(Solution.class);
}
synchronized int reenter(int depth) { // a thread may re-acquire a lock it holds
return depth == 0 ? 0 : 1 + reenter(depth - 1);
}
private int nextTicket;
private void sellAndAnnounce(List<Integer> announced) {
synchronized (this) { // increment and report as one unit
announced.add(++nextTicket);
}
}
public static void main(String[] args) throws Exception {
System.out.println("== 1. ++ on a shared int is not atomic");
System.out.println(" plain int lost updates in at least one run: " + losesUpdates(() -> {
Solution s = new Solution();
hammer(() -> s.plainSold++);
return s.plainSold;
}));
System.out.println(" volatile int lost updates in at least one run: " + losesUpdates(() -> {
Solution s = new Solution();
hammer(() -> s.volatileSold++);
return s.volatileSold;
}));
System.out.println("\n== 2. Fixes that never lose an update");
Solution atomic = new Solution();
hammer(atomic.atomicSold::incrementAndGet);
System.out.println(" AtomicInteger: " + atomic.atomicSold.get());
Solution locked = new Solution();
hammer(() -> { synchronized (locked.gate) { locked.lockedSold++; } });
System.out.println(" synchronized (gate): " + locked.lockedSold);
LongAdder adder = new LongAdder();
hammer(adder::increment);
System.out.println(" LongAdder: " + adder.sum());
System.out.println(" synchronized on a new Object each time lost updates: " + losesUpdates(() -> {
Solution s = new Solution();
hammer(() -> { synchronized (new Object()) { s.lockedSold++; } }); // every thread has its own lock!
return s.lockedSold;
}));
System.out.println("\n== 3. Atomic methods (start at 10)");
AtomicInteger seats = new AtomicInteger(10);
System.out.println(" getAndIncrement(): " + seats.getAndIncrement() + " -> now " + seats.get());
System.out.println(" incrementAndGet(): " + seats.incrementAndGet());
System.out.println(" getAndDecrement(): " + seats.getAndDecrement() + " -> now " + seats.get());
System.out.println(" decrementAndGet(): " + seats.decrementAndGet());
System.out.println(" getAndSet(50): " + seats.getAndSet(50) + " -> now " + seats.get());
System.out.println(" addAndGet(-5): " + seats.addAndGet(-5));
System.out.println(" compareAndSet(45, 40): " + seats.compareAndSet(45, 40)
+ ", compareAndSet(45, 30): " + seats.compareAndSet(45, 30) + " -> now " + seats.get());
System.out.println(" updateAndGet(x -> x * 2): " + seats.updateAndGet(x -> x * 2));
System.out.println(" accumulateAndGet(7, Math::max): " + seats.accumulateAndGet(7, Math::max));
AtomicBoolean soldOut = new AtomicBoolean();
System.out.println(" AtomicBoolean getAndSet(true): " + soldOut.getAndSet(true) + " -> now " + soldOut.get());
AtomicLong revenue = new AtomicLong(1_000L);
System.out.println(" AtomicLong addAndGet(2_500): " + revenue.addAndGet(2_500));
AtomicReference<String> headliner = new AtomicReference<>("The Owls");
headliner.updateAndGet(name -> name + " & Friends");
System.out.println(" AtomicReference: " + headliner.get());
System.out.println("\n== 4. volatile makes a stop flag visible");
AtomicLong loops = new AtomicLong();
Thread usher = Thread.ofPlatform().start(() -> {
while (doorsOpen) loops.incrementAndGet(); // re-reads the volatile field every time
});
Thread.sleep(100);
doorsOpen = false; // this write is seen by the usher thread
usher.join(2_000);
System.out.println(" usher stopped after the flag changed: " + !usher.isAlive()
+ " (looped: " + (loops.get() > 0) + ")");
System.out.println("\n== 5. synchronized keeps increment-and-report together");
List<Integer> announced = Collections.synchronizedList(new ArrayList<>());
Solution box = new Solution();
try (ExecutorService pool = Executors.newFixedThreadPool(10)) {
for (int i = 0; i < 10; i++) pool.submit(() -> box.sellAndAnnounce(announced));
}
System.out.println(" tickets announced in order: " + announced);
System.out.println("\n== 6. Which lock does a synchronized method use?");
System.out.println(" instance method holds this (not the class): " + box.instanceLockHeld());
System.out.println(" static method holds Solution.class: " + staticLockHeld());
System.out.println(" outside any synchronized code: " + Thread.holdsLock(box));
System.out.println(" synchronized is reentrant, nested 5 deep: " + box.reenter(5));
System.out.println("\n== 7. A thread waiting for a monitor is BLOCKED");
CountDownLatch inside = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Thread holder = Thread.ofPlatform().start(() -> {
synchronized (box) {
inside.countDown();
try { release.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
});
inside.await();
Thread waiter = Thread.ofPlatform().start(() -> { synchronized (box) { } });
while (waiter.getState() != Thread.State.BLOCKED) Thread.onSpinWait();
System.out.println(" holder: " + holder.getState() + ", waiter: " + waiter.getState());
release.countDown();
holder.join();
waiter.join();
System.out.println(" after release, waiter: " + waiter.getState());
}
}
Output:
== 1. ++ on a shared int is not atomic
plain int lost updates in at least one run: true
volatile int lost updates in at least one run: true
== 2. Fixes that never lose an update
AtomicInteger: 1000000
synchronized (gate): 1000000
LongAdder: 1000000
synchronized on a new Object each time lost updates: true
== 3. Atomic methods (start at 10)
getAndIncrement(): 10 -> now 11
incrementAndGet(): 12
getAndDecrement(): 12 -> now 11
decrementAndGet(): 10
getAndSet(50): 10 -> now 50
addAndGet(-5): 45
compareAndSet(45, 40): true, compareAndSet(45, 30): false -> now 40
updateAndGet(x -> x * 2): 80
accumulateAndGet(7, Math::max): 80
AtomicBoolean getAndSet(true): false -> now true
AtomicLong addAndGet(2_500): 3500
AtomicReference: The Owls & Friends
== 4. volatile makes a stop flag visible
usher stopped after the flag changed: true (looped: true)
== 5. synchronized keeps increment-and-report together
tickets announced in order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
== 6. Which lock does a synchronized method use?
instance method holds this (not the class): true
static method holds Solution.class: true
outside any synchronized code: false
synchronized is reentrant, nested 5 deep: 5
== 7. A thread waiting for a monitor is BLOCKED
holder: WAITING, waiter: BLOCKED
after release, waiter: TERMINATED
Points to notice:
- The
volatile intlost updates just like the plainint. Visibility doesn't make++atomic. synchronized (new Object())lost updates too, because each thread locked a different object.compareAndSet(45, 40)succeeded because the value was 45. The second call failed because the value was by then 40, not 45.- Ticket numbers came out in order because the increment and the
addhappened inside one synchronized block. Thread.holdsLockconfirmed that an instance synchronized method holdsthisand a static one holdsSolution.class.- The waiting thread was
BLOCKED, while the holder, which was waiting on a latch inside the block, wasWAITING.
Common questions
Should I make every method synchronized?
No. Locking costs time and limits parallelism, and holding a lock too long invites deadlocks (article 82). Synchronize only access to shared mutable state, and keep the blocks short. Immutable objects and thread-confined data need no locking at all.
Atomic class or synchronized?
For a single counter or flag, an atomic class is simpler and usually faster. For updates that must keep several fields consistent, or for check-then-act logic across statements, use synchronized or a Lock.
Is volatile ever enough?
Yes: when one thread writes and the others only read, and the new value doesn't depend on the old one. A stop flag or a "latest configuration" reference are classic examples.
Summary
- A race condition occurs when threads interleave in a read-modify-write such as
++, and updates are lost. volatilegives visibility of a field's latest value but not atomicity.- Atomic classes (
AtomicInteger,AtomicLong,AtomicBooleanandAtomicReference) update one variable atomically.getAndXreturns the old value, andxAndGetthe new one. synchronizedblocks and methods let one thread at a time hold an object's lock. Instance methods lockthis, and static methods lock theClassobject.- Every thread must use the same lock object. Waiting threads are
BLOCKED, and the locks are reentrant.
Practice quiz
Test yourself with the thread safety quiz: 10 exam-style questions with explanations.
Previous: Java ExecutorService: Runnable, Callable, Future, invokeAll and Scheduling (OCP 21)
Next: Java Locks: ReentrantLock, tryLock, ReadWriteLock and CyclicBarrier (OCP 21)
Related reading
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
- Java ExecutorService: Runnable, Callable, Future, invokeAll and Scheduling (OCP 21)
- Java Threads: Platform and Virtual Threads, Thread States and Interrupting (OCP 21)
- Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.