Java Race Conditions

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 191 of 306

A Java race condition happens when two or more threads use the same data at the same time and the result depends on which thread runs first. The program works most of the time, then suddenly gives a wrong answer, because the thread scheduler decided on a different order.

Race conditions are the most common bug in multithreaded code. This lesson shows how they appear, why simple operations like count++ are not safe, and how to fix them with synchronized, atomic variables and locks.


What Is a Race Condition in Java?

A race condition needs three things: shared data, at least two threads, and at least one thread that changes the data. If any one of these is missing, there is no race.

The classic example is a counter that two threads increase at the same time.

public class LostUpdate {
    static int likeCount = 0; // shared and unprotected

    public static void main(String[] args) throws InterruptedException {
        Runnable clickLike = () -> {
            for (int i = 0; i < 100_000; i++) {
                likeCount++; // read, add 1, write: three separate steps
            }
        };

        Thread userA = new Thread(clickLike);
        Thread userB = new Thread(clickLike);
        userA.start();
        userB.start();
        userA.join();
        userB.join();

        System.out.println("expected: 200000");
        System.out.println("actual  : " + likeCount);
    }
}

Output (different on every run):

expected: 200000
actual  : 137512

How it works:

  • Each thread adds 1 to likeCount one hundred thousand times, so the answer should be 200,000.
  • The real result is smaller, and it changes every time you run the program.
  • Some increments are lost: both threads read the same old value, both add 1, and both write back the same new value. Two clicks are counted as one.

Note: A race condition may not appear on your machine during testing and then appear on a busy server. "It worked when I ran it" proves nothing for multithreaded code.


Why count++ Is Not Atomic

likeCount++ looks like one operation, but the JVM runs it as three steps: read the value, add one, and write the result back. Another thread can run between any of these steps.

TimeThread AThread BlikeCount in memory
1reads 4141
2reads 4141
3adds 1 → 4241
4adds 1 → 4241
5writes 4242
6writes 4242 (one update lost)

The same thing happens with any read-modify-write sequence. The next example makes the gap between the read and the write longer with Thread.sleep(), so the race happens on every run.

public class ReadModifyWrite {
    static int balance = 1000; // shared bank balance

    static void withdraw(String customer, int amount) {
        int current = balance;                           // 1. read
        System.out.println(customer + " read balance " + current);
        pause(100);                                      // the other thread runs here
        balance = current - amount;                      // 2. modify + 3. write
        System.out.println(customer + " wrote balance " + balance);
    }

    static void pause(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread alice = new Thread(() -> withdraw("alice", 300));
        Thread bob = new Thread(() -> withdraw("bob", 500));
        alice.start();
        bob.start();
        alice.join();
        bob.join();
        System.out.println("final balance: " + balance + " (expected 200)");
    }
}

Output (the order of the lines can change):

alice read balance 1000
bob read balance 1000
alice wrote balance 700
bob wrote balance 500
final balance: 500 (expected 200)

How it works:

  • Both threads read 1000 before either of them writes.
  • Alice writes 1000 - 300 = 700, then Bob overwrites it with 1000 - 500 = 500.
  • Rs. 800 was withdrawn but the balance only dropped by Rs. 500. Alice's withdrawal was lost.

Check-Then-Act Race Condition in Java

The second common type of race is check-then-act: a thread checks a condition and then acts on it, but another thread changes the data between the check and the action.

public class TicketRace {
    static int seatsLeft = 1; // only one seat in the show

    static void book(String customer) {
        if (seatsLeft > 0) {                 // check
            pause(50);                       // e.g. payment processing
            seatsLeft--;                     // act
            System.out.println(customer + " booked a seat");
        } else {
            System.out.println(customer + ": sold out");
        }
    }

    static void pause(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread[] customers = {
            new Thread(() -> book("Asha")),
            new Thread(() -> book("Ravi")),
            new Thread(() -> book("Meena"))
        };
        for (Thread c : customers) c.start();
        for (Thread c : customers) c.join();
        System.out.println("seats left: " + seatsLeft);
    }
}

Output (order can change):

Asha booked a seat
Ravi booked a seat
Meena booked a seat
seats left: -2

How it works:

  • All three threads run the check seatsLeft > 0 while the value is still 1, so all three pass.
  • Each one then decreases seatsLeft, and the theatre sells three tickets for one seat.
  • The check was correct when it ran, but it was stale by the time the thread acted on it.

Other check-then-act examples are "create the file if it does not exist", "put into the map if the key is missing" and lazy initialisation (if (instance == null) instance = new ...).


How to Fix a Race Condition with synchronized

The fix is to make the check and the action (or the read and the write) happen as one indivisible step. The simplest tool is synchronized, covered in detail in Java Synchronization.

public class TicketFixed {
    static int seatsLeft = 1;

    // Only one thread at a time can run this method
    static synchronized void book(String customer) {
        if (seatsLeft > 0) {
            pause(50);
            seatsLeft--;
            System.out.println(customer + " booked a seat");
        } else {
            System.out.println(customer + ": sold out");
        }
    }

    static void pause(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread[] customers = {
            new Thread(() -> book("Asha")),
            new Thread(() -> book("Ravi")),
            new Thread(() -> book("Meena"))
        };
        for (Thread c : customers) c.start();
        for (Thread c : customers) c.join();
        System.out.println("seats left: " + seatsLeft);
    }
}

Output (which customer wins can change):

Ravi booked a seat
Asha: sold out
Meena: sold out
seats left: 0

How it works:

  • static synchronized locks on the TicketFixed.class object, so only one thread can be inside book() at a time.
  • The thread that gets the lock checks and decreases seatsLeft before anyone else can look at it.
  • The other two threads wait for the lock, then see seatsLeft == 0 and report "sold out".

Note: Every access to the shared variable must use the same lock. If one method is synchronized but another method changes seatsLeft without the lock, the race comes back.


Fixing Race Conditions with AtomicInteger

For a single number, AtomicInteger is faster than a lock. Its methods do the read, change and write in one hardware-level step.

MethodWhat it does atomically
incrementAndGet()++value, returns the new value
getAndIncrement()value++, returns the old value
addAndGet(delta)value += delta
compareAndSet(expected, newValue)sets newValue only if the current value is still expected
updateAndGet(function)applies a function and stores the result

The example below fixes the lost-update counter and the ticket booking with compareAndSet().

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicFix {
    static final AtomicInteger likeCount = new AtomicInteger();
    static final AtomicInteger seatsLeft = new AtomicInteger(2);
    static final AtomicInteger booked = new AtomicInteger();
    static final AtomicInteger soldOut = new AtomicInteger();

    // Book one seat without a lock, using compare-and-set
    static boolean tryBook() {
        while (true) {
            int current = seatsLeft.get();
            if (current == 0) {
                return false;                                  // nothing left
            }
            if (seatsLeft.compareAndSet(current, current - 1)) {
                return true;                                   // we took a seat
            }
            // another thread changed seatsLeft in between: read again and retry
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable clickLike = () -> {
            for (int i = 0; i < 100_000; i++) {
                likeCount.incrementAndGet();
            }
        };
        Thread userA = new Thread(clickLike);
        Thread userB = new Thread(clickLike);
        userA.start(); userB.start();
        userA.join(); userB.join();
        System.out.println("likes: " + likeCount.get());

        Thread[] customers = new Thread[5];
        for (int i = 0; i < customers.length; i++) {
            customers[i] = new Thread(() -> {
                if (tryBook()) booked.incrementAndGet(); else soldOut.incrementAndGet();
            });
            customers[i].start();
        }
        for (Thread c : customers) c.join();
        System.out.println("booked: " + booked.get() + ", sold out: " + soldOut.get()
                + ", seats left: " + seatsLeft.get());
    }
}

Output:

likes: 200000
booked: 2, sold out: 3, seats left: 0

How it works:

  • incrementAndGet() never loses an update, so the counter always reaches 200,000.
  • compareAndSet(current, current - 1) only succeeds if no other thread changed seatsLeft since this thread read it. If it fails, the loop reads the new value and tries again.
  • Five customers compete for two seats, and exactly two succeed on every run.

Fixing a Race Condition with ReentrantLock

ReentrantLock from java.util.concurrent.locks does the same job as synchronized, with extra features such as timeouts. Always unlock in a finally block, so the lock is released even if an exception is thrown.

import java.util.concurrent.locks.ReentrantLock;

public class WalletWithLock {
    private final ReentrantLock lock = new ReentrantLock();
    private int balance = 1000;

    boolean withdraw(int amount) {
        lock.lock();                      // wait until we own the lock
        try {
            if (balance < amount) {
                return false;             // check and act inside the lock
            }
            balance -= amount;
            return true;
        } finally {
            lock.unlock();                // always release the lock
        }
    }

    int balance() {
        lock.lock();
        try {
            return balance;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WalletWithLock wallet = new WalletWithLock();
        Thread[] shoppers = new Thread[4];
        int[] successes = new int[4];

        for (int i = 0; i < shoppers.length; i++) {
            int index = i;
            shoppers[i] = new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    if (wallet.withdraw(5)) successes[index]++;
                }
            });
            shoppers[i].start();
        }
        for (Thread s : shoppers) s.join();

        int total = successes[0] + successes[1] + successes[2] + successes[3];
        System.out.println("successful withdrawals: " + total);
        System.out.println("final balance: " + wallet.balance());
    }
}

Output:

successful withdrawals: 200
final balance: 0

How it works:

  • Four threads try 400 withdrawals of Rs. 5 from a wallet holding Rs. 1000.
  • The balance check and the subtraction both happen while the thread holds lock, so only 200 withdrawals succeed and the balance stops at exactly 0.
  • balance() also locks, so a reader never sees a half-finished update. Each thread writes only its own slot of successes, and main reads them after join().

Race Conditions vs Data Races

The two terms are related but not the same. You can have a race condition even when every single operation is thread-safe.

Data raceRace condition
MeaningTwo threads access the same variable, at least one writes, and there is no synchronizationThe result depends on the timing of threads
ExamplePlain int updated by two threadsif (!map.containsKey(k)) map.put(k, v) on a ConcurrentHashMap
Fixed by thread-safe classes alone?Usually yesNo, the combined steps must be atomic

The ConcurrentHashMap example has no data race, because each call is safe. It still has a race condition, because two threads can both pass the containsKey check. Single atomic methods such as putIfAbsent() and computeIfAbsent() solve this, as shown in Java Thread Safety.


Real-World Example: A Coupon Redemption Service

A festival sale coupon can be used at most 50 times in total and once per user. Ten checkout threads process 200 redemption attempts at the same time, because each user taps the button twice. Every rule must hold no matter how the threads interleave.

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;

public class CouponService {
    enum Result { REDEEMED, ALREADY_USED, LIMIT_REACHED }

    private final int maxRedemptions;
    private final Set<String> usedBy = new HashSet<>(); // guarded by "this"
    private int redeemedCount = 0;                       // guarded by "this"

    CouponService(int maxRedemptions) {
        this.maxRedemptions = maxRedemptions;
    }

    // Both checks and both updates run as one atomic step
    synchronized Result redeem(String userId) {
        if (usedBy.contains(userId)) {
            return Result.ALREADY_USED;
        }
        if (redeemedCount >= maxRedemptions) {
            return Result.LIMIT_REACHED;
        }
        usedBy.add(userId);
        redeemedCount++;
        return Result.REDEEMED;
    }

    synchronized int redeemedCount() {
        return redeemedCount;
    }

    public static void main(String[] args) throws InterruptedException {
        CouponService festivalSale = new CouponService(50);
        Map<Result, LongAdder> stats = new ConcurrentHashMap<>();

        Thread[] checkoutThreads = new Thread[10];
        for (int t = 0; t < checkoutThreads.length; t++) {
            int threadNo = t;
            checkoutThreads[t] = new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    String userId = "user-" + (threadNo * 10 + i);
                    for (int attempt = 0; attempt < 2; attempt++) { // every user taps twice
                        Result result = festivalSale.redeem(userId);
                        stats.computeIfAbsent(result, key -> new LongAdder()).increment();
                    }
                }
            });
            checkoutThreads[t].start();
        }
        for (Thread checkout : checkoutThreads) checkout.join();

        System.out.println("total attempts : 200");
        new TreeMap<>(stats).forEach((result, count) ->
                System.out.printf("%-14s : %d%n", result, count.sum()));
        System.out.println("redeemed count : " + festivalSale.redeemedCount());
    }
}

Output:

total attempts : 200
REDEEMED       : 50
ALREADY_USED   : 50
LIMIT_REACHED  : 100
redeemed count : 50

How it works:

  1. Two check-then-act rules. "Has this user already redeemed?" and "Is the limit reached?" are both checks followed by updates. Putting all of them inside one synchronized method removes both races.
  2. Guarded state. usedBy is a plain HashSet and redeemedCount is a plain int. They are safe only because every access goes through a method that locks this.
  3. The proof. 100 users tap twice. The first 50 users to get the lock redeem the coupon, and their second tap returns ALREADY_USED (50). The other 50 users get LIMIT_REACHED on both taps (100). Which 50 users win changes between runs, but the totals never do.
  4. Statistics. ConcurrentHashMap.computeIfAbsent() with a LongAdder counts results from ten threads without losing any.

When the threads in this example need to hold two locks at the same time, a new danger appears: threads waiting for each other forever. That problem is covered in the next lesson, Java Deadlocks. To review how main waits for the worker threads, see Java Thread Join.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Race Conditions and get answers drawn from it.

Signed-in readers only.