Multithreading in Java
Multithreading in Java: concepts (thread, synchronization, race, deadlock), Java APIs (Thread, Runnable, synchronized, volatile, locks, ExecutorService), memory-model rules (happens-before) and example programs showing common patterns.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Multithreading lets a Java program do more than one task at the same time (concurrency) or on multiple CPU cores (parallelism). Engineers use threads for responsive user interfaces, I/O concurrency (servers), background computation, and to make better use of multi-core processors.
Key ideas
Start from the simple difference between a program and what executes it. A process is an instance of a program running with its own memory. A thread is a single sequence of executed instructions inside a process that has its own CPU registers and program counter but shares the process memory and resources.
- Thread (defined): a lightweight unit of execution within a process. It executes code independently but can read/write shared memory of the process.
- Concurrency (defined): the property of a system in which multiple tasks make progress overlapping in time. They may execute truly in parallel (multiple CPUs) or by interleaving on a single CPU.
- Parallelism (defined): a special case of concurrency where tasks run at the same time on different CPU cores.
- Context switch (defined): saving and restoring CPU state when changing the running thread. This costs time.
Shared-memory programming introduces hazards because two threads can access the same variable. Key hazards and solutions:
- Race condition (defined): a situation where the program outcome depends on the non-deterministic order of operations by threads. If two threads write and read a shared variable without coordination, results can be wrong.
- Critical section (defined): a region of code that accesses shared state and must not run concurrently by multiple threads.
- Mutual exclusion (mutex) (defined): a mechanism to ensure only one thread executes a critical section at a time.
- Monitor (defined): an object that combines mutual exclusion (a lock) with the ability to wait and notify other threads (Java's synchronized block plus wait/notify implement a monitor).
- Lock (defined): an object that provides mutual exclusion; Java has intrinsic locks (one per object) used by synchronized and explicit locks via classes like ReentrantLock. Intrinsic locks are reentrant (a thread can acquire the same lock it already holds).
- volatile (defined): a field modifier that makes reads/writes to that variable visible to other threads in a specific way — volatile reads/writes establish memory visibility (no caching reorder), but volatile does not provide atomic read-modify-write.
- Atomic operation (defined): an operation that appears indivisible to other threads (example: operations on java.util.concurrent.atomic.AtomicInteger). Simple reads/writes of 32-bit primitives are atomic in Java, but compound actions (read-modify-write) are not atomic unless provided by atomic classes or synchronization. Reads/writes of references are also atomic; reads/writes of 64-bit long and double are not guaranteed atomic unless declared volatile (per JLS), so use volatile, AtomicLong, or synchronization when sharing them between threads.
- Deadlock (defined): a situation where two or more threads wait forever for resources held by each other. Classic condition: circular wait, hold-and-wait, no-preemption, mutual exclusion.
- Liveness (defined): properties like deadlock-freedom and starvation-freedom. Starvation is when a thread never gets CPU/lock because others monopolise it.
Java-specific rules that exams ask for (Java Memory Model basics):
- Happens-before relation (defined): a partial order on actions (reads/writes, locks/unlocks, thread start/terminate) that guarantees memory visibility: if action A happens-before action B, then the effects of A are visible to B.
Exact points commonly required in answers (state these as rules):
- Program order rule: Each action in a single thread happens-before every later action in that thread.
- Monitor lock rule: An unlock (exit of synchronized block) on a monitor happens-before every subsequent lock (entry of synchronized block) on that same monitor.
- Volatile rule: A write to a volatile field happens-before every subsequent read of that same volatile field.
- Thread start rule: A call to Thread.start() on thread T happens-before any action in the started thread T.
- Thread termination rule: Any action in a thread happens-before another thread successfully returns from a Thread.join() on that thread. Note: Thread.isAlive() returning false does not by itself establish a happens-before relationship.
- Transitivity: If A happens-before B and B happens-before C then A happens-before C.
Common exam derivation: show how synchronized ensures visibility. Steps to show on paper: draw two vertical timelines: Thread A and Thread B. Mark a synchronized block on object X in Thread A with an unlock operation at the end; mark a synchronized block on same object X in Thread B with a lock at its start. Label the unlock as "A: unlock(X)" and the lock as "B: lock(X)". Then write the rule: unlock happens-before subsequent lock, so writes in A before unlock are visible to reads in B after lock. This is the standard diagram requested in exams.
Also know these practical APIs and behavior: calling Thread.run() executes code in the calling thread (no new thread); calling Thread.start() creates a new thread and eventually calls run() in that new thread. Calling wait() inside a synchronized block causes the current thread to release the monitor and sleep; calling notify()/notifyAll() wakes waiting threads but does not release the lock immediately. Always call wait in a loop that rechecks the condition to handle spurious wakeups; Thread.sleep does not release any locks; Thread.interrupt sets the thread's interrupt status—blocking methods like wait/sleep/join react by throwing InterruptedException and clearing the status; check and propagate interruption with Thread.currentThread().isInterrupted() or Thread.interrupted().
Formulas
Remember these Java syntaxes and short forms:
class MyThread extends Thread { public void run() { /* code */ } } — define a thread by extending Thread.
class MyTask implements Runnable { public void run() { /* code */ } } — define a task by implementing Runnable.
synchronized(obj) { /* critical section */ } — enter monitor of obj; acquires intrinsic lock.
public synchronized void method() { /* ... */ } — synchronized method; equivalent to synchronized(this) for instance methods; for static methods, synchronized locks the Class object.
volatile int flag; — volatile field declaration.
Lock lock = new ReentrantLock(); lock.lock(); try { /* critical */ } finally { lock.unlock(); } — explicit lock use.
obj.wait(); obj.notify(); obj.notifyAll(); — wait and notify (must be called inside synchronized on the same object).
ExecutorService ex = Executors.newFixedThreadPool(n); ex.submit(Runnable); ex.submit(Callable<V>); Future<V> f = ex.submit(callable); V result = f.get(); ex.shutdown(); — thread pool and futures.
AtomicInteger a = new AtomicInteger(0); a.incrementAndGet(); — atomic operations.
Worked examples
Example 1 — Thread by extending Thread (simple and deterministic)
// File: PrintThread.java
class PrintThread extends Thread {
private final String msg;
public PrintThread(String msg) { this.msg = msg; }
public void run() { System.out.println(Thread.currentThread().getName() + ": " + msg); }
public static void main(String[] args) throws Exception {
Thread t1 = new PrintThread("Hello from t1");
t1.setName("t1");
Thread t2 = new PrintThread("Hello from t2");
t2.setName("t2");
t1.start(); t1.join(); // join to make output deterministic for this example
t2.start(); t2.join();
System.out.println("Main done");
}
}
Sample input: (none) Exact output:
t1: Hello from t1
t2: Hello from t2
Main done
Example 2 — Shared counter using AtomicInteger (shows correct concurrency-safe result)
// File: AtomicCounter.java
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter {
public static void main(String[] args) throws Exception {
final AtomicInteger counter = new AtomicInteger(0);
Thread[] threads = new Thread[5];
for (int i = 0; i < 5; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) counter.incrementAndGet();
});
threads[i].start();
}
for (Thread t : threads) t.join();
System.out.println("Final counter = " + counter.get());
}
}
Sample input: (none) Exact output:
Final counter = 5000
Example 3 — ExecutorService with Callable and Future
// File: SquaresExecutor.java
import java.util.concurrent.*;
public class SquaresExecutor {
public static void main(String[] args) throws Exception {
ExecutorService ex = Executors.newFixedThreadPool(3);
Callable<Integer> task = () -> { int n = 7; return n * n; };
Future<Integer> f = ex.submit(task);
System.out.println("7*7=" + f.get());
ex.shutdown();
}
}
Sample input: (none) Exact output:
7*7=49
Common mistakes
- Believing volatile gives atomic read-modify-write. (Wrong: volatile only guarantees visibility and ordering for the variable itself.)
- Using notify() when notifyAll() is required; not understanding that notify does not release lock immediately; not using a while loop to guard wait against spurious wakeups.
- Forgetting to call wait()/notify() only inside synchronized blocks on the same object.
- Assuming synchronized on different objects protects the same data. (Locking must be on the same monitor.)
- Thinking that making a field private removes data races — visibility rules still apply; publish updates safely (e.g., volatile stop flags or synchronization).
- Using Thread.stop() or Thread.suspend() in answers — these methods are deprecated and unsafe.
For your exam
- Short notes: describe synchronized, wait/notify, Atomic classes, ExecutorService. Include short code snippets and mention exceptions (IllegalMonitorStateException for wait/notify called outside synchronized). Also mention safe publication: establish a happens-before edge via synchronization, volatile, thread-safe containers, or immutability/final fields (writes to final fields in a constructor become visible after the constructor completes and the object is safely published).
- Derivations/diagrams: draw two threads' timelines showing synchronized unlock/lock and explain visibility via the monitor rule; show how a volatile write-read pair establishes a happens-before edge.
- Programs: write code to create threads using Thread or Runnable; write synchronized code to protect a shared counter; use ExecutorService and Callable. A full answer compiles and runs and explains why it is correct.
- Debug/analysis: given code with race, explain the race and give two fixes (synchronized or AtomicInteger) and show the correct final state.
Quick check
- What does the keyword volatile guarantee? (short)
- Which method creates a new OS/VM thread: run() or start()?
- Name two conditions that together can lead to deadlock. Answers: 1) volatile guarantees visibility (writes happen-before later reads) and ordering for that variable, not atomicity for compound actions. 2) start() creates a new thread; run() does not. 3) Mutual exclusion (locks) and circular wait (each thread waits for a resource held by another) — plus hold-and-wait and no-preemption are the other needed conditions.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?