Object-Oriented Programming with Java · Lecture Notes

Chapter 10: Threads

A program can do several things at once. A word processor checks spelling while you type, a browser stays responsive to one tab while it downloads another, and a server handles hundreds of requests together. Java does this with threads, independent flows of execution inside one program. These notes first introduce threads, processes, concurrency, and parallelism. They then cover the Thread class, the thread life cycle, the ways to create and start a thread, and how to stop one safely. The core of the chapter is the protection of shared data: race conditions, synchronized, volatile, explicit locks, deadlock, and waiting for a condition. The last sections introduce the ready-made tools of the java.util.concurrent package, atomic classes, interruption, ThreadLocal, and thread pools. The output of a program with several threads often changes from run to run. Every such output in these notes was measured by running the program many times on JDK 21, and each example states which part of the output may vary.

Learning outcomes

Concepts
Explain the difference between a thread and a process, and between concurrency and parallelism.
Creating threads
Write a thread by implementing Runnable or extending Thread, and start it with start().
Life cycle
Trace the six states and the transitions caused by sleep, join, wait, and waiting for a lock.
Synchronization
Recognize a race condition and prevent it with synchronized, volatile, Lock, and atomic classes.
Condition waiting
Write a producer–consumer program with wait/notify and Condition; avoid deadlock.
Ready-made tools
Use CountDownLatch, CyclicBarrier, Exchanger, Semaphore, ThreadLocal, and thread pools.

10.1Basic concepts

10.1.1Threads

Every program written so far ran as a single flow. The first line of main runs, then the second; if a method is called, the flow enters that method and resumes where it left off when the method returns. At any moment, the program's "position" can be described by a single line. That single flow is itself a thread.

Definition 10.1

A thread is an independently progressing flow of execution inside a program. It executes instructions one after another and has its own call stack and its own program counter. In Java, every thread is represented by an object of the class java.lang.Thread.

Every Java program starts with at least one thread. The JVM creates a thread to run main(); it is called the main thread. If the program starts new threads, they run alongside the main thread. Working with several threads is called multithreading. Programming in which several tasks make progress during the same period of time is called concurrent programming.

process (JVM)heap: objects (shared)mainown stack, PCT1own stack, PCT2own stack, PC
Figure 10.1: Threads in a process. The heap is shared; each thread has its own stack.

The slides compare the situation to a beehive. Each bee does its own job; that is a thread. But all the bees use the same hive and the same honeycomb; that is shared memory. If two bees try to put honey into the same cell at the same moment, there is trouble. Most of this chapter is about how to organize such collisions.

Why do we need several threads? Three reasons stand out:

  • A responsive interface. In a program with a graphical interface, a long computation done on the thread that draws the interface freezes the window. If the computation is given to a separate thread, the user can keep pressing buttons.
  • Using multicore processors. Most of today's processors have 4, 8, or more cores. A single-threaded program uses only one of them. If the work is split into pieces, the cores run at the same time and the computation speeds up.
  • Working while waiting. Waiting for data to arrive over the network or for a file to be read from disk is very slow compared with the processor. While the waiting thread sleeps, another thread carries on with its work.

10.1.2Concurrency and parallelism

In everyday speech, "at the same time" describes two different situations. In technical language, the two have different names.

Definition 10.2

Concurrency means that several tasks make progress during the same period of time. It can happen even on a single core: the operating system runs threads in turn for very short time slices. Parallelism means that tasks really run at the same instant on different cores; it requires more than one core.

One coreconcurrencyABABABABABTwo coresparallelismC1AC2Btime
Figure 10.2: Left, one core: A and B run in turn in time slices. Right, two cores: A and B run at the same time.

The left half of Figure 10.2 shows one core. A runs for a slice, then B, then A again. Because the slices last milliseconds, the user believes that both jobs advance at once. This is concurrency but not parallelism: at any given instant, only one thread is on the processor. The right half has two cores, and A and B really run at the same time. Parallelism is a special case of concurrency.

The scheduler of the JVM and the operating system decides which thread runs when and on which core. The programmer cannot know or control this order. The same program may run A first in one execution and B first in another. This nondeterminism is the most distinctive feature of multithreaded programs.

10.1.3Processes and threads

Definition 10.3

A process is a running program that has its own memory space. The operating system gives each process a separate address space. Inside a process, one or more threads run; these threads share the process's memory.

Process: a running JVMHeap: objects and arraysshared by ALL threadsmainStacklocal variablesPC: next instructionThread-0Stacklocal variablesPC: next instruction
Figure 10.3: One process: a shared heap, and a separate stack and program counter for each thread.
Table 10.1: Comparison of a process and a thread.
ProcessThread
MemoryIts own address spaceShares the process's heap
Stack—Each has its own
CreationExpensiveCheap (lightweight process)
CommunicationFiles, sockets, pipesShared objects
RiskCannot corrupt each otherCan corrupt shared data

A running Java program is a process, and many threads run inside it. Table 10.1 summarizes the difference between the two concepts. The objects on the heap are open to all threads of the process. If two threads hold references to the same object, both can read and modify it. Local variables, on the other hand, live on each thread's own stack and are not shared. Even if two threads run the same method at the same time, the method's local variable i has two separate copies.

This distinction cuts both ways. The good side is that sharing data between threads is very easy: it is enough to write to a shared object. Two processes can send data to each other only through operating-system facilities such as files, sockets, or pipes. The bad side is that two threads that know nothing about each other can modify a shared object at the same time. One process cannot corrupt another's memory; a thread can corrupt anything in its own process.

Creating a thread is much cheaper than creating a process, because no new address space is opened; only a new stack is allocated. That is why a thread is also called a lightweight process.

10.1.4Context switching

A computer usually has many more threads than cores. The operating system runs them in turn in time slices. When a thread's slice ends, its state is saved and the state of the next one is loaded.

Definition 10.4

Context switching is the processor's move from one thread to another. During the switch, the state of the running thread (program counter, registers, stack pointer) is saved and the state of the next thread is loaded.

one core:T1T2T3T1T2▲ context switch: save registers, load the other threadEvery switch takes time; if the number of threads far exceeds the number of cores, this cost grows.
Figure 10.4: On one core, threads run in turn, with a context switch between them.

Context switching has a price. Each switch takes a few microseconds. More importantly, some of the data in the processor's cache is useless to the new thread and has to be read from memory again. For this reason, adding threads does not always speed things up. A program that starts thousands of threads spends a significant part of its time on switches and slows down.

There is a practical rule. For compute-bound work, keep the number of threads at about the number of cores. The core count is available from Runtime.getRuntime().availableProcessors(); the examples in these notes were run on a machine with 12 logical cores. For I/O-bound work (network, files), more threads can help because most of them are asleep much of the time. A thread pool keeps the number under control.

10.1.5The JVM and threads

Java programs do not run directly on the operating system but inside the Java Virtual Machine (JVM). The JVM is a virtual environment that manages threads as independent units of execution. In today's JVMs, every Java thread corresponds to an operating-system thread, and the operating system does the scheduling.

Class LoaderJVM memory areasMethod area(class data)HeapobjectsStack(per thread)PC register(per thread)Native methodstackExecution Engine(interpreter, JIT, GC)Native Method Interface(JNI)NativelibrariesShared: all threads use themOne per thread
Figure 10.5: JVM architecture. The method area and the heap exist in a single copy; the stack, the PC register, and the native method stack are separate for each thread.

Figure 10.5 shows the memory areas of the JVM. When a thread is created, the JVM gives it three private areas:

  • Stack: holds the frames of method calls, local variables, and parameters.
  • Program counter (PC) register: holds the address of the instruction the thread is currently executing.
  • Native method stack: serves calls to native methods written outside Java, for example in C.

The method area (the code of classes and static fields) and the heap (all objects) exist in a single copy and are shared by all threads. A static field and an object on the heap are therefore shared between two threads; local variables are not.

Common mistake

Believing that local variables are also shared between threads. If two threads run void count() { int i = 0; i++; } at the same time, each increments its own i on its own stack; both get 1 and neither affects the other. Trouble begins when two threads write to a field of the same object or to the same static field.

10.2The Thread class

10.2.1The class and its basic methods

Every thread is an object of the class Thread in the java.lang package. Because the package is java.lang, no import is needed. The Thread object manages the life cycle of the thread: it starts it, makes it wait, and holds its name and state.

One way to write a thread is to write a subclass of Thread. The subclass overrides the run() method and puts the thread's work there. The thread is then started by calling start(). The difference between the two methods is critical: run() is the work itself, and start() is the call that opens the new flow. Table 10.2 summarizes the frequently used methods of the class.

Table 10.2: The basic methods of the Thread class.
MethodPurpose
start()Starts the new thread, which then runs run()
run()The work the thread does
sleep(ms)static: puts the running thread to sleep for a given time
join()Waits for that thread to finish
yield()static: temporarily gives up execution to others
interrupt()Sends an interrupt request
currentThread()static: the thread that is running right now
getName(), getState(), isAlive()Read information

It is significant that sleep, yield, and currentThread are static. They act not on a particular Thread object but on the thread that executes that line. The thread that writes Thread.sleep(100) puts itself to sleep; there is no way to put another thread to sleep.

10.2.2Thread properties

A Thread object carries several properties that describe the thread. They are fields of the object, with get/set methods to read or change them.

Runnable
The object that contains the run() method the thread will execute. The main logic of the thread is defined here.
Name
Such as main, Thread-0, Thread-1. If no name is given, the JVM appends an increasing number to the prefix Thread-. It is used to recognize the thread in log files and while debugging: getName(), setName().
ID
A unique number assigned automatically when the thread is created. Since Java 19 it is read with threadId(); older versions used getId().
Group (ThreadGroup)
The group the thread belongs to. It is used to organize threads.
Daemon
A helper thread that serves other threads. The JVM does not wait for it to finish when shutting down.
Context class loader
The class loader the thread uses when it loads classes at run time.
Priority
An integer between MIN_PRIORITY (1) and MAX_PRIORITY (10); the default is NORM_PRIORITY (5).
State
One of NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED.
Interrupted
A flag showing whether an interrupt request has arrived; it is set by interrupt().

The following fragment runs inside main and prints the properties of the thread that is running at that moment.

Thread t = Thread.currentThread();   // current
System.out.println("Name    : " + t.getName());
// threadId(): Java 19+ (getId() before)
System.out.println("ID      : " + t.threadId());
System.out.println("Priority: " + t.getPriority());
String group = t.getThreadGroup().getName();
System.out.println("Group   : " + group);
System.out.println("Daemon  : " + t.isDaemon());
System.out.println("State   : " + t.getState());
Name    : main
ID      : 1
Priority: 5
Group   : main
Daemon  : false
State   : RUNNABLE

Thread.currentThread() returns the thread that executes that line. Because the code is in main, this is the main thread. Its name is main, its ID is 1, and its priority is the default 5. Its group is also named main. The main thread is not a daemon thread. Its state is RUNNABLE, because the thread calling getState() is running at that moment. Run on JDK 21, the program printed these six lines identically every time.

Priority and the daemon property are inherited from the thread that creates the new thread. A thread created in main has priority 5 and is not a daemon. These values can be changed before start().

Example 10.1

In main, before any other thread has been created, these lines run: Thread a = new Thread(() -> { }, "worker");, Thread b = new Thread(() -> { });, Thread c = new Thread(() -> { });, and c.setPriority(Thread.MAX_PRIORITY);. What are the names of a, b, and c, and the priorities of b and c?

The names are worker, Thread-0, and Thread-1. A thread that is given a name does not use up an automatic number; numbers go in order only to unnamed threads. The priority of b is 5, inherited from the creating thread (main); that of c is 10. None of the three was ever started, so their states are NEW. On JDK 21 the program printed worker Thread-0 Thread-1 and 5 10 false.

10.2.3Thread groups

When the JVM starts, it creates two thread groups. The system group contains the JVM's own threads: Reference Handler, which manages references, the finalizer Finalizer, Signal Dispatcher, which handles signals, and others. The main group is a subgroup of system; the main thread and the threads the program creates belong to it by default.

system groupReference HandlerFinalizerSignal DispatcherAttach Listener …main groupmainThread-0, Thread-1 …userJVM daemon threads
Figure 10.6: Thread groups: the JVM threads and the main group under the system group.

Thread.getAllStackTraces() returns all live threads and their stacks as a map. Iterating over the key set lists them all:

Set<Thread> all =
        Thread.getAllStackTraces().keySet();
for (Thread t : all) {
    System.out.println(t.getThreadGroup().getName()
            + "  " + t.getName()
            + "  daemon=" + t.isDaemon());
}
system  Notification Thread  daemon=true
main  main  daemon=false
system  Signal Dispatcher  daemon=true
system  Reference Handler  daemon=true
system  Attach Listener  daemon=true
InnocuousThreadGroup  Common-Cleaner  daemon=true
system  Finalizer  daemon=true

This output was taken from one run on JDK 21. The list has seven threads, and all except main are daemon threads. Common-Cleaner is in a separate group, InnocuousThreadGroup. The order of the lines depends on the internal layout of the map. In ten runs the order was always the same, but that is not a guarantee. Which JVM threads appear in the list also varies with the JVM version and settings.

10.2.4Threads running when the JVM starts

The slides discuss four of the threads that exist when the HotSpot JVM starts:

Main thread
The first thread that runs when the JVM starts. The main() method runs here; the core logic of the application executes here.
Garbage collector
Responsible for memory management. It finds and cleans up objects that no longer have references. In the HotSpot JVM, the garbage collector's threads are internal JVM threads; they do not appear as Java objects, so they are not in the list above.
Signal Dispatcher
Handles signals from the operating system. For example, on a shutdown request that arrives with Ctrl+C, it starts the orderly shutdown of the JVM.
Finalizer
Calls the finalize() method of objects. finalize() was deprecated in Java 9 and marked for removal in Java 18 (JEP 421). If the JVM is started with the --finalization=disabled option, the finalizer thread never starts. Use try-finally or try-with-resources with AutoCloseable instead.

10.3The life cycle

10.3.1The six states

From the moment it is created until it finishes, a thread passes through different states. The getState() method returns the current state as a constant of the Thread.State enumeration. Java defines six states.

Table 10.3: Thread states.
StateMeaningHow it is entered
NEWThe object has been created but not yet startednew Thread(…); exit: start()
RUNNABLERunning, or waiting for its turn on the processorAfter start()
BLOCKEDWaiting for a monitor lock to enter a synchronized block or methodWhile another thread holds the lock
WAITINGWaiting indefinitely; another thread must wake itObject.wait(), Thread.join(), LockSupport.park()
TIMED_WAITINGWaiting for a limited timeThread.sleep(ms), wait(ms), join(ms), parkNanos, parkUntil
TERMINATEDHas completed executionWhen run() returns

Table 10.3 makes one point clear: Java has no separate RUNNING state. The thread that is on the processor right now and a thread waiting for its turn are both RUNNABLE. The scheduler knows which one is really on the processor; the JVM does not expose this distinction to the program.

The three waiting states should not be confused. BLOCKED means only waiting for a monitor lock: the thread wants to enter a synchronized block, but the lock is held by another thread. WAITING is waiting indefinitely for an event: another thread must finish (join) or wake it (notify). TIMED_WAITING is waiting for a limited time; when the time runs out, the thread returns on its own. That is why sleep always produces TIMED_WAITING.

10.3.2The state diagram

NEWRUNNABLETERMINATEDBLOCKEDWAITINGTIMED_WAITINGstart()run() endswaits for synchronized lock⇄ gets the lockwait(), join()⇄ notify(), task endssleep(ms), wait(ms)⇄ time is up
Figure 10.7: The state diagram. NEW becomes RUNNABLE with start(); there are round trips between RUNNABLE and the three waiting states; when run() ends, the thread is TERMINATED.

Figure 10.7 shows the transitions. The main path is one-way: NEW → RUNNABLE → TERMINATED. There is no way back. A thread that has finished cannot be restarted; to do the same work again, a new Thread object is needed. From each of the three waiting states, on the other hand, the thread returns to RUNNABLE: when the lock is free, when the awaited event happens, or when the time runs out.

10.3.3Code trace: observing the states

The following program puts four threads into different states and prints their states. pause(ms) and waitFor(t) are helper methods that wrap the calls Thread.sleep and t.join() in try-catch. lock is a field of type static final Object.

public static void main(String[] args) {
    Thread sleeper = new Thread(() -> pause(1000));
    System.out.println("1) " + sleeper.getState());
    sleeper.start();
    pause(100);
    System.out.println("2) " + sleeper.getState());
    Thread waiter = new Thread(() -> waitFor(sleeper));
    waiter.start();
    pause(100);
    System.out.println("3) " + waiter.getState());
    Thread blocked = new Thread(() -> {
        synchronized (lock) { }
    });
    synchronized (lock) {
        blocked.start();
        pause(100);
        System.out.println("4) " + blocked.getState());
    }
    waitFor(waiter);
    System.out.println("5) " + sleeper.getState());
}
Table 10.4: Trace of the state-observation program.
StepLineVariables / stateNew output
12: Thread sleeper = new Thread(() -> pause(1000));——
23: System.out.println("1) " + sleeper.getState());—1) NEW
34: sleeper.start();——
45: pause(100);——
56: System.out.println("2) " + sleeper.getState());—2) TIMED_WAITING
68: waiter.start();——
710: System.out.println("3) " + waiter.getState());—3) WAITING
815: blocked.start();——
917: System.out.println("4) " + blocked.getState());—4) BLOCKED
1019: waitFor(waiter);——
1120: System.out.println("5) " + sleeper.getState());—5) TERMINATED

In steps 1 and 2, the sleeper object is created but not started; its state is NEW. In step 3, start() is called. The new thread immediately enters pause(1000) and sleeps for a second. Meanwhile main also sleeps for 100 ms. When main wakes up, sleeper is still asleep: TIMED_WAITING.

In step 6, waiter is started and calls sleeper.join(). join without a timeout is indefinite; waiter stays in the WAITING state until sleeper finishes. In step 8, main acquires the monitor of lock and then starts blocked. blocked wants to enter a synchronized block on the same lock, but main holds it. While main sleeps for 100 ms inside the block, it prints the state: BLOCKED.

mainRUNNABLEsleeperTIMED_WAITINGwaiterWAITINGblockedBLOCKED
Figure 10.8: Step 9. main holds the lock and sleeps; sleeper is asleep, waiter is waiting for it, and blocked is waiting for the lock.

Figure 10.8 shows the situation in step 9: four threads are in four different states. One point deserves attention. While main sleeps inside sleep, it does not release the lock, so blocked cannot get in. When the block ends, the lock is released, blocked enters, leaves immediately, and finishes. main then waits for waiter. sleeper finishes its full second and ends; waiter then finishes too. The last line prints the state of sleeper: TERMINATED.

Although this program is multithreaded, its output is stable. The waiting times determine which state the threads will be in at each observation: 100 ms is enough for a thread to start and enter sleep or join. The program was run 8 times and printed the same five lines each time. Even so, such timing assumptions can break on a heavily loaded machine. The delays are used here only for observation, not for synchronization.

10.4Creating and starting threads

10.4.1The Runnable interface

Every thread runs a Runnable object. The Runnable interface is in the java.lang package and contains a single method:

package java.lang;

public interface Runnable {
    void run();
}

A class that implements this interface writes the run() method. The body of the method is the work the thread will do.

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // The thread's tasks
    }
}

Because Runnable has a single abstract method, it is a functional interface. Since Java 8, a lambda expression can be written in place of such an interface. A separate class is not needed for short tasks:

Runnable r = () -> System.out.println("hello");

The lambda gives the body of the run() method directly. Its parameter list is empty because run() takes no parameters, and since the return type is void, the lambda returns no value.

10.4.2Starting a thread

A Runnable object is not a thread by itself; it only describes the work to be done. To run the work in a new thread, the object is passed to the Thread constructor and start() is called.

public class Worker implements Runnable {
    // The thread's work goes here
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println("Worker running: " + name);
    }
    public static void main(String[] args) {
        // Start the thread
        Worker w = new Worker();
        Thread t = new Thread(w);
        t.start();
        System.out.println("main goes on");
    }
}

The slides show the output of one run like this:

main goes on
Worker running: Thread-0

main creates the Worker object and passes it to the constructor to create a Thread. t.start() opens the new thread and returns immediately. From then on there are two threads: main moves on to the next line and prints main goes on, while Thread-0 runs run() and prints its own name. The name was given automatically: the first unnamed thread the program creates is Thread-0.

Which of the two lines is printed first is not determined. As soon as start() returns, main continues; the scheduler decides when the new thread gets the processor. The program was run 40 times on JDK 21, and main goes on came first every time. The reverse order is also valid and can be seen on another machine or under load. The measured distribution varies with the machine and the load; the correctness of a program must never depend on any particular order.

Common mistake

Calling run() instead of start(). t.run() is an ordinary method call: the code runs in the caller's thread, that is, in main, and no new thread is opened. The program raises no error, but nothing runs in parallel. For this reason the mistake often goes unnoticed.

10.4.3Code trace: two stacks, two flows

Tracing the same program step by step shows what start() really does. The trace shows one of the possible orders, the one in which main prints first.

Table 10.5: One possible order of the Worker program.
StepLineVariables / stateNew output
19: Worker w = new Worker();w=Worker object, t=…—
210: Thread t = new Thread(w);w=Worker object, t=Thread-0 (NEW)—
311: t.start();w=Worker object, t=Thread-0 (RUNNABLE)—
412: System.out.println("main goes on");w=Worker object, t=Thread-0 (RUNNABLE)main goes on
513: }t=Thread-0 (RUNNABLE)—
64: String name = Thread.currentThread().getName();t=Thread-0 (RUNNABLE), name="Thread-0"—
75: System.out.println("Worker running: " + name);t=Thread-0 (RUNNABLE), name="Thread-0"Worker running: Thread-0
86: }t=Thread-0 (TERMINATED)—

In step 2 the Thread object has been created and its state is NEW. But there is not yet a separate flow of execution; the object is an ordinary object waiting on the heap. In step 3, start() is called. The JVM opens a new stack and starts run() on that stack. start() itself returns without waiting for run() to finish.

mainemptyTERMINATEDThread-0run()RUNNABLE
Figure 10.9: Step 6. main() has finished, but Thread-0 is running run() on its own stack. name is its local variable.

In step 5, the main() method ends. The program does not. The JVM keeps running until all threads that are not daemon threads have finished. Figure 10.9 shows this moment: the stack of main is empty, and the stack of Thread-0 holds the frame of run(). The variable name is in this frame, and no other thread can see it. In step 8, run() ends and Thread-0 becomes TERMINATED. With no running threads left, the JVM exits.

10.4.4Extending Thread

A thread can also be written by extending the Thread class. Thread already implements Runnable; the subclass only overrides run().

public class Worker2 extends Thread {
    // The thread's work goes here
    public void run() {
        String name = getName();   // inherited from Thread
        System.out.println("Worker running: " + name);
    }
    public static void main(String[] args) {
        // Create and start the thread
        Worker2 w = new Worker2();
        w.start();
        System.out.println("main goes on");
    }
}
main goes on
Worker running: Thread-0

In this approach the Runnable object and the Thread object are the same. Because the object is itself a Thread, w.start() is called directly. Inside run(), getName() is written without a prefix because the method is inherited from Thread. The output order may again vary: in 40 runs, main printed first every time.

10.4.5start() or run()?

The difference between start() and run() becomes visible when both are called one after the other on the same object.

public class StartVsRun {
    public static void main(String[] args)
            throws InterruptedException {
        Thread t = new Thread(() -> {
            String name = Thread.currentThread().getName();
            System.out.println("inside run(): " + name);
        });
        t.run();     // WRONG: main runs it
        t.start();   // RIGHT: a new thread
        t.join();
    }
}
inside run(): main
inside run(): Thread-0

The first line comes from t.run(). This call is an ordinary method call inside main; currentThread() returns main. The second line comes from t.start(): now run() runs in the new thread, Thread-0. The order of the output is fixed: execution does not reach the t.start() line until the t.run() call has finished. join() makes main wait until Thread-0 ends.

Table 10.6: The difference between calling run() and start().
CallWhat happens
t.run()An ordinary method call: runs in the same thread (main), no new stack, and main waits until it finishes.
t.start()The JVM creates a new thread and stack; run() runs there, and start() returns immediately.
t.start() a second timeIllegalThreadStateException: a Thread object can be started only once.

The rule is short: the thread's work goes into run(), and the thread is started with start(). If start() is called a second time on the same object, JDK 21 threw java.lang.IllegalThreadStateException both while the thread was running and after it had finished. The reason is the one-way path in the state diagram: start() is valid only for a thread in the NEW state.

Example 10.2

A thread named T is created; its job is to print "run: " + Thread.currentThread().getName(). Then these lines run in order: t.run();, System.out.println("A " + t.getState());, t.start();, t.join();, and System.out.println("B " + t.getState());. What does the program print?

The call t.run() runs in main: run: main. The thread has still never been started: A NEW. After start(), run() runs on T's own stack: run: T. join() waits until T ends, so the last line is B TERMINATED. Because join() fixes the order, these four lines are the same in every run; the program was run five times and always gave the same output.

10.4.6The single-inheritance problem

Java allows a class to inherit from only one class. If the class that should run in a thread already extends another class, it cannot extend Thread. Writing class Worker extends Base, Thread is a compile-time error; javac reports '{' expected at the comma.

The solution lies in the Runnable interface. There is no limit on the number of interfaces a class can implement. The class extends Base, implements Runnable, and, if needed, keeps a field of type Thread inside.

Base+ greet(): void«interface»Runnable+ run(): voidWorker- thread: Thread+ run(): void+ start(): voidextendsimplements
Figure 10.10: Worker extends Base and implements Runnable; it has a Thread field named thread.
class Base {
    public void greet() {
        System.out.println("Hello from Base");
    }
}
class Worker extends Base implements Runnable {
    private Thread thread;   // Thread as a field
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println("run(): " + name);
    }
    public void start() {
        thread = new Thread(this);
        thread.start();
    }
}
public class SingleInheritance {
    public static void main(String[] args) {
        Worker w = new Worker();
        w.greet();   // inherited from Base
        w.start();   // our own start()
    }
}
Hello from Base
run(): Thread-0

Worker both inherits the methods of Base and can run in a thread. w.greet() is the method that comes from Base, and it runs in main. w.start() is not the start() of Thread but a start() method that Worker defines itself. It hands itself to a Thread with new Thread(this) and starts it. this is of type Runnable, which is why the Thread constructor accepts it. The order of the two output lines is fixed: greet() finishes before the thread is started.

This pattern separates the work from the thread. Worker describes "what to do", and the Thread object describes "how to run it". The same Runnable object can later be handed to a thread pool as well. This is why Runnable is preferred in most cases.

10.4.7Comparing the three ways

The following program puts the three ways of creating a thread side by side. A static class is a class defined inside another class; it can be used without an instance of the outer class.

public class ThreeWays {
    static class Task implements Runnable {     // 1)
        public void run() {
            System.out.println("1) Runnable class");
        }
    }
    static class MyThread extends Thread {       // 2)
        public void run() {
            System.out.println("2) Thread subclass");
        }
    }
    public static void main(String[] args)
            throws InterruptedException {
        Thread t1 = new Thread(new Task());
        Thread t2 = new MyThread();
        // 3) Lambda (Java 8+)
        Thread t3 = new Thread(
                () -> System.out.println("3) Lambda"));
        t1.start(); t1.join();
        t2.start(); t2.join();
        t3.start(); t3.join();
    }
}
1) Runnable class
2) Thread subclass
3) Lambda

Because each start() is followed immediately by join(), one thread does not begin before the previous one has finished. The output order is therefore fixed. Of course, this usage defeats the whole point of threads; the program was written only to show the three ways.

Table 10.7: Three ways to create a thread.
WayWhen to use it
implements RunnableWhen the class already extends another class; keeps the work and the thread separate
extends ThreadShort, self-contained examples; uses up the one inheritance slot
Lambda (Java 8+)The most practical way for short tasks

10.4.8Code trace: two threads

How does the output come about when two threads really run together? In the following program, two threads named A and B run the same task() method. The second argument of the Thread constructor is the thread's name.

public class TwoThreads {
    static void task() {
        String name = Thread.currentThread().getName();
        for (int i = 1; i <= 2; i++) {
            System.out.println(name + ": step " + i);
        }
    }
    public static void main(String[] args)
            throws InterruptedException {
        Thread a = new Thread(() -> task(), "A");
        Thread b = new Thread(() -> task(), "B");
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println("main: done");
    }
}
Table 10.8: One possible order of the two threads (the order in the slides).
StepLineCall stackVariables / stateNew output
112: a.start();main()a=RUNNABLE, b=NEW—
213: b.start();main()a=RUNNABLE, b=RUNNABLE—
314: a.join();main()a=RUNNABLE, b=RUNNABLE, main=WAITING—
45: System.out.println(name + ": step " + i);A: run() → task()A.i=1, B.i=—, main=WAITINGA: step 1
55: System.out.println(name + ": step " + i);B: run() → task()A.i=1, B.i=1, main=WAITINGB: step 1
65: System.out.println(name + ": step " + i);A: run() → task()A.i=2, B.i=1, main=WAITINGA: step 2
75: System.out.println(name + ": step " + i);B: run() → task()A.i=2, B.i=2, main=WAITINGB: step 2
816: System.out.println("main: done");main()A=TERMINATED, B=TERMINATED, main=RUNNABLEmain: done

In steps 1 and 2, main starts the two threads. Both are RUNNABLE, but which one will run when is not determined. In step 3, main begins waiting for A to finish with a.join() and becomes WAITING. Now it is A and B that are running.

mainAB▶a▶b11time →
Figure 10.11: Step 5. A context switch: B is running now. The i of B is a separate local variable from the i of A.

In steps 4–7, A and B each print one line in turn. At every context switch, the other thread resumes where it left off. The i of A and the i of B are on separate stacks; incrementing one does not affect the other. In step 8, a.join() returns. Because B has already finished, b.join() returns without waiting, and main prints the last line.

This order is only one of the possible ones. The program was run 60 times on JDK 21; the outputs seen and their counts:

32 times:  B: step 1 · B: step 2 · A: step 1 · A: step 2 · main: done
25 times:  A: step 1 · A: step 2 · B: step 1 · B: step 2 · main: done
 3 times:  B: step 1 · A: step 1 · A: step 2 · B: step 2 · main: done

When the same two threads were started repeatedly inside a single JVM, the picture changed: in 6,000 trials, A1 · A2 · B1 · B2 occurred 5,958 times, B1 · B2 · A1 · A2 35 times, A1 · B1 · A2 · B2 5 times, and A1 · B1 · B2 · A2 2 times. In a warmed-up JVM, a new thread starts very quickly and finishes its short job before the other one even starts. The order in the slides was indeed seen, though rarely. Two things are certain. First, main: done is always last, because it is printed after both join() calls. Second, the two lines of the same thread keep their order relative to each other: A: step 2 never comes before A: step 1. The lines of the two threads, however, can interleave in any way.

Example 10.3

In main these run in order: start a, a.join(), start b, print "m", b.join(). Thread a prints "a" and b prints "b". Which outputs are possible?

a.join() does not let main proceed until a has finished, so a is always the first letter. After b is started, main printing m races with b running. The possible outputs are abm and amb; mab is impossible. b.join() only prevents the program from ending before b. In five rounds of 300 trials each inside a single JVM, 1,500 trials in all, every one gave amb; in 40 runs with separate JVMs, amb was seen every time as well. By the time the new thread starts, main has usually already printed its line. Still, abm is a valid order; no order is guaranteed.

10.5Managing and stopping threads

10.5.1sleep, join, and yield

Three basic methods control the flow of a thread.

sleep(ms)
Puts the running thread to sleep for a given time; during this time the thread is in the TIMED_WAITING state. A sleeping thread does not release the locks it holds.
join()
The calling thread waits until the target thread has finished. The form join(ms) waits at most ms milliseconds; when the time is up it returns even if the target has not finished.
yield()
A hint that the thread is willing to give up execution temporarily to another thread. The scheduler may ignore the hint, so no order is guaranteed with yield().

The following program shows why join() is needed. The calc thread adds the numbers from 1 to 1,000,000 and writes the result into a static field.

public class JoinDemo {
    static long result = 0;
    public static void main(String[] args)
            throws InterruptedException {
        Thread calc = new Thread(() -> {
            long sum = 0;
            for (int i = 1; i <= 1_000_000; i++) {
                sum += i;
            }
            result = sum;
        });
        calc.start();
        System.out.println("before join: " + result);
        calc.join();   // wait for calc to end
        System.out.println("after join : " + result);
    }
}
before join: 0
after join : 500000500000

Right after start(), main reads result. The computation has not yet finished at that point; main sees the initial value, 0. The program was run 30 times, and the first line was 0 every time. This is not a guarantee: a main that was slow to continue, or a very fast computation, could have shown the result on the first line as well. After join(), however, the situation is certain. The computation has finished, and the value it wrote is visible to main: 1 + 2 + … + 1,000,000 = 1,000,000 · 1,000,001 / 2 = 500,000,500,000.

It matters that the result is kept in a long. The total is about 5 · 1011, far above 2,147,483,647, the upper limit of int.

join() gives a second guarantee: everything the target thread wrote is visible to the thread that returns from join(). That is why it is not a problem that result is not volatile.

sleep and join can throw InterruptedException, a checked exception. Wherever they are called, they must therefore be either caught or declared with throws InterruptedException. Most examples in the slides declare main with throws InterruptedException. Inside a lambda, throws cannot be written, because run() declares no checked exceptions; there try-catch is mandatory.

Common mistake

Writing Thread.sleep(100); without try-catch in a method that does not declare throws. The compiler reports unreported exception InterruptedException; must be caught or declared to be thrown. The fix is a try-catch or adding throws InterruptedException to the method signature.

10.5.2Daemon threads

Definition 10.5

A daemon thread is a helper thread that does not prevent the JVM from shutting down. The JVM exits when all threads that are not daemon threads have finished; it does not wait for daemon threads to finish.

public class DaemonDemo {
    public static void main(String[] args)
            throws InterruptedException {
        Thread clock = new Thread(() -> {
            int s = 0;
            while (true) {
                System.out.println("tick " + s++);
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    return;
                }
            }
        });
        clock.setDaemon(true);   // BEFORE start()
        clock.start();
        Thread.sleep(1000);
        System.out.println("main done, JVM exiting");
    }
}
tick 0
tick 1
tick 2
tick 3
main done, JVM exiting

clock is in an infinite loop and prints a line every 300 ms. setDaemon(true) makes it a daemon thread. main sleeps for one second, prints its last line, and ends. Only a daemon thread is left, so the JVM exits; the loop of clock is cut off midway.

How many tick lines are printed? clock prints at about 0, 300, 600, and 900 ms; its fourth sleep would end at 1200 ms. main wakes up at 1000 ms. The expected output is therefore four tick lines. The program was run 10 times and printed four tick lines every time. Like any output that depends on timing, this is not guaranteed; the margin between 900 ms and 1000 ms is small.

setDaemon(true) must be called before start(). If it is called after the thread has started, IllegalThreadStateException is thrown; this behavior was tried on JDK 21. Daemon threads are meant for helper work such as logging, cache cleanup, or periodic checks. A job that writes to a file or must not be interrupted is not given to a daemon thread, because when the JVM exits, even finally blocks may be cut off without running.

10.5.3Stopping a thread

A thread stops when its run() method completes. The JVM exits in two cases: when System.exit() (internally Runtime.exit()) is called, or when all threads that are not daemon threads have finished.

The right way to stop a thread from outside is cooperation. The thread to be stopped checks a flag at regular intervals; when the flag is raised, it finishes its work cleanly and leaves run(). The flag is declared volatile so that a change made by another thread becomes visible. A second way is to send an interrupt request with interrupt().

Older versions of Java had a method called Thread.stop(). It killed the thread in the middle of its work. The locks the thread held were suddenly released, and the objects they protected were left half updated. For example, money might have been withdrawn from one account but not yet deposited into the other. The method stayed deprecated for a long time; since Java 20 it no longer works:

Thread t = new Thread(() -> { });
try {
    t.stop();
} catch (UnsupportedOperationException e) {
    System.out.println("stop(): not supported");
}
stop(): not supported

On JDK 21, stop() always throws UnsupportedOperationException. In the same experiment, suspend() and resume() threw the same exception.

10.5.4Stopping with a flag

class Worker extends Thread {
    private volatile boolean flag = false;
    public void finish() { flag = true; }
    public void run() {
        while (!flag) {
            System.out.println("working...");
            try { Thread.sleep(100); }
            catch (InterruptedException e) { return; }
        }
        System.out.println("flag seen, finishing");
    }
}
public class FlagStop {
    public static void main(String[] args)
            throws InterruptedException {
        Worker w = new Worker();
        w.start();
        Thread.sleep(350);
        w.finish();   // raise the flag
        w.join();     // wait for it to end
        System.out.println("main: worker stopped");
    }
}
working...
working...
working...
working...
flag seen, finishing
main: worker stopped

finish() only raises the flag; it does not stop the thread by force. The worker checks the condition !flag at the start of every iteration. On the first iteration in which it sees the flag raised, it leaves the loop, prints its last line, and returns from run() by itself. main waits for the worker to finish with join().

The timing is as follows: the worker prints at about 0, 100, 200, and 300 ms. main wakes up at 350 ms and raises the flag. When the worker wakes at 400 ms, it sees the flag. The program was run 15 times, and four working... lines were seen every time. The count depends on timing; the correctness of the flag method does not depend on the count.

What would happen if the flag were not volatile? The worker could keep the value it first read in a cache or a register and never see the change. In this example, the sleep call in the loop often hides the problem; in an empty loop, the thread could really get stuck.

10.5.5Stopping through a reference

A second form of cooperative stopping is to keep a reference to the thread itself instead of a flag.

class Worker implements Runnable {
    private volatile Thread thread;
    public void start() {
        thread = new Thread(this);
        thread.start();
    }
    public void finish() { thread = null; }
    public void run() {
        Thread me = Thread.currentThread();
        while (thread == me) {   // ... work ...
        }
        System.out.println("run() done");
    }
}
public class ReferenceStop {
    public static void main(String[] args) throws Exception {
        Worker w = new Worker();
        w.start();
        Thread.sleep(200);
        w.finish();
        Thread.sleep(200);
        System.out.println("main: done");
    }
}
run() done
main: done

The class implements Runnable and keeps the running Thread object in a volatile field. The loop continues as long as the field still points to its own thread. The comparison with Thread.currentThread() checks this. finish() sets the field to null; the condition fails and run() ends. main stops the worker after 200 ms, waits another 200 ms, and prints its last line. In ten runs, the output was always these two lines.

One detail: currentThread() is a static method of Thread. In a class that does not extend Thread, it must be written with the Thread. prefix. If the prefix is forgotten, the compiler reports cannot find symbol. Because the body of the loop is empty, the thread keeps one core completely busy for these 200 ms. In a real program, the body does some work or sleeps for a short time.

10.6Synchronization

10.6.1Why the order breaks

When several threads work with the same data, performing operations in the right order is hard for three reasons.

Speed is unpredictable
The speed and frequency at which each thread runs vary. Operating systems may ignore priorities, so priority cannot be trusted for ordering.
Values can go stale
After one thread reads a variable, another can update the value. The first keeps working with an out-of-date value.
Instructions can be reordered
The compiler, the JIT (just-in-time) compiler, and the processor may change the order of instructions for speed. In a single thread this goes unnoticed; with more than one, it causes unexpected behavior.
T1T2read x → 5write x + 1 = 6 (stale!)write x = 9T2's 9 is lost
Figure 10.12: A stale value: T1 reads, then T2 writes; T1 continues with the old value.

If several threads access shared, changing data, the access must be synchronized. Otherwise the result depends on the order in which the threads run.

Definition 10.6

A race condition occurs when the result of a program depends on the order in which threads run. Synchronization is the coordination of the threads' access to shared data so that the result no longer depends on that order.

10.6.2Race conditions

The simplest race example is two threads incrementing the same counter. Each thread does counter++ 100,000 times; the expected result is 200,000.

public class RaceCondition {
    static int counter = 0;   // shared data
    public static void main(String[] args)
            throws InterruptedException {
        Runnable inc = () -> {
            for (int i = 0; i < 100_000; i++) {
                counter++;   // read, add 1, write: NOT atomic
            }
        };
        Thread t1 = new Thread(inc);
        Thread t2 = new Thread(inc);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Expected: 200000");
        System.out.println("Actual  : " + counter);
    }
}

Three runs in the slides gave 138001, 135352, and 136776. For these notes the program was run 20 more times on JDK 21. The values found:

136210, 145954, 155340, 149684, 132748, 125554, 126412, 156356, 126897, 144040, 137525, 127748, 117573, 164660, 129167, 134217, 140315, 129857, 128366, 133715
(smallest 117573, largest 164660)

Every run gave a different result, and none reached 200,000. Some of the increments are lost. The amount lost varies completely from run to run; it depends on the number of cores in the machine, the load at that moment, and when the JIT compiles the code. In a program that makes few increments (say 1,000), the result is often correct, because the threads may finish without ever overlapping. The bug therefore looks random and is hard to catch by testing.

10.6.3Code trace: why does counter++ lose updates?

In the source code, counter++ looks like a single operation. On the processor it is three steps: read the value from memory, add one, write it back to memory.

// counter++ is three CPU steps:
int reg = counter;     // 1) read
reg = reg + 1;          // 2) add 1
counter = reg;          // 3) write

If two threads perform these three steps at the same time, the steps can interleave. The following trace shows an order in which a counter that starts at 0 stays at 1 after two increments.

Table 10.9: One possible interleaving of the counter++ steps. The "Call stack" column shows the thread running at that moment.
StepLineCall stackVariables / state
11: // counter++ is three CPU steps:—counter=0, t1.reg=—, t2.reg=—
22: int reg = counter; // 1) readt1counter=0, t1.reg=0, t2.reg=—
32: int reg = counter; // 1) readt2counter=0, t1.reg=0, t2.reg=0
43: reg = reg + 1; // 2) add 1t1counter=0, t1.reg=1, t2.reg=0
54: counter = reg; // 3) writet1counter=1, t1.reg=1, t2.reg=0
63: reg = reg + 1; // 2) add 1t2counter=1, t1.reg=1, t2.reg=1
74: counter = reg; // 3) writet2counter=1, t1.reg=1, t2.reg=1

In step 2, t1 reads the counter: its register gets 0. A context switch happens at exactly this point. In step 3, t2 also reads the counter; because t1 has not written yet, it also sees 0. In steps 4 and 5, t1 adds 1 in its own register and writes 1 to memory.

memorycounter = 1t1reg = 1t2reg = 1write
Figure 10.13: Step 7. t2 added 1 to its own stale value and wrote it. Two increments were made, but counter is 1.

In steps 6 and 7, t2 adds 1 to the old value in its own register, that is, to 0, and writes 1. A 1 has been written on top of the 1 that t1 wrote. Two increments were made, but the result is 1: the increment of t1 is lost (Figure 10.13). This event is called a lost update.

This is only one of the possible orders. If no interleaving occurs, that is, if one thread finishes its three steps before the other starts, the result is correct. In the program with 100,000 increments each, this interleaving happens thousands of times, and each time an increment is lost. The Thread Race simulator lets you order these steps by hand or at random and follow how the loss arises.

Example 10.4

The balance of an account is 500. T1 calls deposit(100) and T2 calls withdraw(30); the methods consist only of the lines balance += m and balance -= m and are not synchronized. Suppose the order is: T1 reads, T2 reads, T2 subtracts and writes, T1 adds and writes. What is the balance in the end, and what should it have been?

The correct result is 500 + 100 − 30 = 570. T1 reads 500. T2 also reads 500, subtracts 30, and writes 470. T1 adds 100 to the stale 500 and writes 600. The result is 600: the withdrawal by T2 is lost. If the last two writes had happened in the opposite order, the result would be 470, and this time the deposit would be lost. The solution is to protect both methods with the lock of the same object (synchronized).

10.6.4Synchronization options

Java offers many tools for coordinating threads. Each of them solves a different problem:

  • join(): waiting for a thread to finish.
  • synchronized: mutual exclusion with an object's monitor lock.
  • Lock objects (ReentrantLock, ReadWriteLock): explicit locking.
  • Barrier, semaphore, exchanger, countdown latch: CyclicBarrier, Semaphore, Exchanger, CountDownLatch.
  • volatile variables: making reads and writes visible to all threads.
  • Atomic objects: indivisible operations such as those of AtomicInteger.

There are also tools that look like synchronization but are not: priorities, putting a thread to sleep with sleep, giving way with yield, and timers. They do not guarantee order. Code written with the thought "I'll wait a bit, the other one will have finished" will one day produce a wrong result at a moment when the other one has not finished.

10.6.5synchronized and monitors

Definition 10.7

A monitor is an internal lock and waiting mechanism attached to every Java object that can be locked and unlocked. Only one thread can hold a monitor at a time. The synchronized keyword acquires the monitor of an object; when the block ends, the monitor is released automatically.

The monitor works like this. While t1 holds an object's monitor, if t2 also wants the same monitor, t2 waits; its state is BLOCKED. When the monitor is released, the waiting threads compete and only one of them gets the monitor. The monitor is released both when the block ends normally and when it is left through an exception. In this way mutual exclusion is achieved and data integrity is preserved.

Definition 10.8

A critical section is a piece of code that accesses shared data and must be executed by only one thread at a time. Mutual exclusion means that only one thread is in the critical section at a time.

The syntax is short. The object whose monitor will be used is written in parentheses:

synchronized (o) {
    // we hold o's monitor here
}

The counter increment in the race example is protected by such a block:

Runnable r = () -> {
    for (int i = 0; i < 50_000; i++) {
        synchronized (o) {   // take o's monitor
            shared++;
        }                    // monitor released
    }
};

When two threads run this task 50,000 times each, the result is 100000 every time. The program was run 10 times and always gave this value. Every shared++ is done while the monitor is held; the other thread cannot enter the block until one thread has finished its read–add–write steps.

The operation of the monitor goes step by step like this:

// t1 and t2 run the same code
synchronized (o) {
    shared++;     // critical section
}
  1. t1 and t2 reach the line synchronized (o) at the same time; the monitor is free.
  2. t1 wins and acquires the monitor. t2 waits in the entry set, BLOCKED.
  3. t1 leaves the block; the monitor is released automatically. The waiting threads compete.
  4. t2 acquires the monitor and enters the critical section.
  5. t2 leaves too. shared++ has been done twice, without interleaving.
entry setBLOCKEDobject omonitorowner: t1donet2t1
Figure 10.14: Step 2. t1 owns the monitor; t2 waits in the entry set, BLOCKED.

Which thread enters first is not determined. What matters is that the critical section is never executed by two threads at the same time. For monitor locking to work correctly, all threads must lock the same object. If each thread takes the monitor of its own object, there is no protection at all.

10.6.6Synchronized methods

synchronized can also be written in front of a method. This is the same as wrapping the whole body of the method in a synchronized block.

class C {
    synchronized void p() { ... }
    static synchronized void q() { ... }
    //...
}

The equivalent of the definition above is:

class C {
    void p() { synchronized (this) { ... } }
    static void q() { synchronized (C.class) { ... } }
    //...
}

Which object is locked depends on the kind of method:

  • Instance method: the monitor of the this object is locked.
  • static method: since there is no instance, the monitor of the class's C.class object is locked.

For this reason, a static synchronized method and an instance synchronized method do not block each other; they use different locks. This behavior was tried on JDK 21: while another thread held the monitor of C.class for 500 ms, x.p() ran without waiting, whereas C.q() waited until the monitor was released. When a body is written in place of ... in the code from the slides (for example n++, s++), both forms compile and behave the same.

The block form has an advantage: only the lines that really need it are locked. If only two lines of a long method touch shared data, locking the whole method makes the other threads wait for nothing.

Example 10.5

The class Counter implements Runnable; it has a static int total field, and its run() method is synchronized. run() increments total 100,000 times. Two threads run two separate objects with new Thread(new Counter()). Why can the total come out smaller than 200,000?

Each thread takes the monitor of its own object (this). Two different locks do not block each other, while the data they are supposed to protect is the shared static total. The program was run ten times, and the totals found ranged from 111,143 to 169,427; none was 200,000. The fix is for everyone to use the same lock: the increment in the loop goes into a synchronized (Counter.class) block. The corrected program gave 200000 in all five runs. AtomicInteger is another solution.

10.6.7Preventing the race

The counter in the race example is fixed by moving it into a class whose methods are synchronized.

class Counter {
    private int value = 0;
    public synchronized void increment() { value++; }
    public synchronized int getValue() { return value; }
}

public class SyncCounter {
    public static void main(String[] args)
            throws InterruptedException {
        Counter counter = new Counter();
        Runnable task = () -> {
            for (int i = 0; i < 100_000; i++) {
                counter.increment();
            }
        };
        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Result: " + counter.getValue());
    }
}
Result: 200000

increment() is now synchronized: the read–add–write steps are performed without being split. The program was run 10 times and printed Result: 200000 every time. The reading method getValue() is synchronized too. At first sight this may look unnecessary, because reading an int is a single step anyway. But if the read is not synchronized, there is no guarantee that the reading thread sees the current value. What was written before a lock is released becomes visible to the thread that acquires the same lock afterward.

Synchronization has a cost. Threads enter the critical section one at a time and wait for each other; the program becomes somewhat slower. That is why only shared data is protected. Local variables that only a single thread uses need no lock.

10.6.8Mutual exclusion: a priority queue

Synchronized methods are the shortest way to make a whole data structure thread-safe. The following priority queue returns the smallest element on each call. All methods use the same monitor, this.

class MinQueue {
    private int[] data;
    private int size;
    public MinQueue(int n) { data = new int[n]; }
    public synchronized void add(int o) {
        if (size == data.length)
            throw new HeapFullException();
        data[size++] = o;
    }
    public synchronized int remove() {   // the smallest
        int min = 0;
        for (int i = 1; i < size; i++) {
            if (data[i] < data[min]) min = i;
        }
        int result = data[min];
        data[min] = data[--size];
        return result;
    }
    public synchronized String toString() {
        return Arrays.toString(Arrays.copyOf(data, size));
    }
}

HeapFullException is not defined in the slides; here it was written as a class that extends RuntimeException and carries the message "Queue full". The queue is used from a single thread as follows:

MinQueue q =
        new MinQueue(3);
q.add(5);
q.add(2);
q.add(8);
System.out.println(q);
int x = q.remove();
System.out.println(x);
System.out.println(q);
q.add(1);
try {
    q.add(9);
} catch (HeapFullException e) {
    String m = e.getMessage();
    System.out.println(m);
}
[5, 2, 8]
2
[5, 8]
Queue full

After 5, 2, and 8 are added, the array is [5, 2, 8]. remove() finds the position of the smallest element by linear search: the 2 at position 1. That element is returned, the last element (8) is moved into its place, and the size decreases by one: [5, 8]. When 1 is added, the queue is full again. add(9) throws an exception, and the message is printed.

Why is synchronization essential in this class? The line data[size++] = o in add also contains a read–modify–write. If two threads add at the same time, both may read the same size and write to the same slot; one element is lost. If an add slips in the middle of remove, the position of the smallest element can change. Because all methods use the same monitor, no other method can start while one is running. Making toString() synchronized as well prevents printing a half-modified array.

10.7Visibility

10.7.1volatile fields

A race condition arises when two threads write at the same time. There is a subtler problem too: a value written by one thread may never be seen by another. Let us describe it with an intuitive model. For speed, processors keep values in caches close to the core or in registers. A compiler may also read a variable it believes does not change in a loop just once and keep it in a register. In that case, even if a thread on another core writes the new value to main memory, the first thread keeps working with the old value.

Definition 10.9

In a field declared with the volatile keyword, every read sees the last write to that field: a volatile write happens-before every subsequent read of the same field. In the intuitive model, this can be thought of as the value being read from main memory on every read and made visible to all threads immediately on every write. volatile guarantees visibility; it does not make multi-step operations atomic.

Core 1: maincache: stop = trueCore 2: tregister: stop = falseMain memory (intuitive model): stop = truewritesdoes not read again(old copy)
Figure 10.15: The intuitive model: main writes the new value to main memory; thread t keeps the old value in its register and does not see the change.

By the rules of the Java language, a single read or write of any variable other than long and double is already atomic. A 64-bit long or double value, however, may be written as two 32-bit halves on some JVMs. For volatile long and volatile double fields, this half-write cannot happen; reads and writes become atomic.

For a simple shared flag, volatile is enough; neither synchronized nor a lock is needed. But only a single read or a single write is atomic. Read–modify–write operations such as x++ are not atomic on a volatile field either.

10.7.2The visibility problem

public class VisibilityProblem {
    static boolean stop = false;   // NOT volatile!
    public static void main(String[] args)
            throws InterruptedException {
        Thread t = new Thread(() -> {
            long laps = 0;
            while (!stop) {
                laps++;
            }
            System.out.println("thread stopped");
        });
        t.setDaemon(true);
        t.start();
        Thread.sleep(500);
        stop = true;
        System.out.println("main: stop = true");
        t.join(2000);   // wait at most 2 s
        boolean alive = t.isAlive();
        System.out.println("still running? " + alive);
    }
}

The thread checks stop in an empty loop. After 500 ms, main sets stop to true and waits at most two seconds. Without volatile, the output in the slides is:

main: stop = true
still running? true

The thread never saw the change and is still running after two seconds. The cause is the JIT compiler. After the loop has run a few thousand times, the JIT translates it to machine code. Because nothing inside the loop changes stop, stop is read once and the loop runs like while (true). This transformation is entirely correct for a single-threaded program, and the Java rules allow it for a field that is not volatile.

The program was run 10 times on JDK 21, and the thread failed to see the change every time; the output was like the one in the slides. When the field was declared static volatile boolean stop, the thread stopped in all ten runs:

main: stop = true
thread stopped
still running? false

In one of these runs, the line thread stopped was printed before main: stop = true. This is not a contradiction: main first changes the field and then prints; the thread can see the change between these two steps and print its own line first.

The outcome can vary with the JVM, the processor, and when the JIT kicks in. On one machine the problem may never show up, on another it shows up every time. Correctness is not left to this kind of luck: a flag changed by another thread is always declared volatile. That is also the purpose of the setDaemon(true) call in the example: the stuck thread must not prevent the program from exiting.

10.7.3The limits of volatile

volatile does not solve the counter problem. Even if the counter in the race example is declared volatile, increments are lost:

static volatile int counter = 0;
// inside main:
Runnable r = () -> {
    for (int i = 0; i < 100_000; i++) counter++;
};

Three runs in the slides gave 163299, 164441, and 199332. The values found in 20 runs made for these notes:

157591, 188201, 171134, 181949, 163135, 175082, 150206, 177784, 184817, 187816, 178180, 174558, 168901, 171061, 179658, 173836, 168144, 176917, 170584, 172321
(smallest 150206, largest 188201)

The visibility problem is solved: every thread sees the current value on every read. But two threads can still read the same value and write the same result; the other thread can slip in between the read and the write. The solution is synchronized or AtomicInteger.

volatile cannot be combined with final either:

public class FinalVolatile {
    private final volatile int x = 5;
}
FinalVolatile.java:2: error: illegal combination of modifiers: final and volatile
    private final volatile int x = 5;
                               ^
1 error

The two keywords solve the same problem in different ways. Table 10.10 summarizes the difference.

Table 10.10: final and volatile.
finalvolatile
Assigned once (in the constructor); never changes afterwardThe value can change
When the constructor finishes (if this was not leaked from the constructor), everyone sees the same valueEvery read returns the current value

A final field never changes, so there is no visibility problem; Java guarantees that after the constructor finishes, all threads will see the correct value of the final field, provided this was not leaked to another thread before the constructor finished. volatile is meaningful only for fields that change. Because writing both together is contradictory, the compiler rejects it.

10.7.4The Java Memory Model and happens-before

When does one thread see a value written by another? The precise answer to this question is given by the Java Memory Model (JMM). The programmer does not have to think about processor caches and memory barriers; instead, they reason with happens-before relationships.

Definition 10.10

If operation A happens-before operation B, everything A wrote is guaranteed to be visible in B. The happens-before relation is transitive: if A happens-before B and B happens-before C, then A happens-before C.

Table 10.11: The main rules that establish a happens-before relation.
RuleA happens-before B
LockReleasing a monitor or lock → a later acquisition of the same lock
volatileWriting a volatile field → a later read of the same field
StartEverything before the call t.start() → the actions inside t
TerminationAll actions of t → the thread that returns from t.join()
Ready-made structuresBlockingQueue.put → the take that receives the same element; the work of a Future → get()

Visibility behavior in multithreaded programs is explained by these rules. In the join() example, result was not volatile, yet main saw the correct value: the termination rule. In the synchronized counter, getValue() being synchronized as well brings the lock rule into play. In the flag example, the volatile rule applies. If none of these relationships is established, there is no visibility guarantee between two threads.

There is also a performance problem that must not be confused with visibility: false sharing. Independent variables of different threads sit on the same cache line (usually 64 bytes), and if they are updated often, the cores keep pulling the line away from each other. The result is not wrong, but the program slows down. This is a performance problem, not a correctness problem.

10.8Explicit locks and deadlock

10.8.1The Lock interface

synchronized is simple and safe, but it is not flexible. A thread cannot give up while waiting for a lock, the wait cannot be limited by a timeout, and a waiting thread cannot be interrupted. For complex synchronization scenarios, the java.util.concurrent.locks package offers explicit locks.

Definition 10.11

An explicit lock is an object that implements the Lock interface. The lock is acquired with lock() and released with unlock(); the programmer calls both. ReentrantLock and ReentrantReadWriteLock are the main implementations of this interface.

Explicit locks do three things that synchronized cannot: try without waiting (tryLock()), wait for a limited time (tryLock(time)), and wait in an interruptible way (lockInterruptibly()). In return, the responsibility is the programmer's: the lock must not be forgotten. To use them, import java.util.concurrent.locks.*.

public class LockDemo {
    private final Lock lock = new ReentrantLock();
    private int counter = 0;
    public void work() {
        lock.lock();
        try {
            // critical section
            counter++;
        } finally {
            lock.unlock();
        }
    }
    public static void main(String[] args)
            throws InterruptedException {
        LockDemo o = new LockDemo();
        Runnable r = () -> {
            for (int i = 0; i < 100_000; i++) o.work();
        };
        Thread a = new Thread(r), b = new Thread(r);
        a.start(); b.start();
        a.join(); b.join();
        System.out.println("Result: " + o.counter);
    }
}
Result: 200000

The program is the race example rewritten with an explicit lock. Every counter++ is done while the lock is held. The program was run 10 times and printed Result: 200000 every time. The lock object is in a final field; all threads use the same lock.

10.8.2Unlocking in a finally block

The correct usage pattern for an explicit lock is always the same:

public void work() {
    Lock lock = ...;
    lock.lock();
    try {
        // access the guarded resource
    } finally {
        lock.unlock();
    }
}

lock() is called right before the try. unlock() is inside the finally. Even if an exception occurs in the critical section, finally runs and the lock is released. There is also a reason why lock() is written before the try and not inside it. If lock() fails, we do not want finally to try to release a lock that was never acquired.

lock.lock();
doWork();       // if this throws...
lock.unlock();  // ...we never get here

In this wrong form, if doWork() throws an exception, the unlock() line is never reached. The lock stays locked, and every thread that wants it waits forever. synchronized has no such problem: even if the block is left through an exception, the monitor is released automatically.

Example 10.6

The method divide(a, b) acquires the lock, prints a / b, and releases the lock; there is no finally. t1 calls divide(10, 0); after t1 finishes, t2 calls divide(10, 2). What is seen on the screen, and in what state does t2 remain?

In t1, 10 / 0 throws ArithmeticException. t1 terminates, but because unlock() is never reached, the lock stays locked. Only the stack trace of t1 appears on the screen; 5 is never printed. t2 waits in lock() forever. The test program was made to finish without hanging by turning t2 into a daemon thread and printing its state after 300 ms; in all three runs the state was WAITING. Because waiting on a Lock is not a monitor wait, the state is WAITING, not BLOCKED. When unlock() was moved into finally, t2 printed 5 and finished.

A second error is releasing a lock that was never acquired:

Lock lock = new ReentrantLock();
lock.unlock();   // never acquired
Exception in thread "main" java.lang.IllegalMonitorStateException
    at java.base/java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:175)
    at java.base/java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1059)
    at java.base/java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:494)
    at UnlockError.main(UnlockError.java:5)

ReentrantLock keeps track of the owner of the lock. If a thread that is not the owner calls unlock(), IllegalMonitorStateException is thrown. The full message printed by JDK 21 also shows where the exception occurred.

10.8.3tryLock()

tryLock() tries to acquire the lock without waiting. If the lock is free, it takes it and returns true; if it is held, it returns false without waiting at all. The form tryLock(3, TimeUnit.SECONDS) waits at most three seconds. Because the timed wait can be interrupted, InterruptedException must be declared.

static void work()
        throws InterruptedException {
    if (lock.tryLock()) {
        // got it
        try { System.out.println("1: acquired"); }
        finally { lock.unlock(); }
    } else {
        // didn't get it; do something else
        System.out.println("1: not acquired");
    }
    if (lock.tryLock(3, TimeUnit.SECONDS)) {
        try { System.out.println("2: acquired"); }
        finally { lock.unlock(); }
    } else {
        // not acquired within 3 seconds
        System.out.println("2: not acquired");
    }
}

The method is tested as follows: main acquires the lock, starts work() in a new thread, and releases the lock one second later.

lock.lock();   // main holds the lock
Thread t = new Thread(() -> {
    try { work(); }
    catch (InterruptedException e) { }
});
t.start();
Thread.sleep(1000);
System.out.println("main: releasing the lock");
lock.unlock();
t.join();
1: not acquired
main: releasing the lock
2: acquired

On the first attempt the lock is held by main; tryLock() returns false without waiting, and 1: not acquired is printed. The thread then starts waiting for at most three seconds. One second later, main releases the lock; the waiting thread acquires it immediately and prints 2: acquired. The output was the same in all five runs. Had main never released the lock, the second attempt would have returned false after three seconds; this case was tried separately and 2: not acquired (3 s) was seen.

10.8.4ReentrantLock and reentrancy

The name ReentrantLock means "a lock that allows re-entry". If the thread that holds the lock asks for the same lock once more, it does not wait; only a counter increases. The lock is really released when the counter drops back to 0.

Definition 10.12

A reentrant lock is a lock that lets the thread holding it acquire it again without waiting. The lock stores an owner and a hold count; each lock() increases the count by one, and each unlock() decreases it by one.

Nested critical sections with more than one lock can also be entered:

ReentrantLock lock1 = new ReentrantLock();
// true: a fair lock
ReentrantLock lock2 = new ReentrantLock(true);
// ...
lock1.lock();
try {
    // enter the critical section
    lock2.lock();
    try {
        // enter the nested section
        System.out.println("both locks acquired");
    } finally {  lock2.unlock();  }
} finally {  lock1.unlock();  }
System.out.println("fair? " + lock2.isFair());
both locks acquired
fair? true

new ReentrantLock(true) creates a fair lock: when the lock becomes free, it is given to the thread that has waited longest. The no-argument constructor gives a non-fair lock; lock1.isFair() returns false. A non-fair lock is faster, but it may let a thread keep waiting for a long time. When two locks are acquired in a nested way, the release order is the reverse of the acquisition order: first lock2, then lock1.

synchronized is reentrant too. A synchronized method can call another synchronized method of the same object; the thread does not wait for a monitor it already holds. Without reentrancy, such a call would lock the thread against itself.

The following program shows how the hold count changes.

import java.util.concurrent.locks.ReentrantLock;

public class Reentrancy {
    static final ReentrantLock lock =
            new ReentrantLock();
    static void show(String where) {
        System.out.println(where + lock.getHoldCount());
    }
    static void outer() {
        lock.lock();
        try { show("outer(): "); inner(); }
        finally { lock.unlock(); }
    }
    static void inner() {
        lock.lock();   // enters without waiting
        try { show("inner(): "); }
        finally { lock.unlock(); }
    }
    public static void main(String[] args) {
        outer();
        show("main:    ");
    }
}
Table 10.12: Trace of the reentrancy program.
StepLineCall stackVariables / stateNew output
120: outer();main()owner=none, count=0—
210: lock.lock();main() → outer()owner=main, count=1—
311: try { show("outer(): "); inner(); }main() → outer() → show()owner=main, count=1outer(): 1
415: lock.lock(); // enters without waitingmain() → outer() → inner()owner=main, count=2—
516: try { show("inner(): "); }main() → outer() → inner() → show()owner=main, count=2inner(): 2
617: finally { lock.unlock(); }main() → outer() → inner()owner=main, count=1—
712: finally { lock.unlock(); }main() → outer()owner=none, count=0—
821: show("main: ");main() → show()owner=none, count=0main: 0

In step 2, outer() acquires the lock: owner main, hold count 1. In step 4, inner() asks for the same lock. Because the owner of the lock is already main, it does not wait; the count becomes 2.

lockowner: maincount = 2
Figure 10.16: Step 4. The owner of the lock is main, and the hold count is 2.

In step 6, the finally of inner() calls unlock(). The count drops to 1; the lock is still held by main and no other thread can acquire it. In step 7, the finally of outer() brings the count down to 0, and the lock is really released. The last show call in main therefore prints 0. Because the output comes from a single thread, it is fixed. The rule is clear: every lock() needs one unlock(). An extra unlock() throws IllegalMonitorStateException; a missing unlock() leaves the lock locked forever.

10.8.5ReadWriteLock

Many data structures are read often and written rarely: a settings table, a cache, a dictionary. Because reads do not change the data, there is no need for them to block each other. ReadWriteLock handles this situation with two separate locks.

Reader-1Reader-2Reader-3Writerreads in parallelwrite aloneparallel againtime →
Figure 10.17: ReadWriteLock: readers read at the same time; nobody can read while the writer writes.
Read lock
More than one thread can read the data at the same time; they do not block each other while reading.
Write lock
While one thread writes, both reading and writing by the others are blocked; the write is safe and atomic.
private final Map<String, String> table =
        new HashMap<>();
private final ReadWriteLock lock =
        new ReentrantReadWriteLock();

public String get(String key) {
    lock.readLock().lock();   // lock for reading
    try {
        return table.get(key);   // read the data
    } finally {
        lock.readLock().unlock();
    }
}
public void put(String key, String value) {
    lock.writeLock().lock();  // lock for writing
    try {
        table.put(key, value);   // write the data
    } finally {
        lock.writeLock().unlock();
    }
}

ReentrantReadWriteLock is an implementation of the ReadWriteLock interface. get uses the read lock and put uses the write lock. The code that tries the class with two readers is:

Settings s = new Settings();
s.put("lang", "en");
Runnable reader = () -> System.out.println(
        Thread.currentThread().getName()
        + ": " + s.get("lang"));
Thread r1 = new Thread(reader, "Reader-1");
Thread r2 = new Thread(reader, "Reader-2");
r1.start(); r2.start();
r1.join(); r2.join();
Reader-2: en
Reader-1: en

Two readers can hold the read lock at the same time. This was tested separately: while one thread held the read lock, a call to readLock().tryLock() from a second thread returned true and writeLock().tryLock() returned false. The order of the lines varies: in 40 runs, Reader-1 printed first 22 times and Reader-2 18 times.

10.8.6Explicit versus intrinsic locking

Table 10.13: Explicit (Lock) and intrinsic (synchronized) locking.
Explicit: LockIntrinsic: synchronized
ControlThe programmer calls lock()/unlock()Automatic: acquired on entering the block, released on leaving it
ClassesThe Lock interface, ReentrantLock, ReentrantReadWriteLockA keyword; the monitor of every object
Trying without waitingtryLock(), tryLock(time)None: waits until the lock is free
Interruptible waitinglockInterruptibly()None
Fairness, conditionsnew ReentrantLock(true), several ConditionsNone; a single wait set
ReentrancyReentrantLock is reentrantAlways reentrant
RiskIf unlock() is forgotten, the lock stays held foreverNo risk of forgetting
When to useWhen advanced control is neededSimple scenarios, more readable code

Table 10.13 makes the choice easier. The default choice is synchronized: it is short, readable, and hard to get wrong. Lock is used when one of the extra capabilities in the table is really needed.

10.8.7Deadlock

Definition 10.13

A deadlock occurs when two or more threads wait forever for locks held by one another. It arises when locks are acquired in different orders by different threads.

static void useBoth(Object x, Object y, String name) {
    synchronized (x) {        // lock 1
        pause(100);
        synchronized (y) {    // lock 2
            System.out.println(name + " done");
        }
    }
}
public static void main(String[] args)
        throws InterruptedException {
    Thread t1 = new Thread(() -> useBoth(a, b, "T1"));
    Thread t2 = new Thread(() -> useBoth(b, a, "T2"));
    t1.setDaemon(true);
    t2.setDaemon(true);
    t1.start();
    t2.start();
    Thread.sleep(500);
    String s = t1.getState() + " " + t2.getState();
    System.out.println(s);
    long[] ids = ManagementFactory.getThreadMXBean()
            .findDeadlockedThreads();
    int n = (ids == null) ? 0 : ids.length;
    System.out.println("Deadlocked: " + n);
}
T1T2abholdswaitsholdswaits
Figure 10.18: A deadlock cycle: T1 holds a and waits for b; T2 holds b and waits for a.
BLOCKED BLOCKED
Deadlocked: 2

useBoth(x, y, name) first acquires the monitor of x and then that of y. T1 calls useBoth(a, b), while T2 calls useBoth(b, a) in the opposite order. pause(ms) is a helper that wraps sleep in try-catch; it makes both threads wait after acquiring their first lock and before asking for the second. After 500 ms, main prints the states of the two threads: both are BLOCKED. ThreadMXBean.findDeadlockedThreads() returns the IDs of the deadlocked threads; the count is 2.

The two threads were made daemon threads. This way, when main ends the JVM exits, and the deadlock does not leave the program hanging. The program was run 10 times, and BLOCKED BLOCKED and Deadlocked: 2 were seen every time. Because of the 100 ms sleep, the two threads almost always acquire their first locks together. Without the sleep, the deadlock would occur only in some runs.

Let us follow step by step how the deadlock is set up, using the shorter version from the slides. In this version the threads are not daemon threads; the program really waits forever.

static final Object a = new Object(), b = new Object();
static void useBoth(Object x, Object y, String name) {
    synchronized (x) {
        pause(100);
        synchronized (y) {
            System.out.println(name + " done");
        }
    }
}
public static void main(String[] args) {
    new Thread(() -> useBoth(a, b, "T1")).start();
    new Thread(() -> useBoth(b, a, "T2")).start();
}
Table 10.14: How the deadlock forms, step by step.
StepLineCall stackVariables / state
11: static final Object a = new Object(), b = new Object();
10: public static void main(String[] args) {
main()a=Object, b=Object
211: new Thread(() -> useBoth(a, b, "T1")).start();
3: synchronized (x) {
T1: useBoth(a, b)T1: x=a, y=b
312: new Thread(() -> useBoth(b, a, "T2")).start();
3: synchronized (x) {
T2: useBoth(b, a)T2: x=b, y=a
44: pause(100);T1: pause(100) → T2: pause(100)a=held by T1, b=held by T2
55: synchronized (y) {T1: useBoth(a, b)T1 wants=b
65: synchronized (y) {T1: useBoth(a, b) → T2: useBoth(b, a)T2 wants=a
76: System.out.println(name + " done");T1: useBoth(a, b) → T2: useBoth(b, a)T1=BLOCKED, T2=BLOCKED
812: new Thread(() -> useBoth(b, a, "T2")).start();T1: useBoth(a, b) → T2: useBoth(a, b)T2 call=useBoth(a, b, "T2")

In steps 2 and 3, T1 acquires a and T2 acquires b. So far there is no problem. In step 4, both sleep for 100 ms; sleep does not release a held lock. In step 5, T1 wakes up and asks for b for the inner block. b is held by T2: T1 becomes BLOCKED. In step 6, T2 also asks for a; a is held by T1. Each waits for the other to release, and a cycle forms.

lock alock bT1blockedT2blockedgreen: holds the lockred: waitingCYCLE
Figure 10.19: Step 6. The cycle is closed in the resource allocation graph: T1 → b → T2 → a → T1.

Neither can ever reach the "done" line. For these notes this program was run three times with a 6-second timeout. In all three, no line was printed and the process was terminated from outside at the timeout. A deadlock is never resolved without outside intervention; the JVM does not notice it and fix it on its own.

10.8.8Preventing deadlock

The most effective remedy for deadlock is a single change: all threads acquire locks in the same order.

Thread t1 = new Thread(() -> useBoth(a, b, "T1"));
Thread t2 = new Thread(() -> useBoth(a, b, "T2"));
T1 done
T2 done
TERMINATED TERMINATED
Deadlocked: 0

Everyone acquires a first and then b. T2 waits for a and never holds b; no cycle can form. When T1 finishes, it releases the locks, T2 acquires them, and it finishes too. The program was run 10 times, and the output was these four lines every time.

There are four ways to prevent deadlock:

Fixed lock order
All threads acquire locks in the same order; for example, by the ID number of the objects.
Timed attempt
If tryLock(time) cannot acquire the lock, the thread releases the locks it holds and tries again later.
Short critical sections
Do not ask for another lock while holding one, and do not do long work while holding a lock.
Diagnosis
The JDK's jstack tool or ThreadMXBean.findDeadlockedThreads() shows the deadlocked threads and the locks they hold.
Common mistake

Ignoring deadlock because "it never happens anyway". In a version without the sleep, if T1 takes a then b and T2 takes b then a, in most runs one of them acquires both locks and leaves, and the problem is not visible. For these notes, two threads each ran these two blocks 1,000 times, and the experiment was repeated at most 200 times. In all three separate runs, the deadlock occurred before this limit was reached. When a deadlock shows up varies from run to run; if its probability is not zero, it will happen sooner or later.

10.8.9Livelock and starvation

Deadlock is not the only progress problem. It has two relatives.

Deadlockeveryone is blocked, nothing changesLivelockeveryone is running, but there is no progressStarvationone thread keeps waiting for its turn
Figure 10.20: Deadlock, livelock, and starvation.
Livelock
The threads are not blocked; they keep changing state by constantly "giving way" to each other, but none of them can finish its work. It is like two people meeting in a narrow corridor who step to the same side at the same time. Example: two threads release the lock they hold when tryLock fails, try again at the same moment, and always collide.
Starvation
A thread cannot reach a resource for a long time, or at all: others always grab the lock, or long critical sections keep it waiting. Priority values (setPriority) are not a reliable way to solve this problem.
Lock fair = new ReentrantLock(true);  // fair
if (lock.tryLock(50, TimeUnit.MILLISECONDS)) {
    try { /* work */ }
    finally { lock.unlock(); }
} else {
    Thread.sleep(rnd.nextInt(20)); // random
}

The remedies are short. A fair lock gives the lock to the thread that has waited longest; the price is slightly slower operation. Waiting a random time before retrying breaks the symmetry of the two threads and prevents livelock; in the code, rnd.nextInt(20) does this job. Keeping critical sections short also ensures that everyone gets a turn.

10.9Condition synchronization

10.9.1Waiting for a condition

Mutual exclusion prevents two threads from entering the critical section at the same time. In some cases that is not enough: when a thread enters the critical section, the condition suitable for its work may not yet hold. Consider a shared queue. A consumer takes items from the queue, but if the queue is empty, there is nothing to take. A producer adds items, but if the queue is full, there is no room.

Definition 10.14

Condition synchronization ensures that a shared resource is accessed only when a certain condition holds. A thread waits until the condition holds; the thread that changes the condition wakes the waiting one.

Updating the queue safely requires the object's lock. It is also necessary to wait until the condition holds. But one cannot wait while holding the lock. If a consumer holds the lock while waiting for an item to arrive in the queue, the producer can never acquire the lock and cannot add an item; everyone gets stuck.

The first solution that comes to mind is to check the condition continuously in a loop:

while (queue.isEmpty()) {
    // burns CPU; if the lock is held,
    // the producer can never add
}

This busy waiting is wrong in two ways. The loop keeps one core completely busy for nothing. And if the lock is held, the producer can never add, and the loop goes on forever. Java offers three correct solutions:

  1. Object.wait() and Object.notify() / notifyAll().
  2. The Condition interface, used together with Lock.
  3. Synchronizer objects (CountDownLatch, Semaphore, …) and the ready-made BlockingQueue classes.

10.9.2wait() and notify()

Two sets are attached to the monitor of every object. The entry set holds the threads that want to acquire the monitor. The wait set holds the threads that are waiting for a condition to change.

entry setwaiting for the lockBLOCKEDmonitor owner(a single thread)wait setwaiting for a conditionWAITINGacquireswait():releasesnotify() / notifyAll(): the woken thread queues up to reacquire the lock
Figure 10.21: The monitor: entry set, owner, and wait set. wait moves a thread to the wait set, and notify returns it to the entry set.
  • The thread that holds the lock calls wait(): it enters the wait set, releases the lock, and blocks.
  • notify() wakes one thread from the wait set, and notifyAll() wakes all of them. The form wait(ms) also returns when the time is up.
  • The woken thread must first reacquire the lock. Once it has the lock, it returns from wait() and continues where it left off.

There are two rules. First, wait and notify are called only inside a synchronized block or method of the same object. Otherwise JDK 21 throws java.lang.IllegalMonitorStateException: current thread is not owner. Second, the condition is checked with while, not if. By the time the woken thread reacquires the lock, another thread may have invalidated the condition again. Java also allows a thread to wake up without any notify, a spurious wakeup. The while loop rechecks the condition on every wakeup.

Example 10.7

Inside a synchronized block, what is the difference between lock.wait() and Thread.sleep(1000)?

wait() releases the monitor and enters the wait set; when it is woken by notify or notifyAll, it reacquires the lock and continues. sleep() has nothing to do with the lock: it sleeps while holding it, and during that time everyone who wants the lock waits BLOCKED. Holding the lock while waiting for a condition keeps out the thread that would change the condition; that is why wait() is used for waiting on a condition.

10.9.3Blocking queues

The classic example of condition synchronization is the producer–consumer problem. Producer threads put items into a shared buffer, and consumer threads take them. If the buffer is full, the producer waits; if it is empty, the consumer waits. The following BlockingQueue class implements this buffer with a fixed-size array.

class BlockingQueue {
    private Object[] data;
    private int head = 0;
    private int tail = 0;
    private int count = 0;
    public BlockingQueue(int capacity) {
        if (capacity <= 0)
            throw new IllegalArgumentException(
                    "capacity must be > 0");
        data = new Object[capacity];
    }
    public synchronized int getSize() {
        return count;
    }
    public synchronized void add(Object item)
            throws InterruptedException {
        while (count == data.length) {
            wait();
        }
        data[tail] = item;
        tail = (tail + 1) % data.length;
        count++;
        notifyAll();
    }
    public synchronized Object remove()
            throws InterruptedException {
        while (count == 0) {
            wait();
        }
        Object item = data[head];
        data[head] = null;
        head = (head + 1) % data.length;
        count--;
        notifyAll();
        return item;
    }
}

The array is used circularly. head is the position of the element to be removed, and tail is the position where the next element will be added. On every add and remove the position advances by one; % data.length wraps it around at the end. count is the number of elements in the queue. remove sets the slot it read to null; this way the queue no longer holds an object that does not belong to it, and the garbage collector can reclaim it. The constructor rejects a capacity of 0 or less with IllegalArgumentException; in a queue of capacity 0, add would wait forever.

add waits when the queue is full (count == data.length); remove waits when the queue is empty. After every add or remove, notifyAll() wakes the waiting threads. Here notifyAll() is a deliberate choice. Both producers and consumers can be waiting in the same wait set. If notify() woke the wrong kind of thread, that thread would find the condition unsatisfied and wait again, and the right thread might never wake up.

10.9.4Code trace: producer and consumer

Let us trace one possible order in a queue of capacity 2, in which the producer adds 1, 2, 3 and the consumer takes them. The line numbers are those of the two methods below.

public synchronized void add(Object item)
        throws InterruptedException {
    while (count == data.length) {
        wait();
    }
    data[tail] = item;
    tail = (tail + 1) % data.length;
    count++;
    notifyAll();
}
public synchronized Object remove()
        throws InterruptedException {
    while (count == 0) {
        wait();
    }
    Object item = data[head];
    data[head] = null;
    head = (head + 1) % data.length;
    count--;
    notifyAll();
    return item;
}
Table 10.15: Producer–consumer trace (capacity 2, one possible order).
StepLineVariables / state
16: data[tail] = item;
7: tail = (tail + 1) % data.length;
8: count++;
head=0, tail=1, count=1
26: data[tail] = item;
7: tail = (tail + 1) % data.length;
8: count++;
head=0, tail=0, count=2
34: wait();head=0, tail=0, count=2
416: Object item = data[head];
17: data[head] = null;
18: head = (head + 1) % data.length;
19: count--;
head=1, tail=0, count=1
520: notifyAll();head=1, tail=0, count=1
63: while (count == data.length) {
6: data[tail] = item;
7: tail = (tail + 1) % data.length;
8: count++;
head=1, tail=1, count=2
716: Object item = data[head];
17: data[head] = null;
18: head = (head + 1) % data.length;
19: count--;
head=0, tail=1, count=1
816: Object item = data[head];
17: data[head] = null;
18: head = (head + 1) % data.length;
19: count--;
head=1, tail=1, count=0
914: wait();head=1, tail=1, count=0

In step 1, add(1) finds room: 1 is written to data[0] and tail advances to 1. In step 2, add(2) writes 2 to data[1]; tail wraps around to 2 % 2 = 0. The queue is full. In step 3, add(3) meets a full queue and calls wait(). The producer enters the wait set and releases the lock.

data[0]1data[1]2headtailProducerWAITINGConsumerrunning
Figure 10.22: Step 3. The queue is full; the producer is in the wait set because of wait(), and the lock is free.

Because the lock is free, the consumer can enter in step 4. remove() takes 1, sets the slot to null, and head becomes 1. In step 5, notifyAll() wakes the producer. But the lock is still held by the consumer, so the producer waits for the lock. When remove returns 1 and releases the lock, the producer acquires it in step 6. It rechecks the while condition: the queue is no longer full. 3 is written to data[0]. In steps 7 and 8, the consumer takes 2 and 3; the queue becomes empty. In step 9, the next remove() meets an empty queue and the consumer waits. It will wake up when the producer adds 4 and calls notifyAll().

This is one of the possible orders; the real order depends on the scheduler. But in no order does the queue overflow or get read while empty. while together with wait provides this guarantee.

The test program in the slides uses the queue with two threads. The consumer sleeps 100 ms before each item, so the producer fills the queue and has to wait.

BlockingQueue queue = new BlockingQueue(2);
Thread producer = new Thread(() -> {
    try {
        for (int i = 1; i <= 4; i++) {
            queue.add(i);
            System.out.println("produced: " + i);
        }
    } catch (InterruptedException e) { }
});
Thread consumer = new Thread(() -> {
    try {
        for (int i = 1; i <= 4; i++) {
            Thread.sleep(100);
            Object x = queue.remove();
            System.out.println("consumed: " + x);
        }
    } catch (InterruptedException e) { }
});
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println("left: " + queue.getSize());
produced: 1
produced: 2
produced: 3
consumed: 1
produced: 4
consumed: 2
consumed: 3
consumed: 4
left: 0

In this output from the slides, produced: 3 appears before consumed: 1. At first sight this is odd: 3 can be added only after 1 has been removed. The explanation is that println is outside the lock. The consumer returns from remove and is just about to print when the scheduler runs the producer; the producer adds 3 and prints its own line first. The program was run 40 times; the orders seen:

20 times:  produced: 1 · produced: 2 · produced: 3 · consumed: 1 · consumed: 2 · produced: 4 · consumed: 3 · consumed: 4
20 times:  produced: 1 · produced: 2 · produced: 3 · consumed: 1 · produced: 4 · consumed: 2 · consumed: 3 · consumed: 4

In all runs, the last line was left: 0, and every item was produced and consumed exactly once. The order of the lines varied from run to run.

10.9.5The Condition interface

wait and notify belong to the world of monitors. In a class that uses Lock, the Condition interface does the same job.

Definition 10.15

A Condition is a wait set attached to a Lock; it is created with lock.newCondition(). await() releases the lock and suspends the thread; signal() wakes one waiting thread, and signalAll() wakes all of them.

The main advantage of Condition is that several conditions can be attached to one lock. Producers and consumers wait in separate sets; each thread wakes only the relevant one.

class BlockingQueue {
    private final Lock lock = new ReentrantLock();
    private final Condition notFull =
            lock.newCondition();
    private final Condition notEmpty =
            lock.newCondition();
    private Object[] data;
    private int head = 0;
    private int tail = 0;
    private int count = 0;
    public BlockingQueue(int capacity) {
        if (capacity <= 0)
            throw new IllegalArgumentException(
                    "capacity must be > 0");
        data = new Object[capacity];
    }
    // add() and remove()
}
public void add(Object item)
        throws InterruptedException {
    lock.lock();
    try {
        while (count == data.length)
            notFull.await();
        data[tail] = item;
        tail = (tail + 1) % data.length;
        count++;
        notEmpty.signal();
    } finally {
        lock.unlock();
    }
}
public Object remove()
        throws InterruptedException {
    lock.lock();
    try {
        while (count == 0)
            notEmpty.await();
        Object item = data[head];
        data[head] = null;
        head = (head + 1) % data.length;
        count--;
        notFull.signal();
        return item;
    } finally {
        lock.unlock();
    }
}

The thread that adds signals only the notEmpty condition, and the thread that removes signals only notFull. Only consumers wait on notEmpty, and only producers wait on notFull. Because there are no unnecessary wakeups, signal() is enough in place of signalAll(). The lock is released in finally; await, like wait, sits inside a while loop.

The slides test the class with a producer and main: the producer adds 1 through 4, and main removes four times and prints the items separated by spaces.

1 2 3 4 

Because the queue works on the first-in, first-out (FIFO) principle, this output is always the same as far as order goes. The program was run ten times and always printed 1 2 3 4.

10.9.6A ready-made solution: ArrayBlockingQueue

Writing our own blocking queue is useful for understanding the mechanism. In real projects, the ready-made BlockingQueue implementations in the java.util.concurrent package are used: ArrayBlockingQueue, LinkedBlockingQueue, and others.

BlockingQueue<Integer> queue =
        new ArrayBlockingQueue<>(2);
Thread producer = new Thread(() -> {
    try {
        // put(): waits if the queue is full
        for (int i = 1; i <= 4; i++) queue.put(i);
    } catch (InterruptedException e) { }
});
producer.start();
for (int i = 1; i <= 4; i++) {
    // take(): waits if the queue is empty
    System.out.print(queue.take() + " ");
}
System.out.println();
producer.join();
1 2 3 4 

put() waits if the queue is full, and take() waits if it is empty. The waiting and waking are done inside the class; the programmer writes no locks or conditions. The result was 1 2 3 4 in all ten runs. Table 10.16 compares the three ways.

Table 10.16: Three ways to wait for a condition.
WayWaitingWaking
synchronizedwait()notify(), notifyAll()
Lock + Conditionawait()signal(), signalAll()
ArrayBlockingQueueinside put(), take()automatic
Example 10.8

With an ArrayBlockingQueue<Integer> of capacity 2, let a producer thread put the numbers 1 through 5, then −1 as an end marker. Let main take items and add them up until −1 arrives. What is the output?

The producer runs for (int i = 1; i <= 5; i++) q.put(i); and q.put(-1);. In a loop, main does int v = q.take();, leaves the loop if v < 0, and otherwise does total += v. Because the queue is FIFO, −1 always arrives last and all five numbers are added: Total: 15. A capacity of 2 only makes the producer wait more often; it does not change the result. The program was run five times and always printed Total: 15.

10.10Synchronizer objects

10.10.1Four ready-made tools

The java.util.concurrent package offers ready-made classes for common forms of coordination between threads. Each is a solution to a particular scenario.

Latch: 3 → 0210the gate opens at zeroBarrier: everyone must arrivethen go on togetherExchanger: swapABSemaphore: 2 permitsT1T2T3the third waits
Figure 10.23: CountDownLatch, CyclicBarrier, Exchanger, and Semaphore.
CountDownLatch
"Wait until N events have happened, then go on." Waiting threads stay put until the counter reaches zero. It is single-use.
CyclicBarrier
"Let all of us reach the meeting point, then continue together." It can be reused.
Exchanger
Two threads meet at a point and swap data.
Semaphore
N permits: at most N threads can enter the resource at the same time.

10.10.2CountDownLatch

A countdown latch coordinates threads that wait for a certain number of events. An initial count is given to the constructor. Each countDown() decreases the counter by one. A thread that calls await() waits until the counter reaches 0.

public static void main(String[] args)
        throws Exception {
    int count = 3;
    CountDownLatch latch = new CountDownLatch(count);
    for (int i = 0; i < count; i++) {
        int no = i + 1;   // copy for the lambda
        new Thread(() -> {
            System.out.println(no + ": event happened");
            // count down when the event happens
            latch.countDown();
        }).start();
    }
    // wait for the threads to finish
    latch.await();
    System.out.println("All events done!");
}

The line int no = i + 1; in the loop is important. A lambda can access only local variables that are final or effectively final (assigned once and never changed). The loop variable i changes in every iteration and cannot be used directly; javac reports this error: local variables referenced from a lambda expression must be final or effectively final. no, which is created anew in every iteration, never changes.

Table 10.17: One run of the CountDownLatch program (the order in the slides).
StepLineVariables / stateNew output
14: CountDownLatch latch = new CountDownLatch(count);counter=3—
211: }).start();counter=3—
314: latch.await();counter=3—
48: System.out.println(no + ": event happened");
10: latch.countDown();
counter=21: event happened
58: System.out.println(no + ": event happened");
10: latch.countDown();
counter=13: event happened
68: System.out.println(no + ": event happened");
10: latch.countDown();
counter=02: event happened
715: System.out.println("All events done!");counter=0All events done!

Three threads are started, and main waits in await(). Each thread prints its line and decreases the counter by one. In the run in the slides, the order is 1, 3, 2. When the last countDown() brings the counter to 0, the latch opens and main wakes up.

counter0123eventsmaincontinues
Figure 10.24: Step 6. The last event has happened and the counter is 0; the latch has opened and main is waking up.

The line All events done! is always last; the order of the event lines varies. The program was run 60 times; the orders seen:

13 times:  1 · 3 · 2
13 times:  1 · 2 · 3
12 times:  2 · 3 · 1
 9 times:  3 · 2 · 1
 7 times:  3 · 1 · 2
 6 times:  2 · 1 · 3

The latch is single-use. The counter never goes up and cannot be reset. A countDown() call when the counter is at 0 has no effect; the counter does not go negative. On a latch that has already opened, await() returns without waiting.

10.10.3CyclicBarrier

A cyclic barrier makes a group of threads wait at a meeting point. The constructor receives the number of threads to wait for, called the number of parties, and an optional barrier action.

public static void main(String[] args) {
    int parties = 3;
    Runnable action = () -> {
        System.out.println("Party complete!");
    };
    CyclicBarrier barrier =
            new CyclicBarrier(parties, action);
    for (int i = 0; i < parties; i++) {
        int no = i + 1;
        new Thread(() -> {
            try {
                System.out.println(no + " waiting");
                // wait for the others
                barrier.await();
                System.out.println(no + " continuing");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
1 waiting
2 waiting
3 waiting
Party complete!
3 continuing
1 continuing
2 continuing

Each thread waits when it calls await(). When the last member of the party also calls await(), the barrier action runs once, and then everyone continues. The thread that completes the party runs the action; this was tested separately. This output is one run as well. The line Party complete! always comes after the three waiting lines and before the three continuing lines. The order inside each group varies: in 60 runs, 8 different outputs were seen.

The barrier is "cyclic" in that after the party is full and everyone has passed, the same barrier can be used again. A typical example is players in a game waiting for one another at the end of every round. If one of the waiting threads gets an exception, times out, or is interrupted, the barrier is broken; the other waiting threads receive BrokenBarrierException.

10.10.4Exchanger

Exchanger is used for exchanging data between two threads. It is more a communication object than a lock.

static void swap(Exchanger<String> ex, String data, int ms) {
    try {
        System.out.println("sending: " + data);
        Thread.sleep(ms);
        String got = ex.exchange(data);   // wait for the other
        System.out.println(data + " owner got: " + got);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) {
    Exchanger<String> exchanger = new Exchanger<>();
    // The first thread sends "Data 1" after 2 s
    new Thread(() -> swap(exchanger, "Data 1", 2000)).start();
    // The second thread sends "Data 2" after 1 s
    new Thread(() -> swap(exchanger, "Data 2", 1000)).start();
sending: Data 2
sending: Data 1
Data 1 owner got: Data 2
Data 2 owner got: Data 1

exchange(data) waits until the other side also calls exchange. The owner of Data 2 arrives at exchange after one second and waits one more second. When the owner of Data 1 arrives after two seconds, they meet and each receives the other's data. The order of the first two lines depends on the order in which the two threads start; the last two lines also race at the moment of the meeting. In ten runs, 4 different outputs were seen.

10.10.5Semaphore

Definition 10.16

A semaphore is a counter that allows at most N threads to access a resource at the same time. acquire() takes a permit; if there is none, it waits. release() gives a permit back.

public static void main(String[] args) {
    int permits = 3;
    Semaphore semaphore = new Semaphore(permits);
    for (int i = 0; i < 5; i++) {
        int no = i + 1;
        new Thread(() -> {
            try {
                semaphore.acquire();   // take a permit
                System.out.println(no + " in");
                Thread.sleep(2000);
                System.out.println(no + " out");
                semaphore.release();   // give it back
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
Table 10.18: A semaphore with three permits and five threads (the run in the slides).
StepLineVariables / stateNew output
13: Semaphore semaphore = new Semaphore(permits);permits=3—
216: }).start();permits=3—
38: semaphore.acquire(); // take a permit
9: System.out.println(no + " in");
permits=21 in
48: semaphore.acquire(); // take a permit
9: System.out.println(no + " in");
permits=13 in
58: semaphore.acquire(); // take a permit
9: System.out.println(no + " in");
permits=02 in
68: semaphore.acquire(); // take a permitpermits=0—
711: System.out.println(no + " out");
12: semaphore.release(); // give it back
permits=12 out
811: System.out.println(no + " out");
12: semaphore.release(); // give it back
permits=21 out
98: semaphore.acquire(); // take a permit
9: System.out.println(no + " in");
permits=04 in ⏎ 5 in
1011: System.out.println(no + " out");
12: semaphore.release(); // give it back
permits=33 out ⏎ 4 out ⏎ 5 out

Five threads are started. The first three each take a permit and enter; in the run in the slides these are 1, 3, and 2. Because no permits are left, 4 and 5 wait in acquire().

permits0 / 31inside2inside3inside4waiting5waiting
Figure 10.25: Step 6. All three permits are in use; 4 and 5 are waiting in acquire().

Two seconds later, those inside leave and release their permits. The waiting threads 4 and 5 take permits and enter, and two seconds later they leave too. In the end, all three permits are back. Never are more than three threads inside at the same time. Which threads enter first and the order of the lines vary: in 12 runs, 12 different outputs were seen. In every run, the first three lines were three in lines, and the fourth entry came only after an exit. The first to enter were not always 1, 2, and 3; in two runs, 4 was also among the first three. Because the output lines are printed outside any lock, an in line sometimes appeared even before the out line of the thread that had released the permit.

new Semaphore(n, true) creates a fair semaphore: permits are handed out in order of waiting. Two properties of the semaphore are surprising. A semaphore does not keep track of who owns the permits; a thread that never acquired a permit can also call release(). And the initial count is not an upper limit: every extra release() increases the number of permits.

Example 10.9

In a single thread, these run: Semaphore s = new Semaphore(2);, s.acquire();, x1 = s.tryAcquire();, x2 = s.tryAcquire();, then s.release(); three times. Then CountDownLatch m = new CountDownLatch(2); and m.countDown(); three times. What are x1, x2, s.availablePermits(), m.getCount(), and m.await(10, TimeUnit.MILLISECONDS)?

The semaphore starts with 2 permits. acquire() takes one: 1 left. tryAcquire() takes the remaining permit and returns true: 0. The second tryAcquire() finds no permit and returns false without waiting; acquire() would have waited forever. Three release() calls raise the permits to 3, above the initial 2. The latch drops to 0 with two countDown() calls; the third has no effect. On an open latch, await returns true without waiting. The program printed true false 3 and 0 true.

10.11Other tools

10.11.1Atomic classes

Using a lock to protect a single counter is like throwing a ball to catch a fly. The java.util.concurrent.atomic package offers lock-free, thread-safe counters.

Definition 10.17

An atomic operation is an operation that completes in a single step, without being split; no other thread can get into the middle of it. Classes such as AtomicInteger, AtomicLong, and AtomicBoolean offer atomic operations on their values.

public class AtomicCounter {
    public static void main(String[] args)
            throws InterruptedException {
        AtomicInteger counter = new AtomicInteger(0);
        Runnable r = () -> {
            for (int i = 0; i < 100_000; i++) {
                counter.incrementAndGet();   // atomic ++counter
            }
        };
        Thread a = new Thread(r), b = new Thread(r);
        a.start(); b.start();
        a.join(); b.join();
        System.out.println("Result: " + counter.get());
        boolean b1 = counter.compareAndSet(200000, 0);
        System.out.println(b1 + " " + counter.get());
        boolean b2 = counter.compareAndSet(5, 10);
        System.out.println(b2 + " " + counter.get());
    }
}
Result: 200000
true 0
false 0

incrementAndGet() is the atomic counterpart of ++x: it increases the value by one and returns the new value. The program was run 10 times and found Result: 200000 every time. Then come two compareAndSet calls. Because the value is 200000, the first one succeeds, writes 0, and returns true. The second expects 5, but the value is 0; it writes nothing and returns false.

Definition 10.18

Compare-and-set (CAS): compareAndSet(expected, new) writes new and returns true if the value is still expected. If the value is different, it leaves it alone and returns false. The comparison and the write are a single atomic operation; the processor does this with one instruction.

Roughly speaking, an atomic object is the combination of a volatile field and an atomic compareAndSet operation. volatile provides visibility, and CAS provides indivisibility.

10.11.2Code trace: compareAndSet

Without a lock, how can incrementAndGet be safe? The following method writes its logic with CAS.

AtomicInteger counter = new AtomicInteger(5);

int inc() {                    // how incrementAndGet works
    while (true) {
        int old = counter.get();
        int next = old + 1;
        if (counter.compareAndSet(old, next))
            return next;
        // failed: someone got in first; retry
    }
}
Table 10.19: Two threads calling inc() at the same time.
StepLineCall stackVariables / state
11: AtomicInteger counter = new AtomicInteger(5);—counter=5
25: int old = counter.get();T1: inc()T1.old=5
35: int old = counter.get();T1: inc() → T2: inc()T1.old=5, T2.old=5
46: int next = old + 1;T1: inc() → T2: inc()T1.next=6, T2.next=6
57: if (counter.compareAndSet(old, next))
8: return next;
T1: inc()counter=6, T1 → 6
67: if (counter.compareAndSet(old, next))T2: inc()counter=6, T2 CAS(5, 6)=false
75: int old = counter.get();T2: inc()T2.old=6
86: int next = old + 1;T2: inc()T2.next=7
97: if (counter.compareAndSet(old, next))
8: return next;
T2: inc()counter=7

In steps 2 and 3, T1 and T2 read the current value; both see 5. Because there is no lock, both carry on. In step 4, both compute 6 locally. With an ordinary counter++, both would write 6 and one increment would be lost.

memorycounter6T1old = –next = –T2old = 5next = 6CAS fails
Figure 10.26: Step 6. The CAS of T1 succeeded and the value is 6. The call compareAndSet(5, 6) of T2 fails: expected 5, value 6.

In step 5, T1 calls compareAndSet(5, 6). Because the value is still 5, 6 is written and true is returned. In step 6, T2 also calls compareAndSet(5, 6). The value is now 6, not the expected 5; nothing is written and false is returned. T2 does not lose its increment; it goes back around the loop: in step 7 it rereads the current value, 6, and computes 7. In step 9 the CAS succeeds this time: counter = 7. Both increments are counted. Nobody waited for a lock; only T2 went around the loop once more.

When this method was called 100,000 times by each of two threads, the counter reached 5 + 200,000 = 200,005; the result was the same in all five runs. The advantage of the lock-free method is that threads never sleep. When contention is low, it is faster than a lock; under very heavy contention, threads spin for nothing.

10.11.3Interruption

The second cooperative way to stop a thread is interruption. t.interrupt() sends an interrupt request to t; it does not stop t by force.

Definition 10.19

An interrupt is a request sent to a thread to "drop what you are doing". interrupt() sets the target's interrupt flag. If the target is waiting in sleep, wait, or join, the wait is cut short immediately and InterruptedException is thrown; at that moment the flag is cleared.

There are two ways to read the flag. Thread.interrupted() is a static method; it reads and clears the flag of the running thread. isInterrupted() is an instance method and only reads the flag.

public class InterruptDemo {
    public static void main(String[] args)
            throws InterruptedException {
        Thread worker = new Thread(() -> {
            try {
                while (!Thread.interrupted()) {
                    // the thread's work
                    System.out.println("working...");
                    Thread.sleep(400);
                }
            } catch (InterruptedException e) {
                System.out.println("Thread cancelled!");
            }
        });
        worker.start();
        Thread.sleep(1000);
        worker.interrupt();   // interrupt it in sleep()
        worker.join();
        System.out.println("main: done");
    }
}
working...
working...
working...
Thread cancelled!
main: done

The worker stays in the loop as long as the flag is not set. In each iteration it prints a line and sleeps for 400 ms. After one second, main calls interrupt().

Table 10.20: Trace of the interrupt program.
StepLineVariables / stateNew output
11: Thread worker = new Thread(() -> {
11: worker.start();
worker=RUNNABLE—
23: while (!Thread.interrupted()) {
4: System.out.println("working...");
5: Thread.sleep(400);
worker=TIMED_WAITINGworking...
312: Thread.sleep(1000);main=TIMED_WAITING—
43: while (!Thread.interrupted()) {
4: System.out.println("working...");
5: Thread.sleep(400);
time=≈400 msworking...
53: while (!Thread.interrupted()) {
4: System.out.println("working...");
5: Thread.sleep(400);
time=≈800 msworking...
613: worker.interrupt(); // worker is in sleep()time=≈1000 ms—
77: } catch (InterruptedException e) {
8: System.out.println("cancelled!");
e=InterruptedExceptioncancelled!
814: worker.join();worker=TERMINATED—
915: System.out.println("main: done");—main: done

The worker prints at 0, about 400, and about 800 ms. Its third sleep would end at 1200 ms. main wakes up at 1000 ms and calls interrupt(). In step 7 the worker is inside sleep; the sleep is cut short immediately, InterruptedException is thrown, and the flag becomes false again.

workermainsleepsleepsleepsleep(1000)04008001000interrupt flag: false
Figure 10.27: Step 7. interrupt() caught the worker inside sleep; the sleep was cut short and the catch ran.

The catch block prints its message, and run() ends. main waits for the worker to finish with join() and prints its last line. The program was run ten times and always printed three working... lines. An interrupt is a request: the thread handles the flag or the exception itself and exits.

Example 10.10

While a thread is in Thread.sleep(5000), main sends it interrupt(). Inside the catch, Thread.currentThread().isInterrupted() is printed. Then main sets its own flag with Thread.currentThread().interrupt() and prints Thread.interrupted() twice. What is the output?

sleep clears the flag when it throws InterruptedException; inside the catch, isInterrupted() is false and interrupted false is printed. The first call of Thread.interrupted() in main reads the set flag and clears it: true. The second reads the cleared flag: false. The program printed interrupted false and true false in all three runs.

Common mistake

Swallowing InterruptedException with an empty catch. When the exception is thrown, the flag has been cleared. If the catch does nothing, the interrupt request is lost and the thread keeps running. The right thing is to leave the loop or to pass the request upward by setting the flag again inside the catch with Thread.currentThread().interrupt().

10.11.4Suspension

In old versions of Java, suspend() froze a thread and resume() continued it. Because suspend() froze the thread together with the locks it held, it was very prone to deadlock; on JDK 21, both methods throw UnsupportedOperationException. The same job is done safely with wait() and notifyAll().

class Task implements Runnable {
    private boolean paused = false;
    public synchronized void pause() {
        paused = true;
    }
    public synchronized void resume() {
        paused = false;
        notifyAll();   // wake the waiter
    }
    public void run() {
        try {
            for (int i = 1; i <= 5; i++) {
                synchronized (this) {
                    while (paused) wait();
                }
                System.out.println("step " + i);
                Thread.sleep(200);
            }
        } catch (InterruptedException e) { }
    }
}

At the start of each step, the task checks the paused flag under the lock. If the flag is raised, it waits with wait(). resume() lowers the flag and wakes the waiting thread with notifyAll(). The flag is protected by the same monitor in both methods; it does not also need to be volatile.

Task g = new Task();
Thread t = new Thread(g);
t.start();
Thread.sleep(500);
g.pause();
System.out.println("main: paused");
Thread.sleep(1000);
System.out.println("main: resume");
g.resume();
t.join();
step 1
step 2
step 3
main: paused
main: resume
step 4
step 5

The task prints a step at 0, 200, and 400 ms. main pauses it at 500 ms. When the task wakes at 600 ms, it sees the flag and waits. For one second, no step is printed. When main resumes it, the remaining two steps are printed. The program was run ten times and always printed these seven lines. The pause takes effect between steps, not in the middle of one; so no object is left half finished.

10.11.5ThreadLocal

The surest remedy for a race is not to share. ThreadLocal gives each thread its own copy of the same variable.

static final ThreadLocal<String> value =
        new ThreadLocal<>();
public static void main(String[] args)
        throws InterruptedException {
    Thread thread1 = new Thread(() -> {
        // first thread
        value.set("Value 1");
        System.out.println("thread1: " + value.get());
    });
    Thread thread2 = new Thread(() -> {
        // second thread
        value.set("Value 2");
        System.out.println("thread2: " + value.get());
    });
    thread1.start();
    thread2.start();
    thread1.join();
    thread2.join();
    System.out.println("main: " + value.get());
thread1: Value 1
thread2: Value 2
main: null

Both threads write to the same value object, but each writes to and reads from its own copy. The copies are independent of each other. Because main never called set, its own copy is empty and it sees null. The order of the first two lines varies: in 40 runs, thread1 printed first 20 times and thread2 20 times. The line main: null was always last.

To give each thread a separate initial value, write ThreadLocal.withInitial(() -> 0) (Java 8+) or override the initialValue() method. A typical use is to give each thread its own copy of an object that is not thread-safe, such as a date formatter.

Example 10.11

ThreadLocal<Integer> t = ThreadLocal.withInitial(() -> 0);, then t.set(5) in main. A new thread x does t.set(t.get() + 1) and prints "x: " + t.get(); main waits for x and prints "main: " + t.get(). What is the output?

The 5 in main does not pass to x. On its first get(), x starts with the 0 from withInitial and makes it 1: x: 1. What x wrote does not affect the copy of main either: main: 5.

10.11.6Thread pools

Starting a new thread for every task creates two problems. Creating a thread is not cheap: a stack is allocated and an operating-system record is made. More importantly, the number grows without control: if a thousand requests arrive, a thousand threads are started.

Definition 10.20

A thread pool is a structure that creates the threads to be used in advance and distributes tasks to them. Tasks are submitted to the pool (submit); an idle worker takes a task and, when finished, moves on to the next one. If there is no idle worker, the task waits in the queue.

submit(task)task queueT1T2T3T4thread pool (2)pool-1-thread-1pool-1-thread-2a thread takes a new task after finishing one
Figure 10.28: Tasks are added to a queue; the two threads in the pool take tasks in turn.

A pool reuses threads and limits their number. In Java, pools are managed through the ExecutorService interface. Executors.newFixedThreadPool(n) gives a ready-made pool with a fixed n workers. When detailed configuration is needed, the ThreadPoolExecutor class, which creates and manages the pool, is used directly.

public class PoolDemo {
    static void task(int no) {
        String name = Thread.currentThread().getName();
        System.out.println("Task " + no + " -> " + name);
    }
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        for (int i = 1; i <= 4; i++) {
            int no = i;
            pool.submit(() -> task(no));
        }
        // Callable: a task that returns a value
        Future<Integer> f = pool.submit(() -> 6 * 7);
        System.out.println("Callable result: " + f.get());
        pool.shutdown();   // accept no new tasks
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("Pool shut down");
    }
}

The first run in the slides is:

Task 1 -> pool-1-thread-1
Task 2 -> pool-1-thread-2
Task 3 -> pool-1-thread-2
Task 4 -> pool-1-thread-2
Callable result: 42
Pool shut down

The four tasks are distributed over the two workers. Which worker gets which task and the order of the lines vary; in a second run, the slides give the last two task lines as Task 3 -> pool-1-thread-1 and Task 4 -> pool-1-thread-2. For these notes, 6 different outputs were seen in 40 runs. Some things do not change: the worker names are always pool-1-thread-1 and pool-1-thread-2; the pool never starts a third thread. The last two lines are always the same, too.

Runnable does not return a value. For tasks that return a value there is the Callable interface; the lambda () -> 6 * 7 is a Callable<Integer>. submit returns a Future immediately. A Future represents a result that will be ready in the future. get() waits until the result is ready.

shutdown() asks the pool to stop accepting new tasks; the tasks in the queue are still completed. awaitTermination waits for all tasks to finish, for at most the given time. If shutdown() is forgotten, the program stays open, because the pool's workers are not daemon threads.

Java 21 introduced a new option: Executors.newVirtualThreadPerTaskExecutor() gives each task its own virtual thread. Virtual threads are managed by the JVM, not by the operating system; millions of them can be started. They are suited to large numbers of short, wait-heavy tasks. In one experiment, isVirtual() and isDaemon() both returned true inside such a task.

10.11.7Code trace: pool and Future

To see how the pool works over time, the tasks imitate long jobs by sleeping. job(ms, d) sleeps for ms milliseconds and returns d.

static int job(int ms, int d) throws Exception {
    Thread.sleep(ms);   // stands in for slow work
    return d;
}
// inside main:
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<Integer> f1 = pool.submit(() -> job(300, 10));
Future<Integer> f2 = pool.submit(() -> job(100, 20));
Future<Integer> f3 = pool.submit(() -> job(100, 30));
System.out.println(f1.isDone() + " " + f3.isDone());
int sum = f1.get() + f2.get() + f3.get();
System.out.println("sum = " + sum);
System.out.println(f2.isDone() + " " + f3.isDone());
pool.shutdown();
Table 10.21: Trace of three tasks in a pool with two workers (times approximate).
StepLineVariables / stateNew output
16: ExecutorService pool = Executors.newFixedThreadPool(2);pool=2 workers—
27: Future<Integer> f1 = pool.submit(() -> job(300, 10));f1=Future (pending)—
38: Future<Integer> f2 = pool.submit(() -> job(100, 20));f2=Future—
49: Future<Integer> f3 = pool.submit(() -> job(100, 30));f3=Future—
510: System.out.println(f1.isDone() + " " + f3.isDone());f1.isDone()=falsefalse false
611: int sum = f1.get() + f2.get() + f3.get();time=≈100 ms—
711: int sum = f1.get() + f2.get() + f3.get();time=≈200 ms—
811: int sum = f1.get() + f2.get() + f3.get();sum=10+20+30=60—
912: System.out.println("sum = " + sum);
13: System.out.println(f2.isDone() + " " + f3.isDone());
sum=60sum = 60 ⏎ true true
1014: pool.shutdown();pool=shutting down—

The pool has two workers. f1 starts on worker 1 and f2 on worker 2. Because both workers are busy, f3 waits in the queue; no new thread is started. In step 5, no task has finished; isDone() returns false without waiting. In step 6, f1.get() stops main until the result is ready. Meanwhile, at about 100 ms, f2 finishes and worker 2 takes f3 from the queue.

queueworker 1worker 2f1f2f30100200300main: waiting in f1.get()done: f2
Figure 10.29: Step 6. main is waiting in f1.get(); f2 is done and worker 2 has taken f3 from the queue.

At about 200 ms, f3 finishes too; main is still waiting for f1. At 300 ms, f1 is ready. Because f2 and f3 have already finished, their get() calls return without waiting: total 10 + 20 + 30 = 60. If the tasks had run one after another in a single thread, it would have taken 300 + 100 + 100 = 500 ms; with the pool the total time is about 300 ms. The program was run ten times; the output was always false false, sum = 60, true true, and the measured time was between 300 and 350 ms every time. Which worker gets which task may vary from run to run.

10.11.8CompletableFuture and concurrent collections

CompletableFuture<Integer> cf = CompletableFuture
    .supplyAsync(() -> 6)
    .thenApply(x -> x * 7)              // 42
    .thenCombine(CompletableFuture
        .supplyAsync(() -> 8), Integer::sum);
System.out.println(cf.get());           // 50

Map<String, Integer> freq =
    new ConcurrentHashMap<>();
String[] w = {"apple", "pear", "apple"};
Arrays.stream(w).parallel()
    .forEach(s -> freq.merge(s, 1, Integer::sum));
System.out.println(freq);  // {apple=2, pear=1}

This code shows two different tools, and in all ten runs it printed 50 and {apple=2, pear=1}.

CompletableFuture
Instead of waiting with get(), it chains operations; each step runs in the background when the previous one finishes. In the code, 6 is produced, multiplied by 7 (42), and added to the 8 produced by a separate task: 50.
ConcurrentHashMap
A thread-safe map. The methods merge and compute are atomic. A parallel stream processes the elements of the array on different threads; merge makes sure that no count is lost.
CopyOnWriteArrayList
Copies the internal array on every write. It suits lists that are read a lot and written rarely.
ForkJoinPool
For divide-and-conquer tasks (RecursiveTask). An idle worker steals work from another worker's queue (work stealing). Parallel streams (parallelStream()) use this pool.

A parallel stream is not always fast. On small data, the cost of coordinating threads exceeds the gain. A parallel stream that writes to a shared mutable variable, on the other hand, corrupts the result. The decision to parallelize is made by measurement.

10.11.9Thread safety

Definition 10.21

A class is thread-safe if it behaves correctly when used from several threads at the same time.

Thread safety is reached in four ways:

Immutable objects
Objects that do not change after they are created (String, classes whose fields are all final, Java 16+ record) can be shared without synchronization. Data that does not change does not race.
Not sharing
Local variables live on each thread's own stack; ThreadLocal also gives each thread a copy.
Synchronization
Every access to shared mutable data is protected by the same lock: synchronized or Lock.
Ready-made structures
AtomicInteger, ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue.

The ordinary classes of the collections framework, ArrayList and HashMap, are not thread-safe. When two threads each added 10,000 elements to the same ArrayList, the size was not 20,000 in any of the ten runs made for these notes; the values found ranged from 10,004 to 14,121. In four runs, one of the threads died with ArrayIndexOutOfBoundsException while the internal array was being grown. These classes are either protected with a lock or replaced by their concurrent counterparts.

10.12Worked problems

Example 10.12 (Problem 1)

What is the output? Is it the same in every run?

Thread t = new Thread(() -> System.out.print("B"));
System.out.print("A");
t.start();
t.join();
System.out.print("C");

ABC, always. A is printed before the thread is started. B is printed in the new thread; join() does not let main move on to C until B has been printed and the thread has finished. In all ten runs, the output was ABC.

Example 10.13 (Problem 2)

What is the output?

Thread t = new Thread(() -> System.out.print("X"));
System.out.print(t.getState() + " ");
t.run();
System.out.print(" " + t.getState());

NEW X NEW. run() is an ordinary call: main prints the X, the thread never starts, and it stays NEW.

Example 10.14 (Problem 3)

Which of the following are possible outputs of the "two threads" example? a) A1 A2 B1 B2 main; b) B1 A1 A2 B2 main; c) A1 main B1 A2 B2; d) A2 A1 B1 B2 main. (Abbreviation: A1 is the line A: step 1.)

a and b. c is impossible, because main prints after both join() calls. d is impossible, because the steps of the same thread keep their order. a was the most frequent order in the measurements made for these notes. The mirror image of b, A1 B1 B2 A2, was also seen twice in the 6,000 trials inside a single JVM.

Example 10.15 (Problem 4)

What is the state of the thread in each case? a) inside sleep(500); b) trying to enter a synchronized block that is held; c) after wait(); d) when run() has ended.

a) TIMED_WAITING; b) BLOCKED; c) WAITING; d) TERMINATED. In c, the thread is in the wait set. Once notify arrives and it is trying to reacquire the lock, it becomes BLOCKED.

Example 10.16 (Problem 5)

Is the following class thread-safe?

class Account {
    private int balance = 0;
    void deposit(int m) { balance += m; }
    int getBalance() { return balance; }
}

No: balance += m is a read–add–write. When two threads each called deposit(1) 100,000 times, the balance was not 200,000 in any of the ten runs; the results ranged from 126,397 to 171,138. The fix: make the methods synchronized, or make the field an AtomicInteger and use addAndGet(m).

Example 10.17 (Problem 6)

Two threads run these blocks. What can happen?

// T1                    // T2
synchronized (a) {       synchronized (b) {
  synchronized (b) { }     synchronized (a) { }
}                        }

Deadlock: if T1 takes a and T2 takes b, each waits forever for the other. Because there is no sleep, the deadlock does not happen in every run; that is what makes it dangerous. When the blocks were run thousands of times each in a loop, the deadlock was seen in all three trials. The fix: both threads take a first and then b.

Example 10.18 (Exercise: two half sums)

The sum of the numbers 1..1000 will be computed with two threads: one adds the first half, the other the second half; main waits for both and prints the total.

Thread left = new Thread(() -> {
    for (int i = 0; i < 500; i++) part[0] += arr[i];
});
Thread right = new Thread(() -> {
    for (int i = 500; i < 1000; i++) part[1] += arr[i];
});
left.start(); right.start();
left.join(); right.join();

Each thread writes to its own slot; because the two threads never write to the same slot, there is no race. Reading after join() is safe. With arr[i] = i + 1, the parts are 125,250 and 375,250; the total is 500,500 = 1000 · 1001 / 2.

Example 10.19 (Exercise: counting even numbers)

The even numbers between 1 and 1000 will be counted in a shared counter by four threads, each taking 250 numbers.

The counter is an AtomicInteger evens. Each thread runs for (int i = start; i < start + 250; i++) if (i % 2 == 0) evens.incrementAndGet();; the start values are 1, 251, 501, and 751. After all the join() calls, the output is Even numbers: 500. If the counter were an ordinary int, the result could come out smaller than 500 because of the race.

Example 10.20 (Exercise: sum of squares)

The squares of the numbers 1..5 will be computed with Callable tasks in a pool of 3 threads and collected from the Futures.

ExecutorService pool = Executors.newFixedThreadPool(3);
List<Future<Long>> results = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
    int n = i;
    results.add(pool.submit(() -> square(n)));
}
long sum = 0;
for (Future<Long> f : results) sum += f.get();
pool.shutdown();
System.out.println("Sum of squares: " + sum);

The helper method is static long square(int n) { return (long) n * n; }. The Futures stay in the list in the order they were submitted; get() waits for the result of each. The output is Sum of squares: 55 (1 + 4 + 9 + 16 + 25).

Example 10.21 (Exercise: a clock)

Write a thread that prints tick every second; after 3.5 seconds, main will stop it with interrupt().

The pattern from the interrupt example is used: while (!Thread.interrupted()) in the loop, and in the body print tick and call sleep(1000); after the catch, print clock stopped. main runs sleep(3500), interrupt(), and join(). The thread prints at seconds 0, 1, 2, and 3; at second 3.5 its sleep is cut short. The output is four tick lines and clock stopped; it was the same in all five runs.

10.13Common mistakes

The following two tables collect the common mistakes from the slides. The compiler messages were verified with JDK 21's javac, and the run-time symptoms by running the programs.

Table 10.22: Mistakes in creating and managing threads.
MistakeSymptomCorrect form
Calling t.run()No new thread; the code runs in order in maint.start()
Calling start() twiceIllegalThreadStateExceptionA new Thread for each run
Thread.sleep(100); on its ownerror: unreported exception InterruptedException; must be caught or declared to be throwntry-catch or throws InterruptedException
The loop variable i inside a lambdaerror: local variables referenced from a lambda expression must be final or effectively finalA copy: int no = i;
Catching an exception that is never thrown: try { while (!Thread.interrupted()) { } } catch (InterruptedException e)error: exception InterruptedException is never thrown in body of corresponding try statementThe body must contain sleep/wait, or the catch must be removed
currentThread() in a class that does not extend Threaderror: cannot find symbolThread.currentThread()
Forgetting join()main reads before the result is ready (e.g., 0)join() before reading the result
Table 10.23: Synchronization mistakes.
MistakeSymptomCorrect form
Calling wait()/notify() outside synchronizedIllegalMonitorStateException: current thread is not ownerInside synchronized on the same object
Waiting for the condition with ifThe condition may be invalid again on wakeup; a queue that overflows or is read while emptywhile (condition) wait();
Writing unlock() outside finallyOn an exception the lock is never released; everyone waits foreverlock(); try { … } finally { unlock(); }
Unlocking a lock that was not acquiredIllegalMonitorStateExceptionOne unlock() for every lock()
counter++ on a volatile counterIncrements are lost (e.g., 163299)AtomicInteger or synchronized
A final volatile fielderror: illegal combination of modifiers: final and volatileUse only one of them
Using stop() or suspend()Java 20+: UnsupportedOperationExceptionA flag, interrupt(), or wait/notify
Swallowing InterruptedException with an empty catchThe interrupt request is lost and the thread does not stopLeave the loop, or call Thread.currentThread().interrupt()
Acquiring locks in different ordersDeadlock: the program freezesEveryone acquires them in the same order

The compiler catches some of these mistakes; the rest appear only at run time, and often only in some runs. Race and deadlock bugs become visible at moments of high load, for example at peak hours on a server. That is why "I tried it and it worked" is not proof for multithreaded code. For every shared variable, it must be clearly known which lock protects it.

10.14Summary

  • A thread is an independently progressing flow of execution inside a process. The threads of one process share the heap and the method area; each has its own stack, PC register, and local variables.
  • Concurrency means that tasks make progress during the same period of time, and it happens even on a single core. Parallelism means that tasks really run at the same instant on different cores.
  • The scheduler decides which thread runs when. The output order of multithreaded programs can therefore vary from run to run.
  • A thread is written by implementing Runnable, by extending Thread, or with a lambda. The work goes into run(); the thread is started with start(). Calling run() directly does not start a new thread.
  • There are six states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. A thread that has finished cannot be restarted.
  • join() waits for a thread to finish and makes what it wrote visible. sleep does not release locks.
  • Daemon threads do not prevent the JVM from exiting; setDaemon(true) is called before start().
  • A thread is stopped cooperatively: with a volatile flag or with interrupt(). stop() has not worked since Java 20.
  • A race condition arises from divisible operations on shared data. counter++ consists of read–add–write steps, and a thread that slips in between makes increments get lost.
  • synchronized provides mutual exclusion by acquiring an object's monitor. An instance method locks this, and a static method locks Class.class. The protection works only if everyone uses the same lock.
  • volatile provides visibility, not atomicity. Happens-before relations (lock, volatile, start, join) determine when what one thread wrote becomes visible to another.
  • Lock is an explicit lock: it offers tryLock, timed and interruptible waiting, fairness, and several Conditions. unlock() always goes in finally. ReentrantLock and synchronized are reentrant.
  • ReadWriteLock lets readers read at the same time and gives the writer exclusive access.
  • Deadlock arises when locks are acquired in different orders. A fixed lock order, timed attempts, and short critical sections prevent it.
  • To wait for a condition, use wait/notifyAll or the await/signal of Condition; check the condition with while. The ready-made ArrayBlockingQueue solves the producer–consumer problem by itself.
  • CountDownLatch counts events, CyclicBarrier makes threads meet, Exchanger swaps data, and Semaphore limits concurrent entry.
  • Atomic classes update safely and without locks using compareAndSet. ThreadLocal gives each thread its own copy.
  • Thread pools reuse threads and limit their number. Callable returns a value, Future.get() waits for the result, and shutdown() must not be forgotten.
  • The ways to thread safety: immutable objects, not sharing, synchronization, and ready-made concurrent structures. ArrayList and HashMap are not thread-safe.

10.15Key terms

  • thread
  • process
  • concurrency / parallelism
  • thread states
  • daemon thread
  • Java Virtual Machine (JVM)
  • functional interface
  • lambda expression
  • race condition
  • synchronization
  • monitor
  • mutual exclusion
  • lock
  • deadlock
  • producer–consumer problem
  • semaphore
  • atomic operation
  • thread pool
  • thread safety
  • immutable
  • context switching
  • scheduler
  • critical section
  • visibility, volatile
  • happens-before
  • reentrant lock
  • livelock / starvation
  • wait set
  • compare-and-set
  • interrupt

10.16Test Yourself

  1. A static method defines int total = 0;, increments total++ 1,000 times in a loop, and prints the result. If two threads named A and B run this method, what does each print? Is there a race?

    Answer

    Both print 1000. total is a local variable and lives on each thread's own stack; the two copies never see each other. A race happens only when the writes go to a shared field (an object field or a static field).

  2. A class has static synchronized void s() { shared++; } and synchronized void o() { shared++; }; shared is a static int. One thread calls s() 100,000 times, and another calls o() 100,000 times on the same object. Is the result always 200,000?

    Answer

    No. s() locks the class's .class object, and o() locks this. Two different locks do not block each other, and shared++ can run in both threads at the same time. In five trials, the result was below 200,000 every time (between 180,586 and 198,518). The fix is for both methods to use the same lock.

  3. On a ReentrantLock k, main calls lock() twice and unlock() once. Then another thread calls k.tryLock(). What does it return? What is k.getHoldCount() in main?

    Answer

    tryLock() returns false; getHoldCount() is 1. The hold count has dropped from 2 to 1, and the lock is still held by main. The lock is released only by the second unlock().

  4. countDown() is called twice on CountDownLatch m = new CountDownLatch(3);. What does m.await(100, TimeUnit.MILLISECONDS) return? What is m.getCount()?

    Answer

    false and 1. Because the counter has not reached 0, the latch does not open; the timed await waits 100 ms and returns false when the time is up. If the untimed await() had been called, the thread would have waited until the third event arrived.

  5. Three tasks are submitted to a pool created with Executors.newFixedThreadPool(1), each printing its own number and the name of its thread. What are the output order and the thread names?

    Answer

    Because the pool has a single worker, the tasks run one after another in queue order: 1, 2, 3. All three run on pool-1-thread-1; the pool starts no new thread. A single-worker pool therefore preserves the order of tasks. In five trials, the output was always the same.

  6. AtomicInteger a = new AtomicInteger(10); is created, then a.compareAndSet(10, 20), a.compareAndSet(10, 30), and a.getAndIncrement() are called. What do the three calls return, and what is the final value of a?

    Answer

    true, false, 20; the final value is 21. The first CAS finds 10 and writes 20. The second expects 10, but the value is 20, so it does not touch it. getAndIncrement() returns the old value (20) first and then increments.

  7. main first calls Thread.currentThread().interrupt(), then runs Thread.sleep(1000) inside a try-catch. Does sleep last a second? What is isInterrupted() inside the catch?

    Answer

    No. If a thread whose interrupt flag is set enters sleep, InterruptedException is thrown immediately. In the experiment, the exception came in under 100 ms. When the exception is thrown, the flag is cleared; isInterrupted() is false.

  8. Three threads acquire three locks as follows: T1 takes a then b; T2 takes b then c; T3 takes c then a. Can deadlock occur? If it can, which rule prevents it?

    Answer

    It can. If all three acquire their first lock, T1 waits for b, T2 for c, and T3 for a. Each lock being waited for is held by the next thread, and the cycle T1 → T2 → T3 → T1 forms. A fixed order is imposed, for example a < b < c, and every thread acquires its locks in that order. T3 then takes a first and c second, and no cycle can form.

  9. In the blocking-queue example, what problem could arise if notify() were written instead of notifyAll()?

    Answer

    Both producers and consumers can be waiting in the same wait set. notify() chooses a single thread arbitrarily. If a consumer, after taking an item, wakes another consumer, that consumer finds the queue empty and waits again. The waiting producer never wakes up, and the program may hang. notifyAll() wakes everyone; the irrelevant threads find the while condition unsatisfied and wait again. If producers and consumers are given separate sets with Condition, signal() is enough.

10.17Further reading

  • Oracle, The Java Tutorials, "Lesson: Concurrency": an official, free treatment of processes and threads, synchronization, liveness problems, guarded blocks, and high-level concurrency objects.
  • B. Goetz et al., Java Concurrency in Practice: the standard book on thread safety, visibility, locks, and pools; its examples are still valid today.
  • J. Bloch, Effective Java (3rd ed.), Chapter 11, Items 78–84: explains, with reasons, how to synchronize access to shared mutable data, why to prefer the ready-made utilities over wait/notify, and how to avoid excessive synchronization.
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Chapter 17, "Threads and Locks": the precise definition of happens-before and of volatile.

10.18References

  1. Oracle, The Java Tutorials: Lesson: Concurrency (Processes and Threads, Synchronization, Liveness, Guarded Blocks, High Level Concurrency Objects).
  2. J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Chapter 17: Threads and Locks.
  3. Oracle, Java SE 21 API Documentation: java.lang.Thread, java.util.concurrent, java.util.concurrent.locks, java.util.concurrent.atomic.
  4. B. Goetz et al., Java Concurrency in Practice, Addison-Wesley, 2006.
  5. P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 23: Concurrency).
  6. C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapter 12: Concurrency).
  7. K. Sierra, B. Bates, and T. Gee, Head First Java, 3rd ed., O'Reilly (the chapters on threads and concurrency).
  8. J. Bloch, Effective Java, 3rd ed., Addison-Wesley (Chapter 11: Concurrency, Items 78–84).

Related pages: Chapter 10 slides · Study questions · Thread Race simulator · Glossary · © Sercan Külcü. All rights reserved.