AdvancedLesson 17 of 205 min read

Concurrency: Threads, Executors and Shared Data

Learn how Java runs work on several threads, why shared counters lose updates, how atomic classes and locks fix that, and how an executor splits a sum across tasks, with results checked by a formula.

In this lesson you will

  • Start threads and wait for them
  • See a race condition
  • Fix it with atomics and locks
  • Split work with an executor

About 28 minutes

Four counters at the till

Hana’s shop now has four tills, each handled by a different thread, and all of them add to one shared total of rentals. At the end of the day the total is lower than the sum of the four tills. Nothing crashed. This is a race condition: when several threads read, change and write the same variable, their steps interleave and updates are lost. Concurrency is powerful, because it lets a program use all the processor cores and wait for slow things such as the network without blocking everything else, and it is also where the most subtle bugs live.

A thread is an independent path of execution. You can create one with new Thread(runnable), start it, and wait for it with join. The statement count++ looks like one step but is really three: read the value, add one and write it back, so two threads can read the same value and both write the same result, losing one increment. There are two main cures. A synchronized block lets only one thread at a time enter, using a lock. The classes in java.util.concurrent.atomic, such as AtomicInteger, make single operations like increment indivisible without an explicit lock. For bigger jobs you rarely manage threads yourself, and instead submit tasks to an ExecutorService, which keeps a pool of threads and returns a Future for each task.

Tool Use it for
Thread, join Learning, and simple background tasks
synchronized Protecting a block of code or a method with a lock
AtomicInteger A shared counter with no lock
ConcurrentHashMap A map used by many threads
ExecutorService Running many tasks on a pool of threads
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static int plain = 0;
    static int locked = 0;
    static final AtomicInteger atomic = new AtomicInteger();
    static final Object lock = new Object();

    public static void main(String[] args) throws Exception {
        final int threads = 4, perThread = 250_000;
        List<Thread> ts = new ArrayList<>();
        for (int t = 0; t < threads; t++) {
            Thread th = new Thread(() -> {
                for (int i = 0; i < perThread; i++) {
                    plain++;
                    synchronized (lock) { locked++; }
                    atomic.incrementAndGet();
                }
            });
            ts.add(th); th.start();
        }
        for (Thread th : ts) th.join();
        int expected = threads * perThread;
        System.out.println("expected " + expected);
        System.out.println("plain int:     " + plain + (plain == expected ? " (no update lost this time)" : " (updates lost: " + (expected - plain) + ")"));
        System.out.println("synchronized:  " + locked);
        System.out.println("AtomicInteger: " + atomic.get());

        ExecutorService pool = Executors.newFixedThreadPool(4);
        List<Future<Long>> parts = new ArrayList<>();
        long n = 1_000_000L;
        for (int k = 0; k < 4; k++) {
            final long from = k * (n / 4) + 1, to = (k + 1) * (n / 4);
            parts.add(pool.submit(() -> { long s = 0; for (long x = from; x <= to; x++) s += x; return s; }));
        }
        long total = 0;
        for (Future<Long> f : parts) total += f.get();
        pool.shutdown();
        System.out.println("parallel sum of 1.." + n + " = " + total);
        System.out.println("formula n(n+1)/2   = " + n * (n + 1) / 2);
    }
}
expected 1000000
plain int:     986478 (updates lost: 13522)
synchronized:  1000000
AtomicInteger: 1000000
parallel sum of 1..1000000 = 500000500000
formula n(n+1)/2   = 500000500000

Four threads each added 250,000 times, so the right answer is 1,000,000. The synchronized counter and the AtomicInteger both reached exactly 1,000,000. The plain int ended at 986,478, so 13,522 updates were lost in this run, silently, with no error message. Run it again and the number changes, because the loss depends on how the threads happen to interleave, which is what makes race conditions so hard to find by testing. The lesson is that a program that passes a test once may still be incorrect.

The executor part split the sum of 1 to 1,000,000 into four tasks of 250,000 numbers, ran them on a pool of four threads, and added up the four futures. The result is 500,000,500,000, and the formula n(n+1)/2 gives 500,000,500,000, so the parallel result is correct. Each task works on its own range and shares nothing, which is the easiest kind of concurrency to get right. Notice also that f.get() waits until the task is finished, and that the pool must be shut down, or the program would not exit.

Check by hand: 4 x 250,000 = 1,000,000. The sum 1 + 2 + … + n equals n x (n + 1) / 2, so for one million it is 1,000,000 x 1,000,001 / 2 = 500,000,500,000, the number printed twice.

Shared mutable data is the problem

Every variable that two threads can change needs a plan: a lock, an atomic class, a concurrent collection, or better, no sharing at all.

Prefer executors and immutable data

Give each task its own input and collect results through futures. Immutable objects can be shared by any number of threads safely.

About this course

Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21. The number of lost updates in the unprotected counter varies from run to run and from machine to machine.

Practice

Change the program to use eight threads and compare how the plain counter behaves. Replace the synchronized counter by a LongAdder and read its sum. Write a task that counts the words of several strings in parallel and combine the counts with a ConcurrentHashMap.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is a race condition?

  1. A fast program
  2. Threads interleaving on shared data and losing updates
  3. A compile error
  4. A very long loop

The result depends on timing.

Why is count++ unsafe across threads?

  1. It is three steps: read, add, write
  2. It is too slow
  3. It needs a license
  4. It only works for long

Two threads can read the same value.

What does synchronized do?

  1. Lets one thread at a time run a block
  2. Speeds up a loop
  3. Sorts threads
  4. Closes a file

It uses a lock.

What does a Future give you?

  1. A new thread
  2. A file
  3. A password
  4. The result of a task when it finishes

Call get to wait for it.

How was the parallel sum verified?

  1. By trusting it
  2. By running it once
  3. By counting threads
  4. With the formula n(n+1)/2

Both gave 500,000,500,000.

Summary

  • A race condition loses updates when threads share mutable data.
  • synchronized and atomic classes make updates safe.
  • An ExecutorService runs tasks on a thread pool and returns futures.
  • A single successful run does not prove thread safety.

Next lesson

Lesson 18 covers professional practices: immutability, Optional and packaging.

Questions

How many threads should I use?

For CPU-heavy work, about the number of cores. For waiting on I/O, more can help. Measure on your own system.

What are virtual threads?

A newer Java feature, final in Java 21, that makes very many lightweight threads cheap, useful for servers that wait a lot. Check the official documentation.

Is volatile enough?

It guarantees visibility of a variable between threads, not atomic updates like increment.

Progress is saved in this browser.