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 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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Multithreading

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.

sold is 41. Emma reads 41 into her copy. Before she writes, Chris also reads 41. Emma adds one and writes 42. Chris adds one to his 41 and also writes 42. Two sales happened but sold went up by one: one update is lost. sold 41 → 42 → 42 Emma 1 read 413 add: 424 write 42 Chris 2 read 415 add: 426 write 42 two sales, +1: an update is lost
Chris read before Emma wrote, so his write overwrites hers.

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

CodeResult
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.

Keep going in Java · 68 of 79

Previous
Java Thread Lifecycle: sleep, join and interrupt
Next post
Java volatile and Atomic Variables
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 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.

On this page

  • Two cashiers, one counter
  • One word: synchronized
  • Or lock just a block
  • A new lock each time protects nothing
  • Recap
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.