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
Runnableor extendingThread, and start it withstart(). - 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/notifyandCondition; 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.
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.
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.
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.
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
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 | Thread | |
|---|---|---|
| Memory | Its own address space | Shares the process's heap |
| Stack | — | Each has its own |
| Creation | Expensive | Cheap (lightweight process) |
| Communication | Files, sockets, pipes | Shared objects |
| Risk | Cannot corrupt each other | Can 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.
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.
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.
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.
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.
| Method | Purpose |
|---|---|
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 prefixThread-. 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 usedgetId(). - 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) andMAX_PRIORITY(10); the default isNORM_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 : RUNNABLEThread.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().
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.
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=trueThis 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=disabledoption, the finalizer thread never starts. Usetry-finallyor try-with-resources withAutoCloseableinstead.
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.
| State | Meaning | How it is entered |
|---|---|---|
NEW | The object has been created but not yet started | new Thread(…); exit: start() |
RUNNABLE | Running, or waiting for its turn on the processor | After start() |
BLOCKED | Waiting for a monitor lock to enter a synchronized block or method | While another thread holds the lock |
WAITING | Waiting indefinitely; another thread must wake it | Object.wait(), Thread.join(), LockSupport.park() |
TIMED_WAITING | Waiting for a limited time | Thread.sleep(ms), wait(ms), join(ms), parkNanos, parkUntil |
TERMINATED | Has completed execution | When 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
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());
}| Step | Line | Variables / state | New output |
|---|---|---|---|
| 1 | 2: Thread sleeper = new Thread(() -> pause(1000)); | — | — |
| 2 | 3: System.out.println("1) " + sleeper.getState()); | — | 1) NEW |
| 3 | 4: sleeper.start(); | — | — |
| 4 | 5: pause(100); | — | — |
| 5 | 6: System.out.println("2) " + sleeper.getState()); | — | 2) TIMED_WAITING |
| 6 | 8: waiter.start(); | — | — |
| 7 | 10: System.out.println("3) " + waiter.getState()); | — | 3) WAITING |
| 8 | 15: blocked.start(); | — | — |
| 9 | 17: System.out.println("4) " + blocked.getState()); | — | 4) BLOCKED |
| 10 | 19: waitFor(waiter); | — | — |
| 11 | 20: 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.
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-0main 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.
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.
| Step | Line | Variables / state | New output |
|---|---|---|---|
| 1 | 9: Worker w = new Worker(); | w=Worker object, t=… | — |
| 2 | 10: Thread t = new Thread(w); | w=Worker object, t=Thread-0 (NEW) | — |
| 3 | 11: t.start(); | w=Worker object, t=Thread-0 (RUNNABLE) | — |
| 4 | 12: System.out.println("main goes on"); | w=Worker object, t=Thread-0 (RUNNABLE) | main goes on |
| 5 | 13: } | t=Thread-0 (RUNNABLE) | — |
| 6 | 4: String name = Thread.currentThread().getName(); | t=Thread-0 (RUNNABLE), name="Thread-0" | — |
| 7 | 5: System.out.println("Worker running: " + name); | t=Thread-0 (RUNNABLE), name="Thread-0" | Worker running: Thread-0 |
| 8 | 6: } | 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.
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-0In 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-0The 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.
| Call | What 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 time | IllegalThreadStateException: 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.
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.
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-0Worker 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) LambdaBecause 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.
| Way | When to use it |
|---|---|
implements Runnable | When the class already extends another class; keeps the work and the thread separate |
extends Thread | Short, 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");
}
}| Step | Line | Call stack | Variables / state | New output |
|---|---|---|---|---|
| 1 | 12: a.start(); | main() | a=RUNNABLE, b=NEW | — |
| 2 | 13: b.start(); | main() | a=RUNNABLE, b=RUNNABLE | — |
| 3 | 14: a.join(); | main() | a=RUNNABLE, b=RUNNABLE, main=WAITING | — |
| 4 | 5: System.out.println(name + ": step " + i); | A: run() → task() | A.i=1, B.i=—, main=WAITING | A: step 1 |
| 5 | 5: System.out.println(name + ": step " + i); | B: run() → task() | A.i=1, B.i=1, main=WAITING | B: step 1 |
| 6 | 5: System.out.println(name + ": step " + i); | A: run() → task() | A.i=2, B.i=1, main=WAITING | A: step 2 |
| 7 | 5: System.out.println(name + ": step " + i); | B: run() → task() | A.i=2, B.i=2, main=WAITING | B: step 2 |
| 8 | 16: System.out.println("main: done"); | main() | A=TERMINATED, B=TERMINATED, main=RUNNABLE | main: 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.
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: doneWhen 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.
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_WAITINGstate. 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 mostmsmilliseconds; 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 : 500000500000Right 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.
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
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 exitingclock 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 supportedOn 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 stoppedfinish() 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: doneThe 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.
If several threads access shared, changing data, the access must be synchronized. Otherwise the result depends on the order in which the threads run.
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) writeIf 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.
| Step | Line | Call stack | Variables / state |
|---|---|---|---|
| 1 | 1: // counter++ is three CPU steps: | — | counter=0, t1.reg=—, t2.reg=— |
| 2 | 2: int reg = counter; // 1) read | t1 | counter=0, t1.reg=0, t2.reg=— |
| 3 | 2: int reg = counter; // 1) read | t2 | counter=0, t1.reg=0, t2.reg=0 |
| 4 | 3: reg = reg + 1; // 2) add 1 | t1 | counter=0, t1.reg=1, t2.reg=0 |
| 5 | 4: counter = reg; // 3) write | t1 | counter=1, t1.reg=1, t2.reg=0 |
| 6 | 3: reg = reg + 1; // 2) add 1 | t2 | counter=1, t1.reg=1, t2.reg=1 |
| 7 | 4: counter = reg; // 3) write | t2 | counter=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.
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.
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.Lockobjects (ReentrantLock,ReadWriteLock): explicit locking.- Barrier, semaphore, exchanger, countdown latch:
CyclicBarrier,Semaphore,Exchanger,CountDownLatch. volatilevariables: 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
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.
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
}t1andt2reach the linesynchronized (o)at the same time; the monitor is free.t1wins and acquires the monitor.t2waits in the entry set,BLOCKED.t1leaves the block; the monitor is released automatically. The waiting threads compete.t2acquires the monitor and enters the critical section.t2leaves too.shared++has been done twice, without interleaving.
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
thisobject is locked. staticmethod: since there is no instance, the monitor of the class'sC.classobject 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.
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: 200000increment() 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 fullAfter 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.
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.
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? trueThe 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? falseIn 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 errorThe two keywords solve the same problem in different ways. Table 10.10 summarizes the difference.
final | volatile |
|---|---|
| Assigned once (in the constructor); never changes afterward | The value can change |
When the constructor finishes (if this was not leaked from the constructor), everyone sees the same value | Every 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.
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.
| Rule | A happens-before B |
|---|---|
| Lock | Releasing a monitor or lock → a later acquisition of the same lock |
volatile | Writing a volatile field → a later read of the same field |
| Start | Everything before the call t.start() → the actions inside t |
| Termination | All actions of t → the thread that returns from t.join() |
| Ready-made structures | BlockingQueue.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.
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: 200000The 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 hereIn 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.
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 acquiredException 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: acquiredOn 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.
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? truenew 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: ");
}
}| Step | Line | Call stack | Variables / state | New output |
|---|---|---|---|---|
| 1 | 20: outer(); | main() | owner=none, count=0 | — |
| 2 | 10: lock.lock(); | main() → outer() | owner=main, count=1 | — |
| 3 | 11: try { show("outer(): "); inner(); } | main() → outer() → show() | owner=main, count=1 | outer(): 1 |
| 4 | 15: lock.lock(); // enters without waiting | main() → outer() → inner() | owner=main, count=2 | — |
| 5 | 16: try { show("inner(): "); } | main() → outer() → inner() → show() | owner=main, count=2 | inner(): 2 |
| 6 | 17: finally { lock.unlock(); } | main() → outer() → inner() | owner=main, count=1 | — |
| 7 | 12: finally { lock.unlock(); } | main() → outer() | owner=none, count=0 | — |
| 8 | 21: show("main: "); | main() → show() | owner=none, count=0 | main: 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.
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.
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: enTwo 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
Explicit: Lock | Intrinsic: synchronized | |
|---|---|---|
| Control | The programmer calls lock()/unlock() | Automatic: acquired on entering the block, released on leaving it |
| Classes | The Lock interface, ReentrantLock, ReentrantReadWriteLock | A keyword; the monitor of every object |
| Trying without waiting | tryLock(), tryLock(time) | None: waits until the lock is free |
| Interruptible waiting | lockInterruptibly() | None |
| Fairness, conditions | new ReentrantLock(true), several Conditions | None; a single wait set |
| Reentrancy | ReentrantLock is reentrant | Always reentrant |
| Risk | If unlock() is forgotten, the lock stays held forever | No risk of forgetting |
| When to use | When advanced control is needed | Simple 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
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);
}a and waits for b; T2 holds b and waits for a.BLOCKED BLOCKED
Deadlocked: 2useBoth(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();
}| Step | Line | Call stack | Variables / state |
|---|---|---|---|
| 1 | 1: static final Object a = new Object(), b = new Object();10: public static void main(String[] args) { | main() | a=Object, b=Object |
| 2 | 11: new Thread(() -> useBoth(a, b, "T1")).start();3: synchronized (x) { | T1: useBoth(a, b) | T1: x=a, y=b |
| 3 | 12: new Thread(() -> useBoth(b, a, "T2")).start();3: synchronized (x) { | T2: useBoth(b, a) | T2: x=b, y=a |
| 4 | 4: pause(100); | T1: pause(100) → T2: pause(100) | a=held by T1, b=held by T2 |
| 5 | 5: synchronized (y) { | T1: useBoth(a, b) | T1 wants=b |
| 6 | 5: synchronized (y) { | T1: useBoth(a, b) → T2: useBoth(b, a) | T2 wants=a |
| 7 | 6: System.out.println(name + " done"); | T1: useBoth(a, b) → T2: useBoth(b, a) | T1=BLOCKED, T2=BLOCKED |
| 8 | 12: 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.
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: 0Everyone 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
jstacktool orThreadMXBean.findDeadlockedThreads()shows the deadlocked threads and the locks they hold.
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.
- 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
tryLockfails, 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.
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:
Object.wait()andObject.notify()/notifyAll().- The
Conditioninterface, used together withLock. - Synchronizer objects (
CountDownLatch,Semaphore, …) and the ready-madeBlockingQueueclasses.
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.
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, andnotifyAll()wakes all of them. The formwait(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.
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;
}| Step | Line | Variables / state |
|---|---|---|
| 1 | 6: data[tail] = item;7: tail = (tail + 1) % data.length;8: count++; | head=0, tail=1, count=1 |
| 2 | 6: data[tail] = item;7: tail = (tail + 1) % data.length;8: count++; | head=0, tail=0, count=2 |
| 3 | 4: wait(); | head=0, tail=0, count=2 |
| 4 | 16: Object item = data[head];17: data[head] = null;18: head = (head + 1) % data.length;19: count--; | head=1, tail=0, count=1 |
| 5 | 20: notifyAll(); | head=1, tail=0, count=1 |
| 6 | 3: while (count == data.length) {6: data[tail] = item;7: tail = (tail + 1) % data.length;8: count++; | head=1, tail=1, count=2 |
| 7 | 16: Object item = data[head];17: data[head] = null;18: head = (head + 1) % data.length;19: count--; | head=0, tail=1, count=1 |
| 8 | 16: Object item = data[head];17: data[head] = null;18: head = (head + 1) % data.length;19: count--; | head=1, tail=1, count=0 |
| 9 | 14: 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.
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: 0In 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: 4In 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.
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.
| Way | Waiting | Waking |
|---|---|---|
synchronized | wait() | notify(), notifyAll() |
Lock + Condition | await() | signal(), signalAll() |
ArrayBlockingQueue | inside put(), take() | automatic |
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.
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.
| Step | Line | Variables / state | New output |
|---|---|---|---|
| 1 | 4: CountDownLatch latch = new CountDownLatch(count); | counter=3 | — |
| 2 | 11: }).start(); | counter=3 | — |
| 3 | 14: latch.await(); | counter=3 | — |
| 4 | 8: System.out.println(no + ": event happened");10: latch.countDown(); | counter=2 | 1: event happened |
| 5 | 8: System.out.println(no + ": event happened");10: latch.countDown(); | counter=1 | 3: event happened |
| 6 | 8: System.out.println(no + ": event happened");10: latch.countDown(); | counter=0 | 2: event happened |
| 7 | 15: System.out.println("All events done!"); | counter=0 | All 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.
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 · 3The 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 continuingEach 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 1exchange(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
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();
}
}| Step | Line | Variables / state | New output |
|---|---|---|---|
| 1 | 3: Semaphore semaphore = new Semaphore(permits); | permits=3 | — |
| 2 | 16: }).start(); | permits=3 | — |
| 3 | 8: semaphore.acquire(); // take a permit9: System.out.println(no + " in"); | permits=2 | 1 in |
| 4 | 8: semaphore.acquire(); // take a permit9: System.out.println(no + " in"); | permits=1 | 3 in |
| 5 | 8: semaphore.acquire(); // take a permit9: System.out.println(no + " in"); | permits=0 | 2 in |
| 6 | 8: semaphore.acquire(); // take a permit | permits=0 | — |
| 7 | 11: System.out.println(no + " out");12: semaphore.release(); // give it back | permits=1 | 2 out |
| 8 | 11: System.out.println(no + " out");12: semaphore.release(); // give it back | permits=2 | 1 out |
| 9 | 8: semaphore.acquire(); // take a permit9: System.out.println(no + " in"); | permits=0 | 4 in ⏎ 5 in |
| 10 | 11: System.out.println(no + " out");12: semaphore.release(); // give it back | permits=3 | 3 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().
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.
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.
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 0incrementAndGet() 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.
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
}
}| Step | Line | Call stack | Variables / state |
|---|---|---|---|
| 1 | 1: AtomicInteger counter = new AtomicInteger(5); | — | counter=5 |
| 2 | 5: int old = counter.get(); | T1: inc() | T1.old=5 |
| 3 | 5: int old = counter.get(); | T1: inc() → T2: inc() | T1.old=5, T2.old=5 |
| 4 | 6: int next = old + 1; | T1: inc() → T2: inc() | T1.next=6, T2.next=6 |
| 5 | 7: if (counter.compareAndSet(old, next))8: return next; | T1: inc() | counter=6, T1 → 6 |
| 6 | 7: if (counter.compareAndSet(old, next)) | T2: inc() | counter=6, T2 CAS(5, 6)=false |
| 7 | 5: int old = counter.get(); | T2: inc() | T2.old=6 |
| 8 | 6: int next = old + 1; | T2: inc() | T2.next=7 |
| 9 | 7: 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.
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.
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: doneThe 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().
| Step | Line | Variables / state | New output |
|---|---|---|---|
| 1 | 1: Thread worker = new Thread(() -> {11: worker.start(); | worker=RUNNABLE | — |
| 2 | 3: while (!Thread.interrupted()) {4: System.out.println("working...");5: Thread.sleep(400); | worker=TIMED_WAITING | working... |
| 3 | 12: Thread.sleep(1000); | main=TIMED_WAITING | — |
| 4 | 3: while (!Thread.interrupted()) {4: System.out.println("working...");5: Thread.sleep(400); | time=≈400 ms | working... |
| 5 | 3: while (!Thread.interrupted()) {4: System.out.println("working...");5: Thread.sleep(400); | time=≈800 ms | working... |
| 6 | 13: worker.interrupt(); // worker is in sleep() | time=≈1000 ms | — |
| 7 | 7: } catch (InterruptedException e) {8: System.out.println("cancelled!"); | e=InterruptedException | cancelled! |
| 8 | 14: worker.join(); | worker=TERMINATED | — |
| 9 | 15: 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.
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.
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.
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 5The 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: nullBoth 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.
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.
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.
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 downThe 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();| Step | Line | Variables / state | New output |
|---|---|---|---|
| 1 | 6: ExecutorService pool = Executors.newFixedThreadPool(2); | pool=2 workers | — |
| 2 | 7: Future<Integer> f1 = pool.submit(() -> job(300, 10)); | f1=Future (pending) | — |
| 3 | 8: Future<Integer> f2 = pool.submit(() -> job(100, 20)); | f2=Future | — |
| 4 | 9: Future<Integer> f3 = pool.submit(() -> job(100, 30)); | f3=Future | — |
| 5 | 10: System.out.println(f1.isDone() + " " + f3.isDone()); | f1.isDone()=false | false false |
| 6 | 11: int sum = f1.get() + f2.get() + f3.get(); | time=≈100 ms | — |
| 7 | 11: int sum = f1.get() + f2.get() + f3.get(); | time=≈200 ms | — |
| 8 | 11: int sum = f1.get() + f2.get() + f3.get(); | sum=10+20+30=60 | — |
| 9 | 12: System.out.println("sum = " + sum);13: System.out.println(f2.isDone() + " " + f3.isDone()); | sum=60 | sum = 60 ⏎ true true |
| 10 | 14: 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.
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
mergeandcomputeare atomic. A parallel stream processes the elements of the array on different threads;mergemakes 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
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 allfinal, 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;
ThreadLocalalso gives each thread a copy. - Synchronization
- Every access to shared mutable data is protected by the same lock:
synchronizedorLock. - 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
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.
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.
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.
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.
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).
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.
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.
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.
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).
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.
| Mistake | Symptom | Correct form |
|---|---|---|
Calling t.run() | No new thread; the code runs in order in main | t.start() |
Calling start() twice | IllegalThreadStateException | A new Thread for each run |
Thread.sleep(100); on its own | error: unreported exception InterruptedException; must be caught or declared to be thrown | try-catch or throws InterruptedException |
The loop variable i inside a lambda | error: local variables referenced from a lambda expression must be final or effectively final | A 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 statement | The body must contain sleep/wait, or the catch must be removed |
currentThread() in a class that does not extend Thread | error: cannot find symbol | Thread.currentThread() |
Forgetting join() | main reads before the result is ready (e.g., 0) | join() before reading the result |
| Mistake | Symptom | Correct form |
|---|---|---|
Calling wait()/notify() outside synchronized | IllegalMonitorStateException: current thread is not owner | Inside synchronized on the same object |
Waiting for the condition with if | The condition may be invalid again on wakeup; a queue that overflows or is read while empty | while (condition) wait(); |
Writing unlock() outside finally | On an exception the lock is never released; everyone waits forever | lock(); try { … } finally { unlock(); } |
| Unlocking a lock that was not acquired | IllegalMonitorStateException | One unlock() for every lock() |
counter++ on a volatile counter | Increments are lost (e.g., 163299) | AtomicInteger or synchronized |
A final volatile field | error: illegal combination of modifiers: final and volatile | Use only one of them |
Using stop() or suspend() | Java 20+: UnsupportedOperationException | A flag, interrupt(), or wait/notify |
Swallowing InterruptedException with an empty catch | The interrupt request is lost and the thread does not stop | Leave the loop, or call Thread.currentThread().interrupt() |
| Acquiring locks in different orders | Deadlock: the program freezes | Everyone 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 extendingThread, or with a lambda. The work goes intorun(); the thread is started withstart(). Callingrun()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.sleepdoes not release locks.- Daemon threads do not prevent the JVM from exiting;
setDaemon(true)is called beforestart(). - A thread is stopped cooperatively: with a
volatileflag or withinterrupt().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. synchronizedprovides mutual exclusion by acquiring an object's monitor. An instance method locksthis, and astaticmethod locksClass.class. The protection works only if everyone uses the same lock.volatileprovides visibility, not atomicity. Happens-before relations (lock,volatile,start,join) determine when what one thread wrote becomes visible to another.Lockis an explicit lock: it offerstryLock, timed and interruptible waiting, fairness, and severalConditions.unlock()always goes infinally.ReentrantLockandsynchronizedare reentrant.ReadWriteLocklets 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/notifyAllor theawait/signalofCondition; check the condition withwhile. The ready-madeArrayBlockingQueuesolves the producer–consumer problem by itself. CountDownLatchcounts events,CyclicBarriermakes threads meet,Exchangerswaps data, andSemaphorelimits concurrent entry.- Atomic classes update safely and without locks using
compareAndSet.ThreadLocalgives each thread its own copy. - Thread pools reuse threads and limit their number.
Callablereturns a value,Future.get()waits for the result, andshutdown()must not be forgotten. - The ways to thread safety: immutable objects, not sharing, synchronization, and ready-made concurrent structures.
ArrayListandHashMapare 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
A
staticmethod definesint total = 0;, incrementstotal++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.
totalis 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 astaticfield).A class has
static synchronized void s() { shared++; }andsynchronized void o() { shared++; };sharedis astatic int. One thread callss()100,000 times, and another callso()100,000 times on the same object. Is the result always 200,000?Answer
No.
s()locks the class's.classobject, ando()locksthis. Two different locks do not block each other, andshared++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.On a
ReentrantLock k,maincallslock()twice andunlock()once. Then another thread callsk.tryLock(). What does it return? What isk.getHoldCount()inmain?Answer
tryLock()returnsfalse;getHoldCount()is 1. The hold count has dropped from 2 to 1, and the lock is still held bymain. The lock is released only by the secondunlock().countDown()is called twice onCountDownLatch m = new CountDownLatch(3);. What doesm.await(100, TimeUnit.MILLISECONDS)return? What ism.getCount()?Answer
falseand 1. Because the counter has not reached 0, the latch does not open; the timedawaitwaits 100 ms and returnsfalsewhen the time is up. If the untimedawait()had been called, the thread would have waited until the third event arrived.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.AtomicInteger a = new AtomicInteger(10);is created, thena.compareAndSet(10, 20),a.compareAndSet(10, 30), anda.getAndIncrement()are called. What do the three calls return, and what is the final value ofa?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.mainfirst callsThread.currentThread().interrupt(), then runsThread.sleep(1000)inside atry-catch. Doessleeplast a second? What isisInterrupted()inside thecatch?Answer
No. If a thread whose interrupt flag is set enters
sleep,InterruptedExceptionis thrown immediately. In the experiment, the exception came in under 100 ms. When the exception is thrown, the flag is cleared;isInterrupted()isfalse.Three threads acquire three locks as follows: T1 takes
athenb; T2 takesbthenc; T3 takescthena. 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 forc, and T3 fora. 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 examplea<b<c, and every thread acquires its locks in that order. T3 then takesafirst andcsecond, and no cycle can form.In the blocking-queue example, what problem could arise if
notify()were written instead ofnotifyAll()?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 thewhilecondition unsatisfied and wait again. If producers and consumers are given separate sets withCondition,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
- Oracle, The Java Tutorials: Lesson: Concurrency (Processes and Threads, Synchronization, Liveness, Guarded Blocks, High Level Concurrency Objects).
- J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Chapter 17: Threads and Locks.
- Oracle, Java SE 21 API Documentation:
java.lang.Thread,java.util.concurrent,java.util.concurrent.locks,java.util.concurrent.atomic. - B. Goetz et al., Java Concurrency in Practice, Addison-Wesley, 2006.
- P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 23: Concurrency).
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapter 12: Concurrency).
- K. Sierra, B. Bates, and T. Gee, Head First Java, 3rd ed., O'Reilly (the chapters on threads and concurrency).
- 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.