Multithreading Part 3 — Advanced Patterns
Deadlock, livelock, starvation, daemon threads, thread interruption
- Detect and prevent deadlocks using lock ordering
- Distinguish deadlock, livelock, and starvation
- Use interrupt() and isInterrupted() for cooperative cancellation
Series:
Multithreading & Concurrency Part: 3 of N Topics Covered: Producer-Consumer Problem · Why stop/suspend/resume are Deprecated · Thread Join · Thread Priority · Daemon Threads
Table of Contents
- Producer-Consumer Problem
- Why stop(), suspend(), and resume() Are Deprecated
- Thread Joining
- Thread Priority
- Daemon Threads
- Summary and Interview Notes
- Practice Questions
1. Producer-Consumer Problem
Overview
The Producer-Consumer problem is one of the most classic concurrency problems in computer science. It models a very common real-world scenario: one or more threads produce data, and one or more threads consume that data, with both operating on a shared, bounded buffer (queue).
This problem tests your understanding of thread coordination using wait(), notify(), and the monitor lock — concepts covered in Part 2.
Problem Statement
- There is a shared queue with a fixed maximum capacity (buffer size).
- A Producer thread generates items and places them into the queue.
- A Consumer thread removes items from the queue.
- If the queue is full, the producer must wait — there is no room to add items.
- If the queue is empty, the consumer must wait — there is nothing to consume.
- When the producer adds an item, it must notify any waiting consumer.
- When the consumer removes an item, it must notify any waiting producer (freeing up space).
Why This Problem Matters
Without proper coordination:
- A producer might overflow the queue (adding past capacity).
- A consumer might try to consume from an empty queue (reading garbage data or crashing).
- Both conditions cause data corruption or incorrect program behavior.
The solution demonstrates wait() and notify() used correctly on a shared object's monitor lock.
Real-World Analogy
Think of a restaurant kitchen:
- The chef (producer) prepares dishes and places them on a service counter (the queue).
- The waiter (consumer) picks dishes from the counter to deliver to tables.
- If the counter is full, the chef must stop cooking and wait for space.
- If the counter is empty, the waiter must wait until food is ready.
- When the chef places a dish, they ring a bell (notify). When the waiter clears a dish, they ring the bell (notify).
Implementation
Step 1: The Shared Resource (SharedBuffer)
1import java.util.LinkedList;2import java.util.Queue;3
4public class SharedBuffer {5
6 private final Queue<Integer> queue = new LinkedList<>();7 private final int bufferSize;8
9 public SharedBuffer(int bufferSize) {10 this.bufferSize = bufferSize;11 }12
13 // Producer calls this method14 public synchronized void produce(int item) throws InterruptedException {15
16 // If buffer is full, producer must wait17 while (queue.size() == bufferSize) {18 System.out.println("Buffer full. Producer waiting...");19 wait(); // releases the monitor lock and waits20 }21
22 queue.add(item);23 System.out.println("Produced: " + item + " | Queue: " + queue);24
25 // Notify any waiting consumer that an item is now available26 notify();27 }28
29 // Consumer calls this method30 public synchronized void consume() throws InterruptedException {31
32 // If buffer is empty, consumer must wait33 while (queue.isEmpty()) {34 System.out.println("Buffer empty. Consumer waiting...");35 wait(); // releases the monitor lock and waits36 }37
38 int item = queue.poll();39 System.out.println("Consumed: " + item + " | Queue: " + queue);40
41 // Notify any waiting producer that space is now available42 notify();43 }44}Line-by-Line Explanation
| Code | Explanation |
|---|---|
Queue | LinkedList is unbounded by default. We enforce a size limit manually using bufferSize. |
synchronized on both methods | Ensures only one thread (producer OR consumer) can be inside these methods at a time, using the SharedBuffer object's monitor lock. |
while (queue.size() == bufferSize) | Uses while (not if) to re-check the condition after being woken up — protects against spurious wakeups. |
wait() | Releases the monitor lock and suspends the calling thread until notify() is called on the same object. |
queue.add(item) | Adds the produced item to the queue. |
notify() | Wakes up one thread waiting on this object's monitor. The awakened thread then races to re-acquire the lock. |
queue.poll() | Removes and returns the head of the queue. |
while instead of if when calling wait(). After a thread is notified and wakes up, it should re-check the condition, because another thread might have changed the state between the notify() and when the waiting thread re-acquires the lock. This is called a spurious wakeup guard.Step 2: The Main Class (Producer and Consumer Threads)
1public class ProducerConsumerDemo {2
3 public static void main(String[] args) {4
5 SharedBuffer sharedBuffer = new SharedBuffer(3); // Queue capacity = 36
7 // Producer Thread: produces 6 items8 Thread producerThread = new Thread(() -> {9 for (int i = 1; i <= 6; i++) {10 try {11 sharedBuffer.produce(i);12 } catch (InterruptedException e) {13 Thread.currentThread().interrupt();14 }15 }16 });17
18 // Consumer Thread: consumes 6 items19 Thread consumerThread = new Thread(() -> {20 for (int i = 1; i <= 6; i++) {21 try {22 sharedBuffer.consume();23 } catch (InterruptedException e) {24 Thread.currentThread().interrupt();25 }26 }27 });28
29 producerThread.start();30 consumerThread.start();31 }32}Sample Output (may vary due to thread scheduling):
1Produced: 1 | Queue: [1]2Produced: 2 | Queue: [1, 2]3Produced: 3 | Queue: [1, 2, 3]4Buffer full. Producer waiting...5Consumed: 1 | Queue: [2, 3]6Produced: 4 | Queue: [2, 3, 4]7Buffer full. Producer waiting...8Consumed: 2 | Queue: [3, 4]9Produced: 5 | Queue: [3, 4, 5]10Buffer full. Producer waiting...11Consumed: 3 | Queue: [4, 5]12Produced: 6 | Queue: [4, 5, 6]13Consumed: 4 | Queue: [5, 6]14Consumed: 5 | Queue: [6]15Consumed: 6 | Queue: []Step-by-Step Execution Walkthrough
Memory Diagram: What's Shared
1Process (JVM Instance)2┌──────────────────────────────────────────────┐3│ Heap (SHARED) │4│ ┌─────────────────────────────────────────┐ │5│ │ sharedBuffer object │ │6│ │ - queue: [1, 2, 3] │ │7│ │ - bufferSize: 3 │ │8│ │ - monitor lock (held by one thread) │ │9│ └─────────────────────────────────────────┘ │10│ │11│ Producer Thread │ Consumer Thread │12│ - own Stack │ - own Stack │13│ - own PC │ - own PC │14│ - own Registers │ - own Registers │15└──────────────────────────────────────────────┘Key Observations
produce()andconsume()are bothsynchronizedon the same object (sharedBuffer). Even though they are different methods, only one thread can holdsharedBuffer's monitor lock at a time.wait()inside asynchronizedmethod releases the lock so the other thread can enter.notify()does not immediately give the lock to the awakened thread — it just moves that thread from the wait set to the ready queue. The awakened thread must still compete for the lock.
2. Why stop(), suspend(), and resume() Are Deprecated
Overview
Java's Thread class originally provided three methods for controlling thread execution: stop(), suspend(), and resume(). All three are deprecated — meaning Java strongly discourages their use and they may be removed in a future version. Understanding why they are dangerous is a very common interview question.
The Thread Lifecycle (Quick Recap)
The key state to understand is Terminated: once a thread reaches this state, it cannot be brought back. It is permanently dead.
Why `stop()` is Deprecated
What it does
thread.stop() immediately kills the thread, regardless of what it is doing at that moment.
The Problem: No Lock Release, No Cleanup
When stop() is called:
- The thread is terminated abruptly.
- Any monitor locks (synchronized blocks) the thread currently holds are NOT released.
- Any resource cleanup (closing files, releasing connections) does NOT happen.
Deadlock Scenario with `stop()`
1Thread 1: acquires lock on Resource R12Thread 2: waiting for lock on Resource R13
4→ Main thread calls thread1.stop()5→ Thread 1 is killed abruptly6→ Lock on R1 is NEVER released7→ Thread 2 waits forever → DEADLOCKCorrect Alternative
Instead of stop(), use a volatile flag to signal the thread to stop gracefully:
1public class GracefulStop implements Runnable {2
3 // volatile ensures visibility across threads4 private volatile boolean running = true;5
6 public void stop() {7 running = false; // signal to stop8 }9
10 @Override11 public void run() {12 while (running) {13 // do work14 System.out.println("Working...");15 try {16 Thread.sleep(500);17 } catch (InterruptedException e) {18 Thread.currentThread().interrupt();19 break;20 }21 }22 // Cleanup happens here — locks released, resources closed properly23 System.out.println("Thread stopped gracefully.");24 }25}26
27// Usage:28GracefulStop task = new GracefulStop();29Thread t = new Thread(task);30t.start();31
32Thread.sleep(2000);33task.stop(); // signals the thread to stop at its next safe checkpointWorking... Working... Working... Working... Thread stopped gracefully.
volatile keyword ensures that when one thread writes to running, other threads immediately see the updated value. Without volatile, each thread might cache its own copy of the variable and never see the update.Why `suspend()` is Deprecated
What it does
thread.suspend() pauses a thread, halting its execution until resume() is called.
The Problem: suspend() Does NOT Release Locks
Unlike wait(), which releases the monitor lock when a thread is suspended, suspend() does NOT release any locks the thread currently holds.
| Method | Releases lock? | Can return to active state? |
|---|---|---|
wait() | ✅ Yes | ✅ Yes, via notify() |
suspend() | ❌ No | ✅ Yes, via resume() — but risky |
stop() | ❌ No | ❌ No — thread is terminated |
Deadlock Scenario with `suspend()`
1Thread 1: acquires lock on Resource R1, then gets suspended2Thread 2: waiting for lock on Resource R13
4→ Thread 1 is suspended but still holds the lock5→ Thread 2 waits forever → DEADLOCKDemonstration (Why You Should Never Use This in Production)
1public class SuspendResumeDemo {2
3 public static void main(String[] args) throws InterruptedException {4
5 SharedResource resource = new SharedResource();6
7 Thread thread1 = new Thread(() -> {8 System.out.println("Thread-1: calling produce (acquiring lock)");9 resource.produce();10 });11
12 Thread thread2 = new Thread(() -> {13 try {14 Thread.sleep(1000); // Wait for Thread-1 to acquire the lock first15 } catch (InterruptedException e) {16 Thread.currentThread().interrupt();17 }18 System.out.println("Thread-2: trying to acquire lock...");19 resource.produce(); // Will wait for lock20 });21
22 thread1.start();23 thread2.start();24
25 // Main waits 3 seconds, then suspends Thread-126 Thread.sleep(3000);27 System.out.println("Main: suspending Thread-1");28 thread1.suspend(); // ⚠️ DEPRECATED — Thread-1 suspended but LOCK NOT RELEASED29
30 System.out.println("Main: finishing");31 // Thread-2 is now in DEADLOCK — will wait forever for Thread-1's lock32
33 // If we call thread1.resume() here, Thread-1 finishes, releases lock, Thread-2 proceeds34 // Thread.sleep(3000);35 // thread1.resume(); // ⚠️ DEPRECATED36 }37}38
39class SharedResource {40 public synchronized void produce() {41 System.out.println(Thread.currentThread().getName() + ": Lock acquired");42 try {43 Thread.sleep(8000); // Hold the lock for 8 seconds44 } catch (InterruptedException e) {45 Thread.currentThread().interrupt();46 }47 System.out.println(Thread.currentThread().getName() + ": Lock released");48 }49}Thread-1: calling produce (acquiring lock) Thread-0: Lock acquired Thread-2: trying to acquire lock... Main: suspending Thread-1 Main: finishing [Program hangs here — Thread-2 waits forever]
Output (with resume after 3 more seconds):
1Thread-1: calling produce (acquiring lock)2Thread-0: Lock acquired3Thread-2: trying to acquire lock...4Main: suspending Thread-15[3 seconds pass]6Thread-0: Lock released ← Thread-1 resumes and finishes7Thread-1: Lock acquired ← Thread-2 finally gets the lock8Thread-1: Lock released9Main: finishingWhy `resume()` is Deprecated
resume() exists solely to undo the effect of suspend(). Since suspend() itself is deprecated and dangerous, resume() has no valid purpose and is deprecated by extension.
Summary: Deprecated Methods
| Method | Problem | Correct Alternative |
|---|---|---|
stop() | Kills thread abruptly; no lock release; no cleanup | Use a volatile boolean flag to stop gracefully |
suspend() | Pauses thread but does NOT release locks; causes deadlock | Use wait() which releases locks |
resume() | Only purpose was to resume a suspended thread | Use notify() / notifyAll() |
stop(), suspend(), and resume() still compile and run in modern Java (they are deprecated, not removed), never use them in production code. They are thread-safety hazards and may be removed in a future Java version.3. Thread Joining
Overview
thread.join() is a coordination mechanism that allows one thread to wait for another thread to finish before it continues execution.
Definition
Whenjoin()is invoked on a Thread object, the currently executing thread blocks and waits until the target thread completes its execution.
Real-World Analogy
Imagine you ask a colleague to complete a report. You say, "I'll wait here until you're done, then I'll review it." You are the calling thread; your colleague is the target thread. join() is you waiting.
How join() Works
1Without join():2
3Main Thread: ──────────────────────────────────────────────► (finishes early)4Thread-1: ──────────────────────────────────────────────► (completes later)5
6
7With thread1.join():8
9Main Thread: ───────────────[WAITING FOR THREAD-1]─────────────────────────────►10Thread-1: ────────────────────────────────────────────►11 ▲12 Main resumes hereCode Examples
Without join() Main finishes before Thread-1
1public class WithoutJoinDemo {2
3 public static void main(String[] args) throws InterruptedException {4
5 System.out.println("Main thread started");6
7 Thread thread1 = new Thread(() -> {8 System.out.println("Thread-1: started work");9 try {10 Thread.sleep(3000); // Simulate 3 seconds of work11 } catch (InterruptedException e) {12 Thread.currentThread().interrupt();13 }14 System.out.println("Thread-1: finished work");15 });16
17 thread1.start();18
19 // No join — main continues immediately20 System.out.println("Main thread finished");21 }22}Main thread started Main thread finished Thread-1: started work Thread-1: finished work
Main finishes before Thread-1 completes. The program stays alive until Thread-1 finishes (because Thread-1 is a user thread), but Main's final print happened early.
With join() Main waits for Thread-1
1public class WithJoinDemo {2
3 public static void main(String[] args) throws InterruptedException {4
5 System.out.println("Main thread started");6
7 Thread thread1 = new Thread(() -> {8 System.out.println("Thread-1: started work");9 try {10 Thread.sleep(3000);11 } catch (InterruptedException e) {12 Thread.currentThread().interrupt();13 }14 System.out.println("Thread-1: finished work");15 });16
17 thread1.start();18
19 System.out.println("Main thread: waiting for Thread-1 to finish...");20 thread1.join(); // Main blocks here until thread1 completes21 System.out.println("Main thread: Thread-1 is done. Main finishing now.");22 }23}Main thread started Main thread: waiting for Thread-1 to finish... Thread-1: started work Thread-1: finished work Main thread: Thread-1 is done. Main finishing now.
Advanced: Joining Multiple Threads Before Proceeding
1public class MultiJoinDemo {2
3 public static void main(String[] args) throws InterruptedException {4
5 System.out.println("Main: starting data pipeline");6
7 Thread fetchThread = new Thread(() -> {8 System.out.println("FetchThread: fetching data from API...");9 try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }10 System.out.println("FetchThread: done");11 });12
13 Thread validateThread = new Thread(() -> {14 System.out.println("ValidateThread: validating data...");15 try { Thread.sleep(1500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }16 System.out.println("ValidateThread: done");17 });18
19 fetchThread.start();20 validateThread.start();21
22 // Main must wait for BOTH threads before processing results23 fetchThread.join();24 validateThread.join();25
26 System.out.println("Main: all data ready. Starting final processing.");27 }28}Main: starting data pipeline FetchThread: fetching data from API... ValidateThread: validating data... ValidateThread: done FetchThread: done Main: all data ready. Starting final processing.
join() waits for that specific thread to finish. By calling join() on multiple threads sequentially, you ensure all of them have completed before the main thread proceeds.join() with Timeout
You can specify a maximum wait time to avoid waiting forever:
1thread1.join(5000); // Wait at most 5000 milliseconds (5 seconds)2// Execution continues here whether thread1 finished or notFlowchart: join() Execution
Key Properties
| Property | Detail |
|---|---|
| Method signature | public final void join() throws InterruptedException |
| Who blocks? | The thread that calls join() |
| Who is waited for? | The thread object on which join() is called |
| Timeout variant | join(long millis) — waits at most the given time |
| Use case | Coordinate threads; ensure prerequisites complete before proceeding |
| Alternative | CountDownLatch, CompletableFuture for more complex coordination |
4. Thread Priority
Overview
Java allows you to assign a priority to each thread — a numeric hint to the thread scheduler about which threads should be preferred when the OS is deciding which thread to run next.
Priority Range
| Constant | Value | Meaning |
|---|---|---|
Thread.MIN_PRIORITY | 1 | Lowest priority |
Thread.NORM_PRIORITY | 5 | Default (normal) priority |
Thread.MAX_PRIORITY | 10 | Highest priority |
Setting and Getting Priority
1Thread thread1 = new Thread(() -> {2 System.out.println("Thread-1 running, priority: " + Thread.currentThread().getPriority());3});4
5Thread thread2 = new Thread(() -> {6 System.out.println("Thread-2 running, priority: " + Thread.currentThread().getPriority());7});8
9Thread thread3 = new Thread(() -> {10 System.out.println("Thread-3 running, priority: " + Thread.currentThread().getPriority());11});12
13thread1.setPriority(Thread.NORM_PRIORITY); // 514thread2.setPriority(Thread.MAX_PRIORITY); // 1015thread3.setPriority(Thread.MIN_PRIORITY); // 116
17thread1.start();18thread2.start();19thread3.start();Expected output (based on priority):
1Thread-2 running, priority: 102Thread-1 running, priority: 53Thread-3 running, priority: 1Actual output (may be completely different):
1Thread-1 running, priority: 52Thread-3 running, priority: 13Thread-2 running, priority: 10The Critical Rule: Priority Is a Hint, Not a Guarantee
The JVM scheduler may consider priorities when deciding which runnable thread to execute next — but it is under no obligation to strictly follow them. The underlying OS scheduler has its own priorities and policies that may override Java's hint.
Priority Inheritance
When a thread creates a new thread, the child thread inherits the parent's priority by default.
1public class PriorityInheritanceDemo {2 public static void main(String[] args) {3 // Main thread has NORM_PRIORITY (5) by default4 System.out.println("Main priority: " + Thread.currentThread().getPriority()); // 55
6 Thread child = new Thread(() -> {7 // Inherits main's priority of 5 unless explicitly set8 System.out.println("Child priority: " + Thread.currentThread().getPriority()); // 59 });10
11 child.start();12 }13}Should You Use Thread Priority in Practice?
No.
In real-world production code, thread priority is almost never used.
Reasons to avoid it:
- No guarantee: As shown, it doesn't enforce ordering.
- Platform-dependent: Behavior varies between JVM implementations and operating systems.
- Better alternatives exist:
ExecutorServicewith custom thread pools,PriorityBlockingQueue, or structured concurrency patterns give you actual control.
join(), CountDownLatch, Semaphore, etc.), not priority.Priority Summary Table
| Scenario | Recommendation |
|---|---|
| Need thread T1 to finish before T2 starts | Use t1.join() |
| Need to limit concurrency to N threads | Use Semaphore |
| Need tasks in a specific order | Use ExecutorService with single thread or CompletableFuture chain |
| Thread priority hint (best-effort) | setPriority() — but never rely on it |
5. Daemon Threads
Overview
Java threads are divided into two categories: user threads and daemon threads. Understanding daemon threads is essential for understanding the JVM's shutdown behavior.
Definition
A daemon thread is a background thread that exists to serve user threads. The JVM automatically terminates all daemon threads as soon as all user threads have finished execution.
Daemon threads are designed for background support tasks — they should not be doing critical work that must complete before the program exits.
Two Types of Threads
| Type | Description | JVM Shutdown Behavior |
|---|---|---|
| User Thread | Normal thread doing application work | JVM waits for ALL user threads to finish before shutting down |
| Daemon Thread | Background support thread | JVM terminates immediately when all user threads finish, regardless of daemon thread state |
How to Create a Daemon Thread
1Thread daemonThread = new Thread(() -> {2 // background work3});4
5daemonThread.setDaemon(true); // MUST be called BEFORE start()6daemonThread.start();setDaemon(true) must be called before start(). Calling it after start() throws an IllegalThreadStateException.Checking if a Thread is a Daemon Thread
1System.out.println(Thread.currentThread().isDaemon()); // false for main thread2System.out.println(daemonThread.isDaemon()); // trueCode Examples
Example 1: User Thread JVM Waits for It
1public class UserThreadDemo {2
3 public static void main(String[] args) {4 System.out.println("Main thread started");5
6 Thread userThread = new Thread(() -> {7 System.out.println("User thread: started");8 try {9 Thread.sleep(5000); // Simulate 5 seconds of work10 } catch (InterruptedException e) {11 Thread.currentThread().interrupt();12 }13 System.out.println("User thread: finished");14 });15
16 // userThread.setDaemon(false); // default — it's already a user thread17 userThread.start();18
19 System.out.println("Main thread: finished its work");20 // JVM does NOT exit here — it waits for userThread to finish21 }22}Main thread started Main thread: finished its work User thread: started User thread: finished [JVM exits here — after user thread completes]
Example 2: Daemon Thread JVM Does NOT Wait
1public class DaemonThreadDemo {2
3 public static void main(String[] args) throws InterruptedException {4 System.out.println("Main thread started");5
6 Thread daemonThread = new Thread(() -> {7 System.out.println("Daemon thread: started");8 try {9 Thread.sleep(5000); // Would take 5 seconds10 } catch (InterruptedException e) {11 Thread.currentThread().interrupt();12 }13 System.out.println("Daemon thread: finished"); // This may NEVER print!14 });15
16 daemonThread.setDaemon(true); // Mark as daemon BEFORE start()17 daemonThread.start();18
19 System.out.println("Main thread: finished its work");20 // JVM exits immediately — daemon thread is killed mid-execution21 }22}Main thread started Main thread: finished its work Daemon thread: started [JVM exits — daemon thread killed abruptly, "finished" may never print]
Example 3: Observing JVM Shutdown with Mixed Threads
1public class MixedThreadDemo {2
3 public static void main(String[] args) throws InterruptedException {4
5 // User thread — JVM will wait for this6 Thread userThread = new Thread(() -> {7 for (int i = 1; i <= 3; i++) {8 System.out.println("User thread: step " + i);9 try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }10 }11 System.out.println("User thread: done");12 });13
14 // Daemon thread — JVM will NOT wait for this15 Thread daemonThread = new Thread(() -> {16 int i = 0;17 while (true) { // Would run forever18 i++;19 System.out.println("Daemon thread: heartbeat " + i);20 try { Thread.sleep(300); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }21 }22 });23
24 daemonThread.setDaemon(true);25 userThread.start();26 daemonThread.start();27
28 System.out.println("Main: started both threads, now finishing");29 }30}Sample Output:
1Main: started both threads, now finishing2Daemon thread: heartbeat 13User thread: step 14Daemon thread: heartbeat 25User thread: step 26Daemon thread: heartbeat 37Daemon thread: heartbeat 48User thread: step 39User thread: done10[JVM exits — daemon thread killed. Did not reach heartbeat 5, 6, etc.]JVM Shutdown Logic
Real-World Use Cases for Daemon Threads
| Use Case | Explanation |
|---|---|
| Garbage Collector | The JVM's GC runs as a daemon thread. It works in the background reclaiming memory. When your program ends, GC stops too — no need for GC to finish a cycle first. |
| Auto-save | An editor auto-saves your work periodically in the background. When you close the editor (program ends), auto-save stops. |
| Logging | Background logging threads write application logs while the app runs. When the app exits, logging stops. |
| Heartbeat / Health Check | A thread that periodically pings a health endpoint runs as a daemon — it should stop when the app stops. |
| Cache Eviction | A background thread that periodically removes stale entries from a cache. |
Daemon Thread Inheritance
Like thread priority, daemon status is inherited from the parent thread. A thread created by a daemon thread is itself a daemon thread by default.
1Thread daemonParent = new Thread(() -> {2 Thread child = new Thread(() -> {3 System.out.println("Child is daemon: " + Thread.currentThread().isDaemon()); // true4 });5 child.start();6});7daemonParent.setDaemon(true);8daemonParent.start();Common Mistake: Calling setDaemon() After start()
1Thread t = new Thread(() -> { /* work */ });2t.start();3t.setDaemon(true); // ❌ WRONG — throws IllegalThreadStateExceptionCorrect approach:
1Thread t = new Thread(() -> { /* work */ });2t.setDaemon(true); // ✅ Set BEFORE start()3t.start();Daemon vs User Thread: Full Comparison
| Aspect | User Thread | Daemon Thread |
|---|---|---|
| Default | ✅ Yes — all threads are user threads by default | ❌ Must be explicitly set with setDaemon(true) |
| JVM shutdown | JVM waits for all user threads | JVM does NOT wait; kills daemon threads immediately |
| Use for | Core application logic | Background support tasks |
| Examples | Main thread, worker threads, business logic threads | GC, auto-save, logging, cache eviction |
| Cleanup on exit | Runs to completion | May be killed mid-execution |
| Inherits from parent? | ✅ Yes | ✅ Yes (if parent is daemon, child is daemon) |
6. Summary and Interview Notes
Quick-Reference Summary
| Concept | Key Point |
|---|---|
| Producer-Consumer | Shared bounded queue; producer waits when full; consumer waits when empty; use wait()/notify() on shared object |
stop() | Deprecated — kills thread abruptly without releasing locks, risking deadlock |
suspend() | Deprecated — pauses thread but does NOT release locks, risking deadlock |
resume() | Deprecated — only purpose was to resume suspended threads; deprecated with suspend() |
| Correct alternative to stop | volatile boolean flag; thread checks flag and exits gracefully |
| Correct alternative to suspend | wait() — pauses thread AND releases lock |
join() | Calling thread blocks until the target thread finishes; enables thread coordination |
join(millis) | Blocks at most millis milliseconds, then continues regardless |
| Thread priority | Range 1–10; hint to scheduler only; NO execution order guarantee; avoid relying on it |
| Priority inheritance | Child thread inherits parent's priority by default |
| User thread | Normal thread; JVM waits for all user threads before shutting down |
| Daemon thread | Background thread; JVM kills all daemon threads when last user thread ends |
| Daemon use cases | Garbage Collector, auto-save, logging, heartbeat, cache eviction |
setDaemon(true) | Must be called BEFORE start() |
Interview Notes
Q1: What is the Producer-Consumer problem and how do you solve it in Java?
The Producer-Consumer problem involves a producer thread adding items to a shared bounded buffer and a consumer thread removing items. If the buffer is full, the producer must wait; if empty, the consumer must wait. The solution uses a synchronized shared buffer class with wait() to pause threads when the condition isn't met, and notify() to wake them up when the condition changes. Always use while (not if) to re-check the condition after waking up, to guard against spurious wakeups.
Q2: Why are stop(), suspend(), and resume() deprecated?
stop() kills a thread abruptly without releasing any monitor locks it holds, which can cause deadlocks and leaves shared data in an inconsistent state. suspend() pauses a thread but also does not release locks — another thread waiting for the same lock will wait forever (deadlock). resume() is deprecated because its only purpose was to reverse suspend(). The correct alternatives are: a volatile boolean flag to gracefully stop threads, and wait()/notify() for pausing and resuming (which properly releases and reacquires locks).
Q3: What does join() do? When would you use it?
join() causes the calling thread to block until the thread it's called on finishes execution. It's used when you need to ensure one or more threads complete before the current thread proceeds — for example, waiting for a data-fetch thread and a validation thread to both complete before processing their results.
Q4: What is the difference between sleep() and wait() with respect to locks?
sleep() pauses the current thread for a given time but does NOT release any monitor locks. wait() pauses the current thread AND releases the monitor lock it holds, allowing other threads to enter the synchronized block.
Q5: Can thread priority guarantee execution order?
No. Thread priority is a hint to the JVM/OS scheduler, not a strict rule. The scheduler may ignore it. In practice, you will rarely if ever see priority-based ordering reliably enforced. Never design application logic that depends on thread priority.
Q6: What is a daemon thread? Give examples.
A daemon thread is a background thread that the JVM kills automatically when all user (non-daemon) threads have finished. Examples: Java's Garbage Collector, IDE auto-save functionality, background logging threads, cache eviction threads, heartbeat/health check threads.
Q7: What happens if you call setDaemon(true) after start()?
It throws an IllegalThreadStateException. setDaemon() must be called before start().
Q8: If main() finishes but a user thread is still running, does the JVM exit?
No. The JVM waits for all user threads to complete before shutting down. If instead the still-running thread were a daemon thread, the JVM would exit immediately after main() finishes.
7. Practice Questions
Easy
- What are the two conditions that cause the producer or consumer to call
wait()in the Producer-Consumer solution? - Why must
wait()always be called inside asynchronizedblock? - What is the difference between
stop()andwait()in terms of lock behavior? - What is the purpose of
thread.join()? - What are the three thread priority constants in Java and their values?
- What is a daemon thread? How do you create one?
- What happens to daemon threads when all user threads finish?
Medium
- Why should you use
whileinstead ofifwhen callingwait()in the Producer-Consumer solution? What is a spurious wakeup? - Explain how
suspend()can cause a deadlock. Write a scenario with two threads and one shared resource. - Write a program where the main thread starts a worker thread and waits for it to finish using
join(), then prints a summary. - If Thread-1 has priority 10 and Thread-2 has priority 1, is it guaranteed that Thread-1 will always run first? Explain.
- What happens to a daemon thread if it is in the middle of writing to a file when the last user thread finishes?
- Why is the Garbage Collector implemented as a daemon thread rather than a user thread?
- How does
notify()differ fromnotifyAll()? When would you use each?
Hard
- Extend the Producer-Consumer solution to support multiple producers and multiple consumers (e.g., 3 producers and 2 consumers). What changes are needed? Why is
notifyAll()safer thannotify()in this case? - Implement the same Producer-Consumer problem using
BlockingQueue(fromjava.util.concurrent) and compare the implementation complexity to the manualwait()/notify()solution. - Write a thread-safe task runner that: (a) accepts a list of tasks, (b) runs them in parallel, (c) waits for all of them to finish using
join(), and (d) prints a completion report. - Design a logging system where a daemon thread collects log messages from a queue and writes them to a file. Ensure that log messages are not lost when the application shuts down — what problem does this reveal about daemon threads, and how would you solve it?
- In the deprecated
suspend()example, if you never callresume(), the program hangs. What mechanism would you use to replace this behavior safely? Write the equivalent code usingwait()andnotify().
java.util.concurrent package — ExecutorService, ThreadPoolExecutor, Future, Callable, CountDownLatch, Semaphore, and BlockingQueue. These are the tools professional Java engineers use instead of raw threads.End of Part 3 — Java Multithreading & Concurrency
Mastery check
How well can you recall this?
Finished this lesson?