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.
What you will learn
- Stop a worker thread with a volatile boolean flag
- Explain why a thread may not see another thread's change without volatile
- Explain why volatile doesn't make views++ safe
- Count from several threads exactly with AtomicInteger.incrementAndGet
Before you start
- Java race conditions and synchronized
Two ideas in this lesson: how one thread sees a flag that another thread changes, and how two threads can count together without losing an update, and without synchronized. As always with threads, exact timings vary from run to run.
main stops a job with a flag
package org.studyeasy.s06l05;
public class Ex01_StopFlag {
// volatile: every thread reads the latest value from main memory
private static volatile boolean running = true;
static void pause(int ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { }
}
public static void main(String[] args) throws InterruptedException {
Runnable syncJob = () -> {
int batch = 0;
while (running) { // checks the flag each pass
batch++;
pause(100); // one batch takes 100 ms
System.out.println("Sync job: batch " + batch + " done");
}
System.out.println("Sync job: stop seen, exiting");
};
Thread job = new Thread(syncJob, "sync-job");
job.start();
pause(250); // main does its own work
System.out.println("Main: stopping the sync job");
running = false; // the job sees this change
job.join();
System.out.println("Main: sync job finished");
}
}
Sync job: batch 1 done
Sync job: batch 2 done
Main: stopping the sync job
Sync job: batch 3 done
Sync job: stop seen, exiting
Main: sync job finished
At 250 ms, main sets running to false while batch 3 is still going. The job isn't interrupted; it finishes that batch, then checks the flag at the top of the loop, sees false and exits.
Why volatile? To work faster, a thread can keep its own copy of a variable. Without volatile, main's change reaches main memory, but Java doesn't promise the job ever re-reads it; it could loop on its stale true. A volatile variable is read from and written to main memory, so all threads see the same, latest value.
volatile does not make views++ one step
Volatile isn't a fix for everything. Picture two threads, web and mobile, both running views++ on a volatile int. As in race conditions, views++ is read, add, write. Both can read 42 at the same moment, both compute 43, both write 43: one update lost. Volatile makes the value visible, but it doesn't glue the three steps together.
Two threads count one total
package org.studyeasy.s06l05;
import java.util.concurrent.atomic.AtomicInteger;
public class Ex02_AtomicCounter {
public static void main(String[] args) throws InterruptedException {
AtomicInteger views = new AtomicInteger(); // starts at 0
Runnable visitor = () -> {
for (int i = 0; i < 100_000; i++) {
views.incrementAndGet(); // read, add 1, write: one step
}
};
Thread web = new Thread(visitor, "web");
Thread mobile = new Thread(visitor, "mobile");
web.start();
mobile.start();
web.join();
mobile.join();
System.out.println("Expected: 200000");
System.out.println("Actual: " + views.get());
}
}
Expected: 200000
Actual: 200000
Both threads share one AtomicInteger. incrementAndGet() seals the read, the add and the write into one indivisible (atomic) step. If web is in the middle of it, taking views from 42 to 43, mobile can't get in; it goes next and makes 44. Nothing slips in between, so the total is exact. Swap it for a volatile int with views++ and the total falls short again. get() reads the current value.
Pick the tool for the job
| Job | Tool | Why |
|---|---|---|
| A stop flag | volatile boolean | one thread writes, others only read; everyone sees the change |
| A shared count | AtomicInteger | many threads change it; each change is one step |
| Several fields changed together | synchronized or a lock | atomics cover one variable at a time |
An AI can write this code for you, but knowing these ideas helps you spot the bug when two threads share data. Next: letting Java manage the threads for you with ExecutorService and thread pools.
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 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.
