Java Race Conditions and synchronized
Two cashiers each sell a million tickets on one counter and the total comes out short, a different number every run, because sold++ is read, add, write. A synchronized method or a synchronized block on one shared lock gives exactly 2,000,000; a new Object() lock protects nothing.
What you will learn
- Explain why sold++ is three steps and how two threads lose an update
- Fix a race with a synchronized method
- Lock only part of a method with a synchronized block on a shared lock object
- Avoid the trap of locking on a new object each time
Before you start
- Java thread lifecycle: sleep, join and interrupt
When two threads work on the same data at the same time, some updates can quietly go missing. This lesson shows why, and how one word, synchronized, fixes it. Thread timing varies from run to run, which is exactly what makes this bug hard to spot.
Two cashiers, one counter
package org.studyeasy.s06l04;
class TicketCounter {
int sold = 0;
void sell() { sold++; } // read, add 1, write back: three steps
}
public class Ex01_LostUpdate {
public static void main(String[] args) throws InterruptedException {
TicketCounter counter = new TicketCounter(); // one object
Runnable cashier = () -> {
for (int i = 0; i < 1_000_000; i++) counter.sell();
};
Thread emma = new Thread(cashier);
Thread chris = new Thread(cashier);
emma.start(); chris.start();
emma.join(); chris.join(); // wait for both before reading
System.out.println("Expected: 2000000");
System.out.println("Sold: " + counter.sold);
}
}
Expected: 2000000
Sold: 1090166
That's one run; your Sold will be different, and different every time. sold++ looks like one action, but it's three steps: read the value into the thread's own copy, add one to the copy, write it back.
Chris read 41 before Emma wrote, so he doesn't know the value changed. Both write 42; one sale vanished. Over two million calls this happens again and again. When the result depends on the timing of threads, it's a race condition. (Delete the join line and main reads Sold while the cashiers are still selling, so it's far too low.)
One word: synchronized
class SafeTicketCounter {
int sold = 0;
synchronized void sell() { // take this object's lock first
sold++; // one thread in here at a time
}
}
Expected: 2000000
Sold: 2000000
The rest of the program is the same. synchronized means a thread must take this object's lock before running sell. Think of sell as a room with one door and one key. Emma takes the key, does read, add, write, and comes out with sold at 42. Chris reaches the door while Emma has the key, so he waits; then he goes in and reads 42. No one cuts in between the three steps, and the total is exact every run.
Or lock just a block
class BlockTicketCounter {
private final Object lock = new Object(); // any object can be a lock
int sold = 0;
void sell() {
synchronized (lock) { // lock only the code inside the block
sold++;
}
}
}
Expected: 2000000
Sold: 2000000
Any object can be a lock; this lock field exists only to be locked. synchronized (lock) { ... } guards just the code inside the block, which is handy when only part of a method touches shared data. It's private final, so every thread uses the same lock object.
A new lock each time protects nothing
synchronized (new Object()) { sold++; } // a new lock on every call
This compiles, and Sold comes out short again. A new object is made on every call, so every thread gets its own key: Emma takes hers and goes in, Chris takes a different one and goes in too. It's the same race as before. A lock only protects threads that share it.
Recap
| Code | Result |
|---|---|
void sell() { sold++; } | lost updates; short, different every run |
synchronized void sell() | exact: one thread at a time on this object |
synchronized (lock) { sold++; } | exact: one shared lock object |
synchronized (new Object()) | short: nobody shares the lock |
For a simple counter there's a lighter tool than a lock: see volatile and atomic variables.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Concurrency: Processes, Threads and the Main Thread in Java
Every Java program runs as a process and starts on one thread, main. One cook takes 15 seconds for soup and salad; a second thread, Jack, brings it to 10. Then two threads add to one counter a million times each and count less than 2,000,000.
Creating Threads in Java: Thread, Runnable and Lambdas
Three ways to give a thread its job: an InvoiceMailer that extends Thread, a ReportTask record that implements Runnable, and a lambda. worker.run() prints main, worker.start() prints backup-worker, and two cashiers, Jack and Liam, scan items in an order that changes every run.
Java Thread Lifecycle: sleep, join and interrupt
A courier thread walks from NEW through RUNNABLE and TIMED_WAITING to TERMINATED while main WAITs at join. An interrupt wakes a sleeping download on report-3: one version retries it, the other returns. And a daemon status thread dies when the last user thread ends.
Java volatile and Atomic Variables
main sets a volatile running flag to false and the sync job finishes batch 3, sees the change and exits. But volatile can't make views++ one step, so two threads still lose updates. An AtomicInteger with incrementAndGet counts web and mobile visits to exactly 200,000.
