Chapter 10: Threads

Object Oriented Programming with Java
Threads and processesThread and RunnableLife cyclesleep · join · daemon StoppingRace conditionssynchronizedvolatileLockDeadlock wait · notify · ConditionSynchronizersAtomic classesThreadLocalThread pools
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Concepts

Explain the difference between a thread and a process, and between concurrency and parallelism.

Creation

Create and start threads by implementing Runnable or extending Thread; explain why start(), not run().

Life cycle

Know the six states and trace the transitions caused by sleep, join, wait and lock waits.

Synchronization

Recognize race conditions; fix them with synchronized, volatile, Lock and atomic classes.

Waiting on conditions

Write a producer–consumer with wait/notify and Condition; prevent deadlock.

Ready-made tools

Use CountDownLatch, CyclicBarrier, Exchanger, Semaphore and thread pools.

Basic Concepts

Threads

  • A thread is the basic unit of execution in a Java program: an independent flow that runs instructions in order.
  • Each thread is represented by an object of the Thread class.
  • Threads are used for multithreading and concurrent programming.
  • Every Java program starts with at least one thread: the main thread, which runs main().
process (JVM)heap: objects (shared)mainown stack, PCT1own stack, PCT2own stack, PC
Analogy: a beehive

Each bee does its own job (a thread), but they all share the same hive and honeycomb (shared memory). If two bees try to fill the same cell at once, trouble follows: this chapter is about managing those “collisions”.

Why?

Do background work without freezing the GUI, use a multicore CPU, keep working while waiting for the network or a file.

Basic Concepts

Concurrency and Parallelism

One coreconcurrencyABABABABABTwo coresparallelismC1AC2Btime
Concurrency

Several tasks make progress in the same time span. Possible even on one core: the OS runs threads in tiny alternating slices, so they seem to run at once.

Parallelism

Tasks run truly at the same time on different cores. Requires more than one core; speeds up computation.

The scheduler of the JVM and the OS decides which thread runs when and on which core; the programmer cannot know this order.

Basic Concepts

Processes and Threads

Process: a running JVMHeap: objects and arraysSHARED by all threadsmainStacklocal variablesPC: next instructionThread-0Stacklocal variablesPC: next instruction
ProcessThread
MemoryOwn address spaceShares the process heap
Stack—Each has its own
CreationExpensiveCheap (lightweight process)
CommunicationFiles, sockets, pipesShared objects
RiskCan't corrupt each otherCan corrupt shared data
A running Java program is a process with many threads inside. Objects live on the heap, so two threads can reach the same object; local variables live on each thread's own stack and are not shared.

Basic Concepts

Context Switching

  • With more threads than cores, the OS runs them in turn using time slices.
  • On each switch the running thread's state (program counter, registers, stack pointer) is saved and the next one's is loaded: this is a context switch.
one core:T1T2T3T1T2▲ context switch: save registers, load the other'sEach switch takes time; with far more threads than cores, the cost adds up.
Cost

Each switch takes a few microseconds and invalidates part of the cache. Starting thousands of threads can slow the program down.

Rule of thumb

For CPU-bound work, threads ≈ cores (Runtime.getRuntime().availableProcessors()). For I/O-bound work (network, files) more can help; use a pool for that.

Basic Concepts

The Java Virtual Machine (JVM)

The JVM is a virtual environment that manages threads as independent units of execution.

Class LoaderJVM memory areasMethod areaHeapobjectsStackPC registerNative methodstackExecution Engine(interpreter, JIT, GC)Native Method Interface(JNI)NativelibrariesShared by all threadsOne per thread

When a thread is created, the JVM gives it its own stack, PC register and native method stack; the method area and the heap exist once.

The Thread Class

The Thread Class

  • Every thread is an object of the Thread class in java.lang (no import needed).
  • Thread manages the thread's life cycle and provides the needed methods and properties.
  • One approach: write a subclass of Thread.
  • Override run() to define the thread's main logic.
  • Call start() to start the thread.
MethodPurpose
start()Starts a new thread, which runs run()
run()The work the thread does
sleep(ms)static: puts the current thread to sleep for a while
join()Waits for that thread to finish
yield()static: temporarily gives way to others
interrupt()Sends an interrupt request
currentThread()static: the thread running right now
getName(), getState(), isAlive()Read information

The Thread Class

Basic Attributes of a Thread (1)

Runnable

The object with the run() method, where the thread's main logic lives.

Name

The thread's name: main, Thread-0… Used in logs and for diagnosis. getName(), setName()

ID

A unique identifier, assigned automatically when the thread is created. threadId()

ThreadGroup

The group the thread belongs to; used to organize and manage threads.

Daemon

Serves other threads and runs periodic chores; the JVM does not wait for it when shutting down.

ContextClassLoader

The context class loader: the loader the thread uses to load classes dynamically.

These attributes are fields of the Thread object, with get/set methods to read and write them.

The Thread Class

Basic Attributes of a Thread (2)

Priority

An integer from MIN_PRIORITY (1) to MAX_PRIORITY (10); default NORM_PRIORITY (5).

State

The current state: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED.

Interrupted

A flag showing whether an interrupt was requested; set by interrupt().

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());
Output
Name    : main
ID      : 1
Priority: 5
Group   : main
Daemon  : false
State   : RUNNABLE

This snippet is inside main. Thread.currentThread() returns the thread running that line: here, the main thread.

The Thread Class

Two Thread Groups at JVM Startup

system groupReference HandlerFinalizerSignal DispatcherAttach Listener …main groupmainThread-0, Thread-1 …userthe JVM's daemon threads
Main thread group

Created at JVM startup; the main thread and the threads we create belong here by default.

System thread group

The JVM's own threads: reference handling, the Finalizer, the Signal Dispatcher…

Let's list every thread

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

The Thread Class

Notable Threads at JVM Startup (HotSpot)

Main Thread

The first thread to run when the JVM starts. main() runs here, and with it the core application logic.

Garbage Collector

Responsible for memory management: finds and frees objects with no references left, automatically. In HotSpot these are internal JVM threads that don't show up in the list.

Signal Dispatcher

Handles signals from the OS; for example, on a Ctrl+C shutdown request it starts an orderly JVM shutdown.

Finalizer

Calls objects' finalize() methods. finalize() was deprecated for removal in Java 18 (JEP 421); with --finalization=disabled it never starts. Use try-with-resources instead.

Life Cycle

Thread States

Threads pass through different states over their life cycle; getState() returns the state as a Thread.State constant.

StateMeaningHow you get there
NEWObject created, not started yetnew Thread(…); leaves on start()
RUNNABLERunning or waiting for a CPUAfter start()
BLOCKEDWaiting for a monitor lock to enter a synchronized block/methodWhile another thread holds the lock
WAITINGWaiting indefinitely; another thread must wake itObject.wait(), Thread.join(), LockSupport.park()
TIMED_WAITINGWaiting with a timeoutThread.sleep(ms), wait(ms), join(ms), parkNanos, parkUntil
TERMINATEDFinished executingWhen run() ends

Java has no separate “RUNNING” state; running threads and threads waiting for a CPU are both RUNNABLE.

Life Cycle

State Diagram

NEWRUNNABLETERMINATEDBLOCKEDWAITINGTIMED_WAITINGstart()run() endswaits for synchronized lock⇄ gets the lockwait(), join()⇄ notify(), task endssleep(ms), wait(ms)⇄ time is up
One way

NEW → RUNNABLE → TERMINATED. A finished thread cannot be restarted.

Waiting states

Each of the three waiting states returns to RUNNABLE.

The difference

BLOCKED: for a lock; WAITING: for an event; TIMED_WAITING: with a time limit.

Life Cycle · Step-by-step trace

Observing the States, Step by Step

mainRUNNABLEsleeperNEWwaiternot yetblockednot yet

sleeper is created but not started: NEW.

mainRUNNABLEsleeperNEWwaiternot yetblockednot yet

The state is printed.

mainRUNNABLEsleeperRUNNABLEwaiternot yetblockednot yet

start(): the new thread is ready to run.

mainTIMED_WAITINGsleeperTIMED_WAITINGwaiternot yetblockednot yet

Both are in sleep: main for 100 ms, sleeper for 1000 ms.

mainRUNNABLEsleeperTIMED_WAITINGwaiternot yetblockednot yet

main woke up; sleeper is still asleep: TIMED_WAITING.

mainRUNNABLEsleeperTIMED_WAITINGwaiterWAITINGblockednot yet

waiter calls sleeper.join(): it waits indefinitely, WAITING.

mainRUNNABLEsleeperTIMED_WAITINGwaiterWAITINGblockednot yet

After 100 ms the state is printed.

mainRUNNABLEsleeperTIMED_WAITINGwaiterWAITINGblockedBLOCKED

main holds lock; blocked wants the same lock: BLOCKED.

mainRUNNABLEsleeperTIMED_WAITINGwaiterWAITINGblockedBLOCKED

main still holds the lock; the state is printed.

mainWAITINGsleeperTERMINATEDwaiterTERMINATEDblockedTERMINATED

When the block ends the lock is released, and blocked enters and finishes. main waits for waiter; sleeper ends after its 1 s, then waiter ends too.

mainRUNNABLEsleeperTERMINATEDwaiterTERMINATEDblockedTERMINATED

A thread whose run() has ended: TERMINATED.

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());
}

pause(ms) and waitFor(t) are helpers that wrap Thread.sleep and t.join() in try-catch. The pauses make the output always come out like this.

Creating and Starting

The Runnable Interface

  • Every thread has a Runnable object that it runs.
  • The Runnable interface has just one method, run().
  • A class that implements it defines run(): the thread's work.
  • Since it is a functional interface (a single abstract method), Java 8+ also lets you write a lambda.

Definition in the JDK

package java.lang;

public interface Runnable {
    void run();
}

An implementing class

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

Java 8+: a lambda

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

Creating and Starting

Starting a Thread

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 Runnable object is passed to the Thread constructor.
  • Calling start() starts the thread.
  • Don't call run() directly: the code would then run on the caller's thread.
Output (a real run)
main goes on
Worker running: Thread-0

The order of the lines may change from run to run: main carries on as soon as start() returns; the scheduler decides when the new thread runs.

Creating and Starting · One possible order

start(): Two Stacks, Two Flows

mainmain()RUNNABLEThread-0no stack

main is running; a Worker object is created on the heap. There is still only one thread.

mainmain()RUNNABLEThread-0no stackNEW

The Thread object exists (NEW) but has no separate flow or stack yet.

mainmain()RUNNABLEThread-0run()RUNNABLE

start(): the JVM creates a new stack and starts run() on it. start() returns at once.

mainmain()RUNNABLEThread-0run()RUNNABLE (waiting its turn)

One possible order: main moves first and prints.

mainemptyTERMINATEDThread-0run()RUNNABLE

main() has ended but the program hasn't: the JVM waits until all non-daemon threads finish.

mainemptyTERMINATEDThread-0run()RUNNABLE

Thread-0 runs on its own stack; name is its local variable.

mainemptyTERMINATEDThread-0run()RUNNABLE

Thread-0 prints.

mainemptyTERMINATEDThread-0emptyTERMINATED

run() is done: Thread-0 is TERMINATED. No threads are left running, so the JVM exits.

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");
    }
}

Creating and Starting

Extending the Thread Class

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");
    }
}
  • A thread can also be created by extending the Thread class.
  • Instead of implementing Runnable, write a subclass of Thread; Thread already implements Runnable.
  • The object itself is a Thread, so you call w.start() and getName() directly.
Output (a real run)
main goes on
Worker running: Thread-0

Again, the order may change.

Creating and Starting

start() or run()?

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();
    }
}
Output
inside run(): main
inside run(): Thread-0
CallWhat happens
t.run()An ordinary method call: runs on the same thread (main), no new stack; main waits until it ends.
t.start()The JVM creates a new thread and stack; run() runs there and start() returns at once.
t.start() a second timeIllegalThreadStateException: a Thread object can be started only once.
Rule: put the thread's work in run(); call start() to start the thread.

Creating and Starting

The Single Inheritance Problem

  • Java lets a class inherit from only one class.
  • If the runnable class already extends another class (Base), it cannot extend Thread: extends Base, Thread won't compile.
  • The fix: the class implements Runnable and keeps a field of type Thread.
  • There is no limit on interfaces, which is why Runnable is usually preferred.
Base+ greet(): void«interface»Runnable+ run(): voidWorker- thread: Thread+ run(): void+ start(): voidextendsimplements

Creating and Starting

Single Inheritance: The Fix in Code

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()
    }
}
Output
Hello from Base
run(): Thread-0
  • Worker inherits Base's methods and can also run on a thread.
  • Our own start() hands itself to a Thread with new Thread(this).
  • this is a Runnable, which the Thread constructor accepts.

Creating and Starting

Three Ways: A Comparison

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();
    }
}
Output
1) Runnable class
2) Thread subclass
3) Lambda
WayWhen?
implements RunnableThe class already extends another; keeps the task separate from the thread
extends ThreadShort, standalone examples; uses up the one superclass
Lambda (Java 8+)The handiest way for short tasks

Each start() is followed right away by join(), so the output order is fixed. static class: a class nested inside another class.

Creating and Starting · One possible order

Two Threads: One Possible Order

mainAB▶atime →

main starts A. A is now RUNNABLE; when it will run is unknown.

mainAB▶a▶btime →

main starts B.

mainAB▶a▶btime →

a.join(): main is WAITING until A ends. Now A and B run.

mainAB▶a▶b1time →

The scheduler runs A: A executes task() on its own stack.

mainAB▶a▶b11time →

A context switch: now B is running. B's i is a separate local variable.

mainABjoin() waits▶a▶b112time →

A again.

mainABjoin() waits▶a▶b1122time →

B again. Then both end (TERMINATED).

mainABjoin() waits▶a▶b1122printtime →

a.join() returns; b.join() returns at once since B is already done; main prints.

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");
    }
}

One of the possible orders. A real run gave B1 · B2 · A1 · A2. What is certain: “main: done” comes last.

Managing and Stopping

Managing Threads: sleep, join, yield

sleep(ms)

Puts the current thread to sleep for a while (TIMED_WAITING). It keeps any lock it holds.

join()

The calling thread waits until the target thread ends. join(ms): at most ms.

yield()

A hint to let another thread run for now; the scheduler may ignore it.

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);
    }
}
Output
before join: 0
after join : 500000500000

Without join(), main reads result before calc finishes and sees 0. After join(), calc has definitely finished and the value it wrote is visible.

sleep and join can throw InterruptedException: catch it or declare it with throws.

Managing and Stopping

Daemon (Background) Threads

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");
    }
}
Output
tick 0
tick 1
tick 2
tick 3
main done, JVM exiting
  • The JVM exits once all non-daemon threads have ended; it doesn't wait for daemon threads.
  • Though clock loops forever, the program ends when main does.
  • Call setDaemon(true) before start(); afterwards it throws IllegalThreadStateException.

Managing and Stopping

Stopping a Thread

  • A thread stops when its run() method completes.
  • The JVM exits when System.exit() (internally Runtime.exit()) is called or when all non-daemon threads have ended.
  • The right way to stop a thread from outside is cooperation: the thread periodically checks a flag.
  • The flag is declared volatile so other threads can see the change.
  • Alternative: an interrupt request with interrupt().
Don't use Thread.stop()

The deprecated stop() kills a thread mid-task; its locks are released and objects may be left half-updated. Since Java 20 it no longer works:

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

Managing and Stopping

Stopping 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");
    }
}
Output
working...
working...
working...
working...
flag seen, finishing
main: worker stopped
  • finish() only raises the flag; the thread sees it at the top of the loop and leaves run() on its own.
  • While main slept 350 ms, the worker printed four times, at 0, 100, 200 and 300 ms.
  • Without volatile, the worker might never see the flag change.

Managing and Stopping

Stopping via a Reference

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");
    }
}
Output
run() done
main: done
  • The class implements Runnable; the running Thread object is kept in a volatile field.
  • The loop goes on while the field still points to its own thread, compared with Thread.currentThread().
  • finish() sets the field to null; the condition fails and run() ends.
  • currentThread() is static, so a class that doesn't extend Thread needs the Thread. prefix.

Synchronization

Executing Operations in the Right Order

Unknown speed

Each thread's speed and frequency vary. Operating systems may ignore priorities; you can't rely on priorities for ordering.

Stale values

After one thread reads a variable, another may update it; the first carries on with an out-of-date value.

Reordering

The compiler, the JIT and the CPU may reorder instructions for speed; unnoticeable in one thread, surprising with several.

T1T2read x → 5write x + 1 = 6 (stale!)write x = 9T2's 9 is lost
When several threads access shared, mutable data, access must be synchronized. Otherwise the result depends on the order in which the threads run: this is a race condition.

Synchronization

Race Conditions

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);
    }
}
Run 1
Expected: 200000
Actual  : 138001
Run 2
Expected: 200000
Actual  : 135352
Run 3
Expected: 200000
Actual  : 136776

A different result below 200000 every run: some increments get lost.

Synchronization · One possible order

Why Does counter++ Get Lost?

memorycounter = 0t1reg = —t2reg = —

At first counter = 0. Both threads will do counter++; the right result is 2.

memorycounter = 0t1reg = 0t2reg = —read

t1 reads: its register gets 0.

memorycounter = 0t1reg = 0t2reg = 0read

Context switch! t2 reads too: it also sees 0.

memorycounter = 0t1reg = 1t2reg = 0

t1 adds 1 in its register.

memorycounter = 1t1reg = 1t2reg = 0write

t1 writes: counter = 1.

memorycounter = 1t1reg = 1t2reg = 1

t2 adds 1 to its own (stale) value: 1.

memorycounter = 1t1reg = 1t2reg = 1write

t2 writes: counter = 1. Two increments ran, but the result is 1: t1's increment is lost.

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

This is just one possible order; without an interleaving the result is right. That is why the bug looks random and is hard to test. The call stack box shows the thread running at that moment.

Synchronization

Synchronization Options

join()

Wait for a thread to finish.

synchronized

Mutual exclusion with an object's monitor lock.

Lock objects

ReentrantLock, ReadWriteLock: explicit locking.

Barriers, semaphores, exchangers, latches

CyclicBarrier, Semaphore, Exchanger, CountDownLatch.

volatile variables

Reads and writes visible to all threads.

Atomic objects

Indivisible operations such as AtomicInteger.

Things that look like synchronization but aren't: priorities, sleeping (sleep), yielding (yield) and timers. They don't guarantee order; never write code that says “I'll wait a bit, the other one will be done by then”.

Synchronization · synchronized

synchronized and Monitors

  • Every object has a monitor (intrinsic lock) that can be locked and unlocked.
  • Only one thread can own a monitor at a time.
  • If t2 wants it while t1 owns it, t2 waits (BLOCKED).
  • When the monitor is released, the waiting threads compete and only one gets it.
  • The monitor is taken with synchronized and released automatically when the block ends (even via an exception).
  • This gives mutual exclusion and protects data integrity.

Syntax

synchronized (o) {
    // we hold o's monitor here
}
Runnable r = () -> {
    for (int i = 0; i < 50_000; i++) {
        synchronized (o) {   // take o's monitor
            shared++;
        }                    // monitor released
    }
};
Output (2 × 50000, every time)
100000

Synchronization

Monitors Step by Step

// t1 and t2 run the same code
synchronized (o) {
    shared++;     // critical section
}

A critical section is code that accesses shared data and must be run by only one thread at a time.

entry setBLOCKEDobject omonitorowner: nonedonet1t2

t1 and t2 reach the synchronized (o) line at the same time; the monitor is free.

entry setBLOCKEDobject omonitorowner: t1donet2t1

t1 wins and takes the monitor. t2 waits in the entry set, BLOCKED.

entry setBLOCKEDobject omonitorowner: nonedonet2t1

t1 leaves the block: the monitor is released automatically. The waiting threads compete.

entry setBLOCKEDobject omonitorowner: t2donet2t1

t2 takes the monitor and enters the critical section.

entry setBLOCKEDobject omonitorowner: nonedonet1t2

t2 leaves too. shared++ ran twice without interfering.

Synchronization

Declaring Synchronized Methods

synchronized method

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

Equivalent: a synchronized block

class C {
    void p() { synchronized (this) { ... } }
    static void q() { synchronized (C.class) { ... } }
    //...
}
  • Declaring a method synchronized is the same as wrapping its body in a synchronized block.
  • Instance method → the monitor of this.
  • static method → the monitor of the class object C.class (there is no instance).
  • So a static synchronized method and an instance synchronized method don't block each other: different locks.
  • The block form lets you lock only the lines that really need it.

With real bodies in place of ... (say n++, s++), both forms compile and behave the same.

Synchronization

Preventing the Race

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());
    }
}
Output (every run)
Result: 200000
  • increment() is now synchronized: the read–add–write steps run without interruption.
  • The reader, getValue(), must be synchronized too; otherwise it isn't guaranteed to see the latest value.
  • The price: threads enter one at a time and slow down a bit. So protect only shared data.

Synchronization

Mutual Exclusion: MinQueue

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));
    }
}

All methods use the same monitor (this).

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);
}
Output
[5, 2, 8]
2
[5, 8]
Queue full

Visibility · volatile

volatile Fields

  • For speed, values may be kept in a cache or a register; other threads then can't see the current value.
  • For a volatile field, every read sees the last write to it (a volatile write happens-before the next read).
  • Single reads and writes of variables other than long and double are already atomic; volatile long/double become atomic too.
  • A simple shared flag needs no synchronized or lock.
  • But only reads and writes are atomic: read–modify–write like x++ is not atomic.
Core 1: maincache: stop = trueCore 2: tregister: stop = falseMain memory (intuitive model): stop = truewritesnever rereads(stale copy)

Visibility

The 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);
    }
}
Output: NO volatile
main: stop = true
still running? true
Output: static volatile boolean stop
main: stop = true
thread stopped
still running? false

Without volatile, the JIT compiler may read stop once and run the loop as while (true): the thread never sees the change. Results vary by JVM; correctness shouldn't be left to luck.

setDaemon(true): so the stuck thread doesn't keep the program from exiting.

Visibility · volatile

volatile Is Not Atomic and Can't Be final

static volatile int counter = 0;
// inside main:
Runnable r = () -> {
    for (int i = 0; i < 100_000; i++) counter++;
};
Three runs (expected 200000)
volatile counter: 163299
volatile counter: 164441
volatile counter: 199332

Visibility is fine, but two threads can still read the same value and write the same result. The fix: synchronized or AtomicInteger.

public class FinalVolatile {
    private final volatile int x = 5;
}
Compiler error
FinalVolatile.java:2: error: illegal combination of modifiers: final and volatile
    private final volatile int x = 5;
                               ^
1 error
finalvolatile
Assigned once (in the constructor); never changesIts value can change
After the constructor (if this didn't escape), all see the same valueEvery read returns the current value

They solve synchronization needs differently; they can't be combined.

Visibility

The Java Memory Model: happens-before

The Java Memory Model (JMM) defines when a value written by one thread becomes visible to another. Programmers reason not with CPU barriers but with happens-before relations: if A happens-before B, whatever A wrote is guaranteed to be visible in B.

RuleA happens-before B
Locksreleasing a monitor/lock → the next acquisition of the same lock
volatilea write to a volatile field → the next read of that field
Starteverything before t.start() → the actions inside t
Terminationall of t's actions → the thread returning from t.join()
Library structuresBlockingQueue.put → the take that gets that element; a Future's task → get()
False sharing: if independent variables of different threads sit on the same cache line (usually 64 bytes) and are updated often, the cores keep pulling the line from each other. The result isn't wrong, but the program slows down: a performance problem, not a correctness one.

Explicit Locks

Explicit Locking

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);
    }
}
  • Used for complex synchronization scenarios.
  • The Lock interface in java.util.concurrent.locks; ReentrantLock and ReadWriteLock offer advanced, customizable locks.
  • Adds flexibility and performance: try-locks, timed and interruptible lock acquisition.
  • Use with care: you must release the lock.
  • Import: java.util.concurrent.locks.*
Output
Result: 200000

Explicit Locks

Unlock in a finally Block

The right pattern

public void work() {
    Lock lock = ...;
    lock.lock();
    try {
        // access the guarded resource
    } finally {
        lock.unlock();
    }
}
  • Call lock() right before the try.
  • unlock() goes in finally: the lock is released in every case, even if the critical section throws.

Wrong: no finally

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

The lock stays locked; every thread that wants it waits forever. synchronized has no such problem: the lock is released automatically when the block ends.

Wrong: unlocking a lock you don't hold

Lock lock = new ReentrantLock();
lock.unlock();   // never acquired
Runtime error
Exception in thread "main" java.lang.IllegalMonitorStateException

Explicit Locks · Lock

tryLock(): Locking Without Waiting, or With a Timeout

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");
    }
}
  • tryLock(): takes the lock if free and returns true; if not, returns false without waiting.
  • tryLock(3, SECONDS): waits at most 3 s; InterruptedException must be declared.
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();
Output
1: not acquired
main: releasing the lock
2: acquired

Explicit Locks · Lock

The ReentrantLock Class

  • The name means it allows reentry.
  • The thread holding the lock can take the same lock again; it doesn't wait, a counter just goes up. The lock is released when the counter drops to 0.
  • Several ReentrantLocks can guard nested critical sections.
  • Fair locking: with new ReentrantLock(true) the lock goes to the longest-waiting thread.
  • synchronized is reentrant too: a synchronized method can call another synchronized method of the same object.
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());
Output
both locks acquired
fair? true

Explicit Locks · Step-by-step trace

Reentrancy, Step by Step

lockowner: nonecount = 0

main calls outer(). The lock is free.

lockowner: maincount = 1

outer() takes the lock: owner main, hold count 1.

lockowner: maincount = 1

show prints the count.

lockowner: maincount = 2

inner() asks for the same lock. main already owns it, so it doesn't wait: the count becomes 2.

lockowner: maincount = 2

Printed.

lockowner: maincount = 1

inner()'s finally: unlock() drops the count to 1; main still holds the lock.

lockowner: nonecount = 0

outer()'s finally: the count is 0 and the lock is really released.

lockowner: nonecount = 0

Every lock() needs one unlock().

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:    ");
    }
}

Explicit Locks · Lock

The ReadWriteLock Class

Reader-1Reader-2Reader-3Writerreads in parallelwrite aloneparallel againtime →
Read lock

Several threads can read the data at the same time without blocking each other (parallel reads).

Write lock

While one thread writes, others can neither read nor write; the write is safe and atomic.

When?

Improves performance when data is read often and written rarely (caches, settings tables).

Explicit Locks · Lock

ReadWriteLock Code

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();
    }
}
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();
Output (one run)
Reader-2: en
Reader-1: en

Two readers can hold the read lock at once; their order may vary. ReentrantReadWriteLock implements the ReadWriteLock interface.

Explicit Locks

Explicit vs Implicit Locking

Explicit: LockImplicit: synchronized
ControlThe developer calls lock()/unlock()Automatic: taken on block entry, released on exit
ClassesThe Lock interface, ReentrantLock, ReentrantReadWriteLockA keyword; every object's monitor
Try without waitingtryLock(), tryLock(time): conditional, non-blockingNone: waits until the lock is free
Interruptible waitlockInterruptibly()None
Fairness, conditionsnew ReentrantLock(true), multiple ConditionsNone; one wait set
ReentrancyReentrantLock is reentrantAlways reentrant
RiskForget unlock() and the lock is held foreverNothing to forget
When?When you need advanced controlSimple cases; more readable code

Explicit Locks · Deadlock

Deadlock

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);
}
T1T2abholdswaits forholdswaits for
Output
BLOCKED BLOCKED
Deadlocked: 2

Two or more threads wait forever for locks the others hold. It happens when locks are taken in different orders. pause(ms) wraps sleep in try-catch.

Explicit Locks · Step-by-step trace

Deadlock, Step by Step

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();
}
lock alock bT1newT2newgreen: holds the lockred: waiting

There are two lock objects; nobody holds them yet.

lock alock bT1runnableT2newgreen: holds the lockred: waiting

T1 starts and takes a with synchronized (a).

lock alock bT1runnableT2runnablegreen: holds the lockred: waiting

T2 was called with the order reversed: it takes b first. No problem yet.

lock alock bT1sleepingT2sleepinggreen: holds the lockred: waiting

Both sleep for 100 ms; sleep does not release the locks held.

lock alock bT1blockedT2sleepinggreen: holds the lockred: waiting

T1 wakes up and asks for b for the inner block. T2 has b: T1 is BLOCKED.

lock alock bT1blockedT2blockedgreen: holds the lockred: waitingCYCLE

T2 asks for a; T1 has a. Each waits for the other to let go: a cycle has formed.

lock alock bT1blockedT2blockedgreen: holds the lockred: waitingCYCLE

Neither reaches the "done" line; the program waits forever. findDeadlockedThreads() reports 2 threads.

lock alock bT1runnableT2blockedgreen: holds the lockred: waiting

Had both threads taken the locks in the same order (a first), T2 would wait at a without ever holding b: no cycle could form.

Explicit Locks · Deadlock

Preventing Deadlock

One change: the same order

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

Everyone takes a first, then b: no cycle can form. T2 waits for a; it gets it once T1 is done, and finishes too.

A fixed lock order

All threads take locks in the same order (say, by ID).

Timed attempts

If tryLock(time) fails, release what you hold and retry later.

Short critical sections

Don't request another lock or do long work while holding one.

Diagnosis

jstack or ThreadMXBean.findDeadlockedThreads() reveals deadlocks.

Explicit Locks

Livelock and Starvation

Deadlockeveryone blocked, nothing changesLivelockeveryone busy, but no progressStarvationone thread never gets a turn
Livelock

The threads aren't blocked; they keep changing state by “giving way” to each other, but none finishes. Example: two threads that release everything when tryLock fails and retry at the same moment, colliding every time.

Starvation

A thread gets the resource late or never: others keep grabbing the lock, or long critical sections keep it waiting. Priority values (setPriority) are not reliable for fixing this.

Lock fair = new ReentrantLock(true);  // fair
if (lock.tryLock(50, TimeUnit.MILLISECONDS)) {
    try { /* work */ }
    finally { lock.unlock(); }
} else {
    Thread.sleep(rnd.nextInt(20)); // random
}
  • A fair lock gives the turn to the longest waiter (a bit slower).
  • Waiting a random time before retrying breaks the symmetry and prevents livelock.
  • Short critical sections give everyone a turn.

Condition Synchronization

Condition Synchronization

  • Gives safe access to a shared resource only when a certain condition holds.
  • Example: a consumer should take an item only when the queue is not empty; a producer should add only when it is not full.
  • Controlled updates need the object's lock, plus a way to wait until the condition holds.
  • But you can't wait while holding the lock: the thread that would change the condition can't get the lock, and everyone gets stuck.
What Java provides

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

Wrong: busy waiting

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

Condition Synchronization

Object.wait() and Object.notify()

entry setwaiting for the lockBLOCKEDmonitor owner(one thread)wait setwaiting on a conditionWAITINGacquireswait():releasesnotify() / notifyAll(): the woken thread queues up to reacquire the lock
  • Every object has a wait set.
  • The thread holding the lock calls wait(): it enters the set, releases the lock and blocks.
  • notify() wakes one thread, notifyAll() wakes them all; wait(ms) also returns when time is up.
  • The woken thread continues where it left off once it reacquires the lock.
  • Rule 1: call them only inside synchronized; otherwise IllegalMonitorStateException: current thread is not owner.
  • Rule 2: check the condition with while, not if: on waking it may be false again (or the wakeup may be spurious).

Condition Synchronization

BlockingQueue with wait() and notifyAll()

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;
    }
}
  • A circular array: head is where to remove, tail where to add; % data.length wraps around.
  • add waits while full, remove while empty; after each change notifyAll() wakes the waiters.

Condition Synchronization · One possible order

Producer–Consumer, Step by Step

data[0]1data[1]—headtailProducerrunningConsumerrunning

The producer calls add(1): there is room, so 1 goes in; tail moves to 1.

data[0]1data[1]2headtailProducerrunningConsumerrunning

add(2): tail wraps to 2 % 2 = 0. The queue is full.

data[0]1data[1]2headtailProducerWAITINGConsumerrunning

add(3): the queue is full, so wait(): the producer enters the wait set and releases the lock.

data[0]—data[1]2headtailProducerWAITINGConsumerrunning

The consumer gets the lock: remove() takes 1, nulls the slot, and head becomes 1.

data[0]—data[1]2headtailProducerBLOCKEDConsumerrunning

notifyAll(): the producer wakes, but the consumer still holds the lock, so it waits for it. remove returns 1.

data[0]3data[1]2headtailProducerrunningConsumerrunning

The producer gets the lock and checks the while condition again: not full. 3 is written to data[0].

data[0]3data[1]—headtailProducerrunningConsumerrunning

The consumer takes 2; head wraps around.

data[0]—data[1]—headtailProducerrunningConsumerrunning

The consumer takes 3. The queue is empty.

data[0]—data[1]—headtailProducerrunningConsumerWAITING

The next remove(): the queue is empty, so the consumer waits; it will wake when the producer adds 4 and calls notifyAll().

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;
}

Capacity 2. This is one possible order; the real one depends on the scheduler, but in no order does the queue overflow or get read while empty.

Condition Synchronization

Producer–Consumer: A Real Run

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());
Output (one run)
produced: 1
produced: 2
produced: 3
consumed: 1
produced: 4
consumed: 2
consumed: 3
consumed: 4
left: 0

The order of the lines may vary. Here “produced: 3” appeared before “consumed: 1”: the producer ran after the consumer returned from remove but before it printed.

Condition Synchronization · Condition

The Condition Interface

  • Lets a thread wait until a state changes and then continue where it left off.
  • Brings wait()/notify() to the Lock world; used with a ReentrantLock: lock.newCondition().
  • await(): releases the lock and suspends the thread.
  • signal() / signalAll(): wakes one / all waiting threads.
  • A lock can have several conditions: producers and consumers wait in separate queues.
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()
}

Condition Synchronization · Condition

BlockingQueue with Condition

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();
    }
}
Output: the producer adds 1–4, main removes 4 times
1 2 3 4 

Adding signals only notEmpty, removing only notFull: no needless wakeups, so signal() is enough.

Condition Synchronization

Ready-Made: java.util.concurrent

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();
Output
1 2 3 4 
ApproachWaitingWaking
synchronizedwait()notify(), notifyAll()
Lock + Conditionawait()signal(), signalAll()
ArrayBlockingQueueinside put(), take()automatic

Real projects use the ready-made java.util.concurrent.BlockingQueue implementations (ArrayBlockingQueue, LinkedBlockingQueue); our own class is for understanding the mechanism.

Synchronizers

Synchronizers

Ready-made tools (java.util.concurrent) that bring order among threads; each solves a different scenario.

Latch: 3 → 0210gate opens at zeroBarrier: all arrivethen togetherExchanger: swapABSemaphore: 2 permitsT1T2T3third waits
CountDownLatch

“Let N events happen, then go on.” Waiters stop until the count reaches zero. Single-use.

CyclicBarrier

“Let's all reach the meeting point, then continue together.” Reusable.

Exchanger

Two threads meet at a point and swap data.

Semaphore

N permits: at most N threads can use the resource at once.

Synchronizers · A real run

CountDownLatch

count3123eventsmainrunning

Synchronizes threads that wait for a number of events. count: the starting count, here 3.

count3123eventsmainrunning

Three threads are started; when they will run is unknown.

count3123eventsmainWAITING (await)

await(): main waits until the count reaches 0.

count2123eventsmainWAITING (await)

Thread 1 prints; countDown() lowers the count by 1: 2.

count1123eventsmainWAITING (await)

In this run, thread 3 came next: the count is 1.

count0123eventsmaingo on

The last event: the count is 0. The latch opens and main wakes up.

count0123eventsmaingo on

This line always comes last; the order of the event lines may vary.

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!");
}

Single-use: the count never goes up; countDown() at zero has no effect.

Synchronizers

CyclicBarrier

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();
    }
}
  • Makes a group of threads wait at a meeting point (the barrier); parties: how many to wait for.
  • await(): wait until the party is complete. Then the barrier action runs once and everyone continues.
  • An exception, a timeout or an interrupt breaks the barrier: the waiters get BrokenBarrierException.
Output (one run)
1 waiting
2 waiting
3 waiting
Party complete!
3 continuing
1 continuing
2 continuing

Synchronizers

Exchanger

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();
Output
sending: Data 2
sending: Data 1
Data 1 owner got: Data 2
Data 2 owner got: Data 1
  • Used by two threads to exchange data; more a communication object than a lock.
  • exchange(data) waits until the other side also calls exchange: the “Data 2” owner waited 1 s.
  • When they meet, each gets the other's data.

Synchronizers · A real run

Semaphore

permits3 / 31—2—3—4—5—

A semaphore limits concurrent access: here at most 3 threads at a time. new Semaphore(n, true): fair distribution.

permits3 / 31ready2ready3ready4ready5ready

Five threads start. acquire() waits if no permit is left; release() gives the permit back.

permits2 / 31inside2ready3ready4ready5ready

1 takes a permit and enters.

permits1 / 31inside2ready3inside4ready5ready

3 enters.

permits0 / 31inside2inside3inside4ready5ready

2 enters. No permits left.

permits0 / 31inside2inside3inside4waiting5waiting

4 and 5 wait in acquire().

permits1 / 31inside2done3inside4waiting5waiting

After 2 s, 2 leaves and releases its permit.

permits2 / 31done2done3inside4waiting5waiting

1 leaves too.

permits0 / 31done2done3inside4inside5inside

The waiting 4 and 5 take the permits and enter.

permits3 / 31done2done3done4done5done

3, 4 and 5 leave too; all 3 permits are 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();
    }
}

Other Tools

Atomic Classes

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());
    }
}
Output
Result: 200000
true 0
false 0
  • AtomicInteger, AtomicLong, AtomicBoolean…: safe access without locks.
  • incrementAndGet() = an atomic ++x; it can't be interrupted halfway.
  • An atomic object ≈ a volatile field + an atomic compareAndSet.
  • compareAndSet(expected, update): if the value is still expected, writes update and returns true; otherwise leaves it alone.

Other Tools · Step-by-step trace

Lock-Free Increment with compareAndSet

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
    }
}
memorycounter5T1old = –next = –T2old = –next = –

Two threads will increment the same counter object. It starts at 5.

memorycounter5T1old = 5next = –T2old = –next = –

T1 reads the current value: old = 5.

memorycounter5T1old = 5next = –T2old = 5next = –

Before T1 goes on, T2 reads too and also sees 5. There's no lock, so both keep running.

memorycounter5T1old = 5next = 6T2old = 5next = 6

Both compute next = 6 locally. With a plain counter++, both would write 6 and one increment would be lost.

memorycounter6T1old = 5next = 6T2old = 5next = 6CAS succeeds

T1: compareAndSet(5, 6). The value is still 5 → 6 is written and true returned. Check and write are one atomic operation.

memorycounter6T1old = –next = –T2old = 5next = 6CAS fails

T2: compareAndSet(5, 6). The value is now 6, not the expected 5 → nothing is written; false.

memorycounter6T1old = –next = –T2old = 6next = –

The loop repeats: T2 rereads the current value.

memorycounter6T1old = –next = –T2old = 6next = 7

next = 7.

memorycounter7T1old = –next = –T2old = 6next = 7CAS succeeds

This time the CAS succeeds: counter = 7. Both increments counted; nobody waited for a lock, T2 just went around once more.

Other Tools

Interrupting

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");
    }
}
Output
working...
working...
working...
Thread cancelled!
main: done
  • interrupt(): an interrupt request; if the thread is in sleep/wait, it gets an InterruptedException.
  • Thread.interrupted() reads the flag and clears it; isInterrupted() only reads it.

Other Tools · Step-by-step trace

Interrupting, Step by Step

Thread worker = new Thread(() -> {
    try {
        while (!Thread.interrupted()) {
            System.out.println("working...");
            Thread.sleep(400);
        }
    } catch (InterruptedException e) {
        System.out.println("cancelled!");
    }
});
worker.start();
Thread.sleep(1000);
worker.interrupt();   // worker is in sleep()
worker.join();
System.out.println("main: done");
workermain04008001000interrupt flag: false

start() sets worker running. The interrupt flag is false.

workermainsleep04008001000interrupt flag: false

The flag is clear: it enters the loop, prints and sleeps 400 ms.

workermainsleepsleep(1000)04008001000interrupt flag: false

main sleeps 1000 ms too; the two threads proceed independently.

workermainsleepsleepsleep(1000)04008001000interrupt flag: false

worker wakes up; Thread.interrupted() is still false: one more lap.

workermainsleepsleepsleepsleep(1000)04008001000interrupt flag: false

Third lap: it prints and sleeps again (it would have slept until 1200 ms).

workermainsleepsleepsleepsleep(1000)04008001000interrupt()interrupt flag: true

main wakes up and calls interrupt(): worker's interrupt flag becomes true.

workermainsleepsleepsleepsleep(1000)04008001000interrupt flag: false

worker is in sleep, so the sleep is cut short at once: an InterruptedException is thrown and the flag is cleared again.

workermainsleepsleepsleepsleep(1000)04008001000interrupt flag: false

main waits for worker with join(); worker ends after the catch.

workermainsleepsleepsleepsleep(1000)04008001000interrupt flag: false

The program ends cleanly. An interrupt is a request: the thread itself handles the flag or the exception and exits.

Other Tools

Suspension

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) { }
    }
}
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();
Output
step 1
step 2
step 3
main: paused
main: resume
step 4
step 5

Use wait()/notifyAll() instead of suspend()/resume().

Other Tools

The ThreadLocal Class

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());
Run 1
thread1: Value 1
thread2: Value 2
main: null
Run 2
thread2: Value 2
thread1: Value 1
main: null
  • A variable of which each thread has its own copy; the copies are independent.
  • main never called set, so it sees null.
  • ThreadLocal.withInitial(() -> 0) (Java 8+), or overriding initialValue(), gives each thread its own initial value.

Other Tools

Thread Pools

submit(task)task queueT1T2T3T4thread pool (2)pool-1-thread-1pool-1-thread-2a thread takes a new task when it finishes one
  • A structure that creates threads up front and manages them: tasks are submitted to the pool.
  • Creating threads is expensive; a pool reuses them and caps their number.
  • The ExecutorService interface controls the pool's work; Executors.newFixedThreadPool(n) gives a ready-made pool.
  • ThreadPoolExecutor: the class that creates and manages the pool, with fine-grained settings.

Other Tools

ExecutorService

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");
    }
}

Java 21+: Executors.newVirtualThreadPerTaskExecutor() gives each task a lightweight virtual thread.

Run 1
Task 1 -> pool-1-thread-1
Task 2 -> pool-1-thread-2
Task 3 -> pool-1-thread-2
Task 4 -> pool-1-thread-2
Callable result: 42
Pool shut down
What differed in run 2
Task 3 -> pool-1-thread-1
Task 4 -> pool-1-thread-2

A Callable returns a value; Future.get() waits for the result. Forget shutdown() and the pool's threads keep the program alive.

Other Tools · Step-by-step trace

The Pool and Future, Step by Step

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();
queueworker 1worker 20100200300main: runningdone: –

A fixed pool of 2 threads. Workers run tasks as they come and take a new one when done.

queueworker 1worker 2f10100200300main: runningdone: –

submit hands the task to the pool and returns a Future at once. f1 starts on worker 1.

queueworker 1worker 2f1f20100200300main: runningdone: –

f2 goes to the idle worker 2.

queuef3worker 1worker 2f1f20100200300main: runningdone: –

Both workers are busy: f3 waits in the queue. No new thread is created.

queuef3worker 1worker 2f1f20100200300main: runningdone: –

No task is done yet; isDone() answers without waiting.

queueworker 1worker 2f1f2f30100200300main: waiting in f1.get()done: f2

f1.get() blocks main until the result is ready. Meanwhile f2 ends and worker 2 takes f3 from the queue.

queueworker 1worker 2f1f2f30100200300main: waiting in f1.get()done: f2, f3

f3 ends too; main is still waiting for f1.

queueworker 1worker 2f1f2f30100200300main: runningdone: f1, f2, f3

t ≈ 300 ms: f1 is ready. f2 and f3 are already done, so their get()s return at once. Total time ≈ 300 ms, not 500.

queueworker 1worker 2f1f2f30100200300main: runningdone: f1, f2, f3

The result and states are printed.

queueworker 1worker 2f1f2f30100200300main: donedone: f1, f2, f3

shutdown() stops accepting tasks; the workers end. Forget it and the program never exits.

Times are approximate (ignoring thread start-up delay); which worker gets which task may vary from run to run.

Other Tools

CompletableFuture, Concurrent Collections, ForkJoinPool

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}
  • CompletableFuture: rather than blocking on get(), chain steps; each runs in the background after the previous one.
  • ConcurrentHashMap: a safe map with fine-grained locking; merge and compute are atomic.
  • CopyOnWriteArrayList: copies on every write; for read-mostly lists.
  • ForkJoinPool: divide-and-conquer tasks (RecursiveTask); an idle worker steals from another's queue. Parallel streams (parallelStream()) use it.
  • A parallel stream isn't always faster: small data and shared mutable state slow or break it; measure first.

Other Tools

Thread Safety

A class is thread-safe if it behaves correctly even when used from several threads at once.

Immutable objects

Objects that never change after construction (String, classes with final fields, Java 16+ records) can be shared without synchronization.

Don't share

Local variables live on each thread's stack; ThreadLocal gives copies too. Unshared data can't race.

Synchronization

Every access to shared mutable data is guarded by the same lock: synchronized, Lock.

Ready-made structures

AtomicInteger, ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue; ArrayList and HashMap are not safe.

Summary

Summary

TopicEssenceTools
ThreadAn independent flow inside a process; shared heap, separate stackThread, Runnable
StartingWork goes in run(); start() starts itstart(), join()
Life cycleNEW → RUNNABLE ⇄ BLOCKED / WAITING / TIMED_WAITING → TERMINATEDgetState()
StoppingBy cooperation: a flag or an interruptvolatile, interrupt()
Race conditionDivisible operations on shared data; the result depends on ordersynchronized, Lock
VisibilityWhat one thread writes may stay invisible to anothervolatile
DeadlockTaking locks in different orders creates a cycleA fixed order, tryLock
Condition waitingWait while releasing the lock; wake on changewait/notify, Condition
CoordinationCounting, meeting, swapping, permitsCountDownLatch, CyclicBarrier, Exchanger, Semaphore
OtherLock-free counters, per-thread values, poolsAtomicInteger, ThreadLocal, ExecutorService

Review

Common Mistakes (1)

MistakeSymptomFix
Calling t.run()No new thread; the code runs in order on maint.start()
Calling start() twiceIllegalThreadStateExceptionA new Thread for each run
Thread.sleep(100); on its ownerror: unreported exception InterruptedException; must be caught or declared to be throwntry-catch or throws InterruptedException
Loop variable i in a lambdaerror: local variables referenced from a lambda expression must be final or effectively finalA copy: int no = i;
Catching an exception that is never thrown: try { while (!Thread.interrupted()) { } } catch (InterruptedException e)error: exception InterruptedException is never thrown in body of corresponding try statementThe body needs a sleep/wait, or drop the catch
currentThread() in a class that doesn't extend Threaderror: cannot find symbolThread.currentThread()
Forgetting join()main reads the result before it's ready (e.g. 0)join() before reading the result

Review

Common Mistakes (2)

MistakeSymptomFix
Calling wait()/notify() outside synchronizedIllegalMonitorStateException: current thread is not ownerInside synchronized on the same object
Waiting on a condition with ifThe condition may be false again on waking; an overflowing/empty queuewhile (condition) wait();
unlock() outside finallyOn an exception the lock is never released; everyone waits foreverlock(); try { … } finally { unlock(); }
Unlocking a lock you don't holdIllegalMonitorStateExceptionOne unlock() per lock()
counter++ on a volatile counterIncrements get lost (e.g. 163299)AtomicInteger or synchronized
A final volatile fielderror: illegal combination of modifiers: final and volatileUse only one of them
Using stop(), suspend()Java 20+: UnsupportedOperationExceptionA flag, interrupt(), wait/notify
Swallowing InterruptedException in an empty catchThe interrupt request is lost; the thread doesn't stopLeave the loop, or call Thread.currentThread().interrupt()
Taking locks in different ordersDeadlock: the program freezesEveryone takes them in the same order

Review

Practice Problems (1)

1) What is the output? Is it the same every run?

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

2) What is the output?

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

3) Which of these 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

Answers
  1. ABC, always. A is printed before start, B on the new thread; join() holds C until B is done.
  2. NEW X NEW. run() is an ordinary call: main prints X, the thread never starts and stays NEW.
  3. a and b. Not c: main prints after both join()s. Not d: a single thread's steps keep their order.

Review

Practice Problems (2)

4) What is the thread's state in each case?

a) inside sleep(500) · b) entering a synchronized block someone else holds · c) after wait() · d) when run() ends

5) Is this thread-safe?

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

6) Two threads run these. What can happen?

// T1                    // T2
synchronized (a) {       synchronized (b) {
  synchronized (b) { }     synchronized (a) { }
}                        }
Answers
  1. a) TIMED_WAITING b) BLOCKED c) WAITING d) TERMINATED.
  2. No: balance += m is read–add–write. Fix: make the methods synchronized or use AtomicInteger.addAndGet(m).
  3. Deadlock: if T1 takes a and T2 takes b, each waits forever for the other. Fix: both take a first, then b.

Review

Exercises (1)

  • 1. Sum the numbers 1..1000 with two threads: one adds the first half, the other the second; main waits for both and prints the total.
  • 2. Count the even numbers in 1..1000 with four threads (250 numbers each) into a shared counter. The count must come out right.
Answers

1. Each thread writes to its own slot; reading after join() is safe. Output: 500500

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();

2. AtomicInteger even; each thread runs for (int i = start; i < start + 250; i++) if (i % 2 == 0) even.incrementAndGet(); with start = 1, 251, 501, 751. After all the join()s the output is Even numbers: 500

Review

Exercises (2)

  • 3. Compute the squares of 1..5 with Callable tasks in a 3-thread pool and add them up from the Futures.
  • 4. Write a thread that prints “tick” every second; main stops it with interrupt() after 3.5 s.
Answers
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);

3. With the helper static long square(int n) { return (long) n * n; }. Output: Sum of squares: 55

4. The pattern from the “Interrupting” slide; sleep(1000) in the loop, sleep(3500) and interrupt() in main. Output: tick · tick · tick · tick · clock stopped

Summary

References

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

The End

Chapter 10: Threads
Previous: Chapter 9: Graphics and User Interfaces · Next: Chapter 11: Database Programming
1 / 1 Sercan KÜLCÜ, All rights reserved.