Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Multithreading

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Multithreading

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.

The main thread writes running = false to main memory. Without volatile, the sync job thread may keep reading its own cached copy, which still says true. With volatile, every read goes to main memory, so the job sees false. mainrunning = false main memoryrunning: false sync jobreads the flag own copy: true? writevolatile: read here Without volatile, the job may keep using a stale copy.
volatile makes every read and write go through main memory, so every thread sees the latest value.

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

JobToolWhy
A stop flagvolatile booleanone thread writes, others only read; everyone sees the change
A shared countAtomicIntegermany threads change it; each change is one step
Several fields changed togethersynchronized or a lockatomics 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.

Keep going in Java · 69 of 79

Previous
Java Race Conditions and synchronized
Next post
Java ExecutorService and Thread Pools
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • main stops a job with a flag
  • volatile does not make views++ one step
  • Two threads count one total
  • Pick the tool for the job
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.