KNOWLEDGEWALA • LEARN TEACH GROW • JAVA INTERVIEW SERIES

Java Multithreading
& Concurrency

From what is a thread to deadlock, thread pools, CompletableFuture and real production systems — one tutorial you can read, learn, understand, and explain in an interview.

⏱ 90–120 min read📚 10 Chapters💻 18+ Runnable Programs🎯 Low → High Complexity🗣 Interview Lines Included

📑 Table of Contents

  1. Chapter 1 — Why Multithreading? Process vs Thread
  2. Chapter 2 — How to Create Threads: Thread, Runnable, Callable
  3. Chapter 3 — Thread Lifecycle, start() vs run(), sleep vs wait
  4. Chapter 4 — Race Condition & synchronized
  5. Chapter 5 — volatile, Atomic Classes & Java Memory Model
  6. Chapter 6 — wait / notify, Producer–Consumer & BlockingQueue
  7. Chapter 7 — ReentrantLock, Semaphore, ReadWriteLock
  8. Chapter 8 — Deadlock, Livelock & How to Fix It
  9. Chapter 9 — ExecutorService, Thread Pools, CountDownLatch, CompletableFuture
  10. Chapter 10 — Real-Time Systems: Rate Limiter, LRU Cache, ThreadLocal & Interview Plan

How to use this tutorial: For every topic — Theory → Problem → Easy Code → Why it fails → Optimized Code → Real-Time Use → What to say in interview. Type every code in your system and run it.

How To Read This Tutorial • For Everyone

Read This First — 2 Minutes That Will Save You 2 Hours

👩‍🎓 If you are a Student
Read only Analogy + Theory + Easy Code. Do not worry about optimized code on first read. Type the easy code, run it, see it fail or work. Then read optimized code.
👨‍💻 If you are Junior Developer
Read Problem → Easy → Optimized for every chapter. Focus on Chapter 4, 5, 6, 8. These 4 chapters cover 80% of interview questions.
🧑‍🏫 If you are Expert / Senior
Jump to Expert Notes + Trade-offs + Real Production Problems in each chapter. Focus on Chapter 7, 9, 10 + LeetCode Hard problems at the end.
🧑‍💼 If you are Non-Tech (Manager / HR / Product)
Read only Analogy + Real-Time Example + One-Line Interview Answer. Skip code. You will understand why engineers talk about deadlock, race, thread pool — without writing code.
Expert Tutor Rule: Never learn a concept without 3 things — 1) A story you can tell, 2) A problem that breaks without it, 3) A code you can type. This tutorial gives you all 3 for every topic.

The 3 Words That Explain All Concurrency

WordMeaning in Simple EnglishExample
AtomicityAll-or-nothing. Either full work happens, or nothing happens.Money transfer: debit + credit both happen, or none.
VisibilityIf one thread changes a value, other threads can see the new value.One thread sets stop = true, other thread stops.
OrderingSteps happen in the order you wrote them, not reordered by CPU / compiler.First create object, then publish it. Not reverse.

If you remember only these 3 words, you can answer 50% of concurrency questions. Every lock, volatile, atomic, queue exists to give you one or more of these 3 guarantees.

Chapter 1 • Beginner • Theory First

Why Multithreading? Process vs Thread

One application doing many things at the same time — without waiting.

1.1 Real-life analogy anyone can understand

Imagine a restaurant. One waiter takes order → goes to kitchen → waits → serves → takes next order. Customers wait long. This is single-threaded.

Now 5 waiters work together. While one waits in kitchen, others serve customers. This is multithreading. Same restaurant (process), many waiters (threads), shared kitchen (shared memory).

1.2 Process vs Thread — Interview Table

ProcessThread
Independent program. Has own memory.Small unit inside a process. Shares process memory.
Heavy — starting a process is costly.Light — starting a thread is cheap.
If one process crashes, others keep running.If one thread crashes, whole process can crash.
Example: Chrome + VS Code running together.Example: In Chrome, one thread loads page, one plays video.
Interview line: “A process has its own memory, a thread shares the memory of its process. Threads share Heap, each thread has its own Stack.”

1.3 Why do we need multithreading?

🌍 Real-time example: A food delivery app. When you open the app, it loads restaurants, offers, location, and ratings in parallel. If it loaded one by one, app would take 8 seconds. In parallel, it takes 2 seconds.

1.4 Problem Statement

Problem: Download 3 files one by one takes 3 seconds. Download them together should take 1 second. How?

Solution: Use 3 threads, one per file. This is the first idea of concurrency.

Chapter 2 • Beginner • Write Your First Thread

How to Create Threads: Thread, Runnable, Callable

There are 3 ways. Learn all 3 — interviewers ask the difference.

2.1 Way 1 — Extend Thread Class (Easy, but limited)

class MyThread extends Thread {
    public void run() {
        System.out.println("Hello from " + Thread.currentThread().getName());
    }
}
public class Demo1 {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start(); // creates new thread
        System.out.println("Hello from main");
    }
}

Problem: Java allows only one parent class. If you extend Thread, you cannot extend anything else. That is why this way is rarely used in production.

2.2 Way 2 — Implement Runnable (Recommended)

class MyTask implements Runnable {
    public void run() {
        System.out.println("Task running in " + Thread.currentThread().getName());
    }
}
public class Demo2 {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyTask(), "Worker-1");
        Thread t2 = new Thread(new MyTask(), "Worker-2");
        t1.start();
        t2.start();
        // Modern short form with Lambda
        new Thread(() -> System.out.println("Lambda thread"), "Worker-3").start();
    }
}
Why Runnable is better: Task (what to do) is separate from Thread (who does it). Same task can be given to many threads. This is composition over inheritance.

2.3 Way 3 — Callable + Future (When you need a result)

Problem: Runnable returns nothing. What if thread must calculate sum and return it?

import java.util.concurrent.*;
public class Demo3 {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Callable<Integer> task = () -> {
            int sum = 0;
            for (int i = 1; i <= 100; i++) sum += i;
            return sum;
        };
        Future<Integer> future = pool.submit(task);
        System.out.println("Doing other work...");
        System.out.println("Result = " + future.get()); // blocks, returns 5050
        pool.shutdown();
    }
}
RunnableCallable
Returns voidReturns a value
Cannot throw checked exceptionCan throw exception
Use with Thread or ExecutorUse with Executor + Future
🗣 Interview Q: Difference between Runnable and Callable? Answer: “Runnable returns nothing, Callable returns a value via Future and can throw checked exceptions.”
Chapter 3 • Beginner • Lifecycle

Thread Lifecycle, start() vs run(), sleep vs wait

3.1 Lifecycle — 5 States

NEW
→
RUNNABLE
→
BLOCKED / WAITING
→
TERMINATED

3.2 start() vs run() — Most Asked Trap

Thread t = new Thread(() -> System.out.println("Hi"));
t.start(); // CORRECT: creates new OS thread, calls run() in new thread
t.run();   // WRONG: just a normal method call, runs in same main thread
Remember: If you call run() directly, there is no multithreading. Always call start(). Calling start() twice throws IllegalThreadStateException.

3.3 sleep() vs wait() vs join() vs yield()

MethodReleases Lock?Where Used?Meaning
sleep(1000)NoAnywherePause thread for time
wait()YesInside synchronized onlyWait until notify()
join()NoOn thread objectMain waits for thread to finish
yield()NoAnywhereHint: give CPU to other thread
Thread t = new Thread(() -> {
    try { Thread.sleep(1000); } catch (Exception e) {}
    System.out.println("Worker done");
});
t.start();
t.join(); // main waits here until worker finishes
System.out.println("Main continues after worker");
🗣 Interview Q: Difference between wait() and sleep()? Answer: “wait() releases the lock and must be inside synchronized, wakes on notify(). sleep() holds the lock, just pauses for time.”

3.4 Daemon vs User Thread

User thread: JVM waits for it. Example: main thread. Daemon thread: JVM does not wait. Example: Garbage Collector, background cleanup. Set with t.setDaemon(true) before start().

Chapter 4 • Intermediate • The Core Problem

Race Condition & synchronized

This is the #1 reason multithreading is hard. Understand this chapter deeply.

🏪 Non-Tech Analogy — Two Cashiers, One Last T-Shirt: A shop has 1 T-shirt left. Two cashiers both check stock at same time — both see “1 left”. Both sell it. Now shop sold 2 shirts but had only 1. This is race condition. Solution: Only one cashier can check + sell at a time — that is a lock.
🧑‍🏫 Expert Note — Why count++ is 3 bytecode instructions: GETFIELD → ICONST_1 + IADD → PUTFIELD. Between GET and PUT, another thread can run. This is called a check-then-act race. The fix is to make check + act atomic — either with a lock or with CAS. In production, prefer LongAdder over AtomicLong when contention is very high — it uses multiple cells to reduce CAS failures.

4.1 Problem Statement — The Lost Update

Problem: 100 threads, each increments a counter 1000 times. Expected = 100,000. But you get 97,432 or 98,101. Why?

Root cause: count++ is NOT one step. It is 3 steps: 1) Read count → 2) Increment → 3) Write count. Two threads can read the same value at the same time, so one increment is lost.

Dry run: count = 10. Thread A reads 10. Thread B reads 10. Both make it 11. Both write 11. Expected 12, got 11. One lost.

4.2 Easy Code — WRONG, Has Race

class CounterWrong {
    int count = 0;
    void increment() { count++; }
}
public class RaceDemo {
    public static void main(String[] args) throws Exception {
        CounterWrong c = new CounterWrong();
        Thread[] ts = new Thread[100];
        for (int i = 0; i < 100; i++) {
            ts[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) c.increment();
            });
            ts[i].start();
        }
        for (Thread t : ts) t.join();
        System.out.println("Expected 100000, Got " + c.count); // Less than 100000
    }
}

4.3 Optimized Code — synchronized

class CounterSafe {
    int count = 0;
    synchronized void increment() { count++; } // only 1 thread at a time
    synchronized int get() { return count; }
}

How synchronized works: Every object has a lock (monitor). When a thread enters a synchronized method, it takes the lock. Other threads wait outside. When it exits, lock is released. This gives Mutual Exclusion + Visibility.

4.4 synchronized Method vs Block — Which to Use?

class BankAccount {
    int balance = 1000;
    // Method lock: locks whole object (this) - coarse, slower
    synchronized void withdrawMethod(int amt) { balance -= amt; }

    // Block lock: locks only critical part - finer, faster
    void withdrawBlock(int amt) {
        // Non-critical work: validation, logging - no lock needed
        if (amt > balance) return;
        synchronized (this) {
            balance -= amt; // only this line needs lock
        }
    }
    // Separate lock object - best practice
    private final Object lock = new Object();
    void deposit(int amt) {
        synchronized (lock) { balance += amt; }
    }
}
Interview line: “Use synchronized block, not method, to reduce lock scope. Smaller critical section = more parallelism = better performance.”
🌍 Real-time problem: Ticket booking. 2 users book the last seat at same time. Without synchronized, both see seat available, both book, seat is double-booked. With synchronized, second user waits, sees seat gone, gets “Sold Out”. This is why banking, tickets, and inventory must be synchronized.

4.5 Static synchronized

static synchronized locks on Class object, not on instance. Two different objects still block each other for static method. Use for static counters.

Chapter 5 • Intermediate • Memory Model

volatile, Atomic Classes & Java Memory Model

synchronized is not the only tool. Learn when to use lighter tools.

📝 Non-Tech Analogy — Two Notebooks: Two people have their own notebooks (CPU cache) + one whiteboard (main memory). Person A writes “Price = 100” in her notebook but forgets to copy to whiteboard. Person B looks at whiteboard, still sees old price 90. volatile means “always write to whiteboard immediately, always read from whiteboard.” No private notebook.

5.1 Java Memory Model — Simple Explanation

Short Theory — Happens-Before: Java guarantees: if Thread A writes to a volatile variable, and Thread B later reads that same volatile variable, then B will see all writes A did before that volatile write. This is called happens-before. It is the formal rule behind volatile, synchronized, and thread start/join.

Each CPU has its own cache. Main memory is shared. Without proper synchronization, Thread A writes to its cache, Thread B still sees old value from its cache. This is a visibility problem.

Solution: volatile, synchronized, or Atomic forces read/write to main memory.

5.2 volatile — Visibility, NOT Atomicity

// PROBLEM: Thread 2 may loop forever, never sees flag = true
class FlagWrong {
    static boolean flag = false;
    public static void main(String[] args) throws Exception {
        new Thread(() -> { while (!flag) {} System.out.println("Saw flag"); }).start();
        Thread.sleep(1000);
        flag = true; // may stay in CPU cache, other thread does not see
    }
}
// FIX: volatile forces read from main memory every time
class FlagCorrect {
    static volatile boolean flag = false;
    public static void main(String[] args) throws Exception {
        new Thread(() -> { while (!flag) {} System.out.println("Saw flag"); }).start();
        Thread.sleep(1000);
        flag = true;
    }
}
Common mistake: volatile int i; i++ is still NOT thread-safe. volatile gives visibility, but i++ is 3 steps. Use AtomicInteger for i++.

5.3 Atomic Classes — CAS, No Lock, Fast

import java.util.concurrent.atomic.AtomicInteger;
class CounterAtomic {
    AtomicInteger count = new AtomicInteger(0);
    void increment() { count.incrementAndGet(); } // CAS - hardware atomic
    int get() { return count.get(); }
}

How CAS works: Compare-And-Swap. CPU checks: “Is current value still what I read?” If yes, swap to new value. If no, retry. No thread is blocked, so it is faster than synchronized for simple counters.

ToolVisibility?Atomicity?Use When
volatileYesNoFlag, stop signal, single write
AtomicIntegerYesYes (for single var)Counter, ID generator
synchronizedYesYes (for block)Multiple variables, complex logic
🗣 Interview Q: volatile vs synchronized vs Atomic? Answer: “volatile = visibility only. Atomic = visibility + atomic for one variable via CAS. synchronized = visibility + atomic + mutual exclusion for a block.”
🌍 Real-time: volatile boolean isRunning to stop a background thread. AtomicLong for request ID generator. synchronized for bank transfer (needs to update two accounts together).
Chapter 6 • Intermediate • Coordination

wait / notify, Producer–Consumer & BlockingQueue

Threads don’t just run alone — they must wait for each other and share work.

6.1 Problem Statement — Print Odd-Even

Problem: Thread-1 prints odd 1,3,5. Thread-2 prints even 2,4,6. Output must be 1,2,3,4,5 in order. How to coordinate?

Idea: Shared counter + lock. Odd thread prints only if number is odd, else waits. After printing, it notifies the other thread.

public class OddEven {
    int n = 1; final int MAX = 10; final Object lock = new Object();
    void printOdd() throws Exception {
        synchronized (lock) {
            while (n <= MAX) {
                if (n % 2 == 1) { System.out.println("Odd : " + n++); lock.notify(); }
                else lock.wait();
            }
        }
    }
    void printEven() throws Exception {
        synchronized (lock) {
            while (n <= MAX) {
                if (n % 2 == 0) { System.out.println("Even: " + n++); lock.notify(); }
                else lock.wait();
            }
        }
    }
    public static void main(String[] args) {
        OddEven o = new OddEven();
        new Thread(() -> { try { o.printOdd(); } catch (Exception e) {} }).start();
        new Thread(() -> { try { o.printEven(); } catch (Exception e) {} }).start();
    }
}
Why while, not if? Because of spurious wakeup — a thread can wake up without notify(). while re-checks the condition after waking. Always use while with wait().

6.2 Producer–Consumer — The Classic Problem

Problem: Producer makes items, Consumer eats them. Buffer size = 5. Producer must wait if full. Consumer must wait if empty.

Easy Way — BlockingQueue (Use in Production)

import java.util.concurrent.*;
public class ProducerConsumerEasy {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);
        Thread producer = new Thread(() -> {
            try { for (int i = 1; i <= 10; i++) { queue.put(i); System.out.println("Produced " + i); } }
            catch (Exception e) {}
        });
        Thread consumer = new Thread(() -> {
            try { for (int i = 1; i <= 10; i++) { int v = queue.take(); System.out.println("Consumed " + v); } }
            catch (Exception e) {}
        });
        producer.start(); consumer.start();
    }
}

put() blocks if full. take() blocks if empty. No manual wait/notify needed.

Hard Way — wait() / notify() (If Interviewer Forces You)

class Buffer {
    int data; boolean empty = true;
    synchronized void put(int v) throws Exception {
        while (!empty) wait();
        data = v; empty = false; notify();
    }
    synchronized int take() throws Exception {
        while (empty) wait();
        empty = true; notify(); return data;
    }
}
🌍 Real-time: Video processing, order processing, log processing. Producer (API) puts orders in queue, Consumer (worker) processes them. Queue decouples fast API from slow processing. This is how Swiggy / e-commerce order pipelines work.

⭐ LeetCode 1115 — Print FooBar Alternately (Famous Interview Problem)

Problem: Two threads. One prints “foo”, other prints “bar”. Output must be foobarfoobar… n times. Same idea as Odd-Even, but with words.

Concept: Turn-taking with Semaphore. Foo starts with 1 permit, Bar with 0.

import java.util.concurrent.Semaphore;
class FooBar {
    private int n;
    private Semaphore fooSem = new Semaphore(1);
    private Semaphore barSem = new Semaphore(0);
    public FooBar(int n) { this.n = n; }
    public void foo(Runnable printFoo) throws Exception {
        for (int i = 0; i < n; i++) {
            fooSem.acquire(); printFoo.run(); barSem.release();
        }
    }
    public void bar(Runnable printBar) throws Exception {
        for (int i = 0; i < n; i++) {
            barSem.acquire(); printBar.run(); fooSem.release();
        }
    }
}

What to say: “I use Semaphore as a token. Foo holds token first. After printing, it passes token to Bar. No busy waiting, no missed signal.”

6.3 notify() vs notifyAll()

notify(): Wakes ONE waiting thread (random). notifyAll(): Wakes ALL waiting threads. Use notifyAll() when there are 3+ threads or different conditions, otherwise wrong thread may wake up and deadlock.

Chapter 7 • Intermediate to Advanced • Locks

ReentrantLock, Semaphore, ReadWriteLock

synchronized is simple, but sometimes you need more control — timeout, fairness, try-lock.

7.1 synchronized vs ReentrantLock

FeaturesynchronizedReentrantLock
ReleaseAutomaticManual in finally
TimeoutNo, waits foreverYes, tryLock(1, SECONDS)
InterruptNoYes, lockInterruptibly()
FairnessNoYes, new ReentrantLock(true)
Multiple wait-setsOneMultiple Condition
import java.util.concurrent.locks.*;
class AccountLock {
    private int balance = 1000;
    private final ReentrantLock lock = new ReentrantLock();
    void withdraw(int amt) {
        lock.lock(); // must unlock in finally
        try { if (balance >= amt) balance -= amt; }
        finally { lock.unlock(); }
    }
    boolean tryWithdraw(int amt) throws Exception {
        if (lock.tryLock(1, TimeUnit.SECONDS)) {
            try { if (balance >= amt) { balance -= amt; return true; } }
            finally { lock.unlock(); }
        }
        return false; // could not get lock in 1 sec, do not wait forever
    }
}

7.2 Semaphore — Permit Counter, Not a Lock

Idea: Semaphore(3) means only 3 threads can enter at once. 4th thread waits. Good for limiting concurrency.

import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
    static Semaphore pool = new Semaphore(3); // only 3 DB connections
    public static void main(String[] args) {
        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                try {
                    pool.acquire(); // take permit
                    System.out.println(Thread.currentThread().getName() + " using DB");
                    Thread.sleep(1000);
                } catch (Exception e) {}
                finally { pool.release(); } // return permit
            }).start();
        }
    }
}
🌍 Real-time: Limit API calls to 100 per second, limit DB connections to 10, limit file uploads to 5 at once. Semaphore is the tool.

7.3 ReadWriteLock — Many Readers, One Writer

import java.util.concurrent.locks.*;
public class CacheRW {
    private final ReadWriteLock rw = new ReentrantReadWriteLock();
    private String data = "v1";
    String read() {
        rw.readLock().lock();
        try { return data; } finally { rw.readLock().unlock(); }
    }
    void write(String v) {
        rw.writeLock().lock();
        try { data = v; } finally { rw.writeLock().unlock(); }
    }
}

Why? Reading can happen in parallel — 100 readers together is safe. Writing must be exclusive. Perfect for read-heavy cache: config, product details, user profile.

🗣 Interview Q: When to use which? Answer: “Simple mutual exclusion → synchronized. Need timeout / fairness / tryLock → ReentrantLock. Limit concurrency → Semaphore. Read-heavy → ReadWriteLock.”
Chapter 8 • Advanced • Must Master

Deadlock, Livelock & How to Fix It

The most asked multithreading coding question. Learn to write it, run it, and fix it.

8.1 What is Deadlock?

Two threads wait for each other forever. Program hangs, no error, no progress.

8.2 4 Conditions — Break Any One, Deadlock Gone

  1. Mutual Exclusion: Resource can be used by one thread at a time.
  2. Hold & Wait: Thread holds one lock, waits for another.
  3. No Preemption: Lock cannot be taken forcibly.
  4. Circular Wait: T1 waits for T2, T2 waits for T1 — a circle.

8.3 Code That Deadlocks — Type & Run, It Will Hang

public class DeadlockDemo {
    static final Object lock1 = new Object();
    static final Object lock2 = new Object();
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (lock1) {
                System.out.println("T1 got lock1");
                sleep(100);
                synchronized (lock2) { System.out.println("T1 got lock2"); }
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized (lock2) { // OPPOSITE ORDER
                System.out.println("T2 got lock2");
                sleep(100);
                synchronized (lock1) { System.out.println("T2 got lock1"); }
            }
        });
        t1.start(); t2.start();
    }
    static void sleep(int ms){ try{ Thread.sleep(ms);}catch(Exception e){} }
}

What happens: T1 holds lock1, waits for lock2. T2 holds lock2, waits for lock1. Both wait forever.

8.4 Fix 1 — Same Lock Order (Easiest)

// Both threads take lock1 FIRST, then lock2 - no circle
Thread t2Fixed = new Thread(() -> {
    synchronized (lock1) {
        sleep(100);
        synchronized (lock2) { /* work */ }
    }
});

8.5 Fix 2 — tryLock with Timeout (Best Answer)

import java.util.concurrent.locks.*;
import java.util.concurrent.TimeUnit;
public class DeadlockFix {
    static ReentrantLock l1 = new ReentrantLock();
    static ReentrantLock l2 = new ReentrantLock();
    public static void main(String[] args) {
        Runnable task = () -> {
            try {
                if (l1.tryLock(1, TimeUnit.SECONDS)) {
                    try {
                        Thread.sleep(100);
                        if (l2.tryLock(1, TimeUnit.SECONDS)) {
                            try { System.out.println("Got both locks"); }
                            finally { l2.unlock(); }
                        } else System.out.println("Could not get l2, releasing l1");
                    } finally { l1.unlock(); }
                }
            } catch (Exception e) {}
        };
        new Thread(task).start();
        new Thread(task).start();
    }
}

Why tryLock works: It breaks Hold & Wait. If second lock is not available in 1 second, release first lock and retry. No indefinite waiting.

⭐ LeetCode 1226 — Dining Philosophers (Famous Deadlock Problem)

Problem: 5 philosophers, 5 forks. Each needs 2 forks to eat. If all pick left fork at same time → deadlock. This is exactly the deadlock chapter in real form.

Solution in 1 line: Make the last philosopher pick forks in opposite order — break the circle.

class DiningPhilosophers {
    // Each fork is a Semaphore(1) or ReentrantLock
    // Philosopher i picks fork i and fork (i+1)%5
    // Philosopher 4 picks fork 0 first, then fork 4 — opposite order
    // No circle → No deadlock
    public void wantsToEat(int philosopher,
        Runnable pickLeft, Runnable pickRight,
        Runnable eat, Runnable putLeft, Runnable putRight) throws Exception {
        // Implementation uses locks in fixed global order for 0-3,
        // reverse order for philosopher 4. See Chapter 8 Fix 1.
        // In interview, explain the idea — code can be pseudo-code + locks.
    }
}

Expert Note: Other valid fixes: Allow only 4 philosophers to sit at once (Semaphore 4), or use tryLock with timeout and put down forks and retry. All 3 break one of the 4 deadlock conditions.

8.6 How to Detect Deadlock in Production?

Livelock vs Deadlock vs Starvation:
Deadlock: Both stuck, no progress.
Livelock: Both keep moving but no progress — like two people in corridor both stepping aside repeatedly.
Starvation: One thread never gets lock because others always get it first. Fix with fair lock.
🌍 Real-time: Bank transfer: Transfer A→B and B→A at same time. If both lock source account first, deadlock. Fix: Always lock accounts in order of account ID (smaller ID first). This is used in real banking systems.
Chapter 9 • Advanced • Production Tools

ExecutorService, Thread Pools, CountDownLatch, CompletableFuture

Never create threads manually in production. Use a pool.

9.1 Why Not new Thread() Every Time?

Creating a thread is costly. If 10,000 requests create 10,000 threads, system runs out of memory (OOM) and crashes. Thread Pool reuses a fixed set of threads.

9.2 ExecutorService — Correct Way

import java.util.concurrent.*;
public class ThreadPoolDemo {
    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
            3, 5, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10), // bounded queue - prevents OOM
            new ThreadPoolExecutor.CallerRunsPolicy()
        );
        for (int i = 1; i <= 10; i++) {
            int id = i;
            pool.submit(() -> System.out.println("Task " + id + " by " + Thread.currentThread().getName()));
        }
        pool.shutdown();
        pool.awaitTermination(10, TimeUnit.SECONDS);
    }
}

9.3 How to Size a Thread Pool? — Interview Favourite

CPU-Bound Work
Image processing, calculation
threads = cores + 1
Example: 8 cores → 9 threads
I/O-Bound Work
DB, network, file
threads = cores × (1 + wait / compute)
Example: 8 cores, 90% wait → 8×10 = 80 threads
Never use: Executors.newCachedThreadPool() in production — unbounded, can create 10,000 threads and crash. Always use bounded ThreadPoolExecutor.

9.4 CountDownLatch vs CyclicBarrier vs Semaphore

ToolOne LineExample
CountDownLatchMain waits for N workers. One-time.Start server only after 3 services are ready.
CyclicBarrierWorkers wait for each other. Reusable.3 friends meet, then go together, repeat.
SemaphoreLimit concurrency.Only 5 threads can use DB at once.
import java.util.concurrent.*;
public class LatchDemo {
    public static void main(String[] args) throws Exception {
        CountDownLatch latch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            new Thread(() -> { System.out.println("Worker done"); latch.countDown(); }).start();
        }
        latch.await(); // main waits here
        System.out.println("All workers done, main continues");
    }
}

9.5 CompletableFuture — Modern Async Java

Problem: Fetch user (1 sec) + orders (1 sec) + payments (1 sec) one by one = 3 sec. In parallel = 1 sec.

import java.util.concurrent.*;
public class AsyncDemo {
    public static void main(String[] args) throws Exception {
        CompletableFuture<String> userF = CompletableFuture.supplyAsync(() -> { sleep(1000); return "User"; });
        CompletableFuture<String> orderF = CompletableFuture.supplyAsync(() -> { sleep(1000); return "Orders"; });
        CompletableFuture<String> payF = CompletableFuture.supplyAsync(() -> { sleep(1000); return "Payments"; });
        String result = CompletableFuture.allOf(userF, orderF, payF)
            .thenApply(v -> userF.join() + " | " + orderF.join() + " | " + payF.join())
            .get(); // total 1 sec, not 3 sec
        System.out.println(result);
    }
    static void sleep(int ms){ try{ Thread.sleep(ms);}catch(Exception e){} }
}
🌍 Real-time: When you open an e-commerce app, it fetches profile, cart, offers, and recommendations in parallel with CompletableFuture. If one fails, others still work. This is modern backend design.

9.6 ConcurrentHashMap & CopyOnWriteArrayList

import java.util.concurrent.*;
public class ConcurrentMapDemo {
    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    public static void main(String[] args) {
        // Only one thread will load from DB, others wait and reuse
        Integer val = map.computeIfAbsent("user:101", k -> loadFromDB(k));
        System.out.println(val);
    }
    static Integer loadFromDB(String k){ return 999; }
}
Chapter 10 • Advanced • Real Systems + Interview Plan

Real-Time Systems: Rate Limiter, LRU Cache, ThreadLocal

10.1 ThreadLocal — Each Thread Has Own Copy

Problem: SimpleDateFormat is not thread-safe. If 2 threads share it, dates corrupt. Solution: Each thread gets its own copy.

import java.text.SimpleDateFormat;
import java.util.Date;
public class ThreadLocalDemo {
    private static ThreadLocal<SimpleDateFormat> formatter =
        ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
    public static void main(String[] args) {
        Runnable task = () -> System.out.println(formatter.get().format(new Date()));
        new Thread(task).start();
        new Thread(task).start();
    }
}

Real use: User context, transaction ID, DB connection per request in web apps. Remember to call remove() after use in thread pools, otherwise memory leak.

10.2 Rate Limiter — Token Bucket, Thread-Safe

Problem: Allow max 5 requests per user per 10 seconds. Prevent abuse.

import java.util.*;
import java.util.concurrent.*;
public class RateLimiter {
    private final Map<String, Deque<Long>> map = new ConcurrentHashMap<>();
    public boolean allow(String userId, int limit, long windowMs) {
        long now = System.currentTimeMillis();
        Deque<Long> q = map.computeIfAbsent(userId, k -> new ArrayDeque<>());
        synchronized (q) {
            while (!q.isEmpty() && now - q.peekFirst() > windowMs) q.pollFirst();
            if (q.size() < limit) { q.offerLast(now); return true; }
            return false;
        }
    }
}

Interview trade-off: Fixed Window = simple but burst at boundary. Sliding Window = accurate but memory heavy. Token Bucket = allows burst, smooth, best for APIs.

10.3 Thread-Safe LRU Cache

Problem: Cache with get() and put() in O(1), evict Least Recently Used when full. Must be thread-safe.

import java.util.*;
public class ThreadSafeLRU {
    private final int capacity;
    private final Map<Integer, Node> map = new HashMap<>();
    private final Node head = new Node(0,0), tail = new Node(0,0);
    public ThreadSafeLRU(int cap){ capacity=cap; head.next=tail; tail.prev=head; }
    public synchronized int get(int key){
        Node n = map.get(key);
        if (n == null) return -1;
        moveToHead(n); return n.value;
    }
    public synchronized void put(int key, int value){
        Node n = map.get(key);
        if (n != null) { n.value = value; moveToHead(n); }
        else {
            Node nn = new Node(key, value); map.put(key, nn); addToHead(nn);
            if (map.size() > capacity) { Node lru = tail.prev; removeNode(lru); map.remove(lru.key); }
        }
    }
    private void moveToHead(Node n){ removeNode(n); addToHead(n); }
    private void removeNode(Node n){ n.prev.next=n.next; n.next.prev=n.prev; }
    private void addToHead(Node n){ n.next=head.next; n.prev=head; head.next.prev=n; head.next=n; }
    static class Node{ int key,value; Node prev,next; Node(int k,int v){key=k;value=v;} }
}

Why HashMap + Doubly Linked List? HashMap gives O(1) lookup. Doubly Linked List gives O(1) move to head and O(1) remove tail. No shifting like ArrayList.

10.4 Common Mistakes Interviewers Catch

10.5 Rapid-Fire Revision — Speak in 10 Seconds Each

QuestionOne-Line Answer
Deadlock?Two threads wait for each other’s lock. Fix: same lock order / tryLock.
wait vs sleep?wait releases lock, sleep holds lock.
volatile?Visibility only, not atomicity.
AtomicInteger?CAS, atomic + visible, no lock.
CountDownLatch vs Barrier?Latch: main waits for workers, one-time. Barrier: workers wait for each other, reusable.
Semaphore?Permit counter, limits concurrency.
BlockingQueue?put blocks if full, take blocks if empty.
start vs run?start creates new thread, run is normal method.
Callable vs Runnable?Callable returns value, Runnable does not.

10.6 7-Day Practice Plan

Day 1: Thread + Runnable
Day 2: Race + synchronized
Day 3: volatile + Atomic
Day 4: Producer-Consumer + Odd-Even
Day 5: Deadlock + Fix
Day 6: Thread Pool + CompletableFuture
Day 7: Mock — 1 DSA + 1 Concurrency + 10 Rapid-Fire
Final Interview Tip: After coding, always say: “Let me test with edge cases: empty input, single thread, many threads, exception in critical section.” Interviewers note this.
Bonus • Famous Interview Problems • LeetCode Style

⭐ Famous LeetCode Multithreading Problems — With Concept + Solution

These 6 problems are asked again and again in interviews. If you can solve these, you can solve any coordination problem. They are ordered easy → hard.

1. LeetCode 1114 — Print in Order EASY

Problem: 3 methods — first(), second(), third(). 3 threads call them in random order. Output must always be first → second → third.

Concept: Ordering with CountDownLatch. Second waits for first, third waits for second.

import java.util.concurrent.CountDownLatch;
class Foo {
    CountDownLatch latch1 = new CountDownLatch(1);
    CountDownLatch latch2 = new CountDownLatch(1);
    public void first(Runnable printFirst) throws Exception {
        printFirst.run(); latch1.countDown();
    }
    public void second(Runnable printSecond) throws Exception {
        latch1.await(); printSecond.run(); latch2.countDown();
    }
    public void third(Runnable printThird) throws Exception {
        latch2.await(); printThird.run();
    }
}

Non-Tech Analogy: Relay race. Runner 2 cannot start until Runner 1 passes the baton. Latch is the baton.

2. LeetCode 1115 — Print FooBar Alternately EASY

Already solved in Chapter 6 with Semaphore. Alternative with synchronized: Use a boolean fooTurn + wait()/notify(). Semaphore version is cleaner and preferred in interviews.

Follow-up: What if n = 0? Loop does not run, no deadlock. What if you forget release()? Other thread waits forever — deadlock. Always release in finally if there is exception risk.

3. LeetCode 1116 — Print Zero Even Odd MEDIUM

Problem: 3 threads: zero() prints 0, even() prints even, odd() prints odd. Output for n=5 must be 0102030405. Zero always comes before a number.

Concept: State machine with 3 semaphores. Zero → Odd/Even → Zero → …

import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;
class ZeroEvenOdd {
    private int n;
    private Semaphore zeroSem = new Semaphore(1);
    private Semaphore oddSem = new Semaphore(0);
    private Semaphore evenSem = new Semaphore(0);
    public ZeroEvenOdd(int n) { this.n = n; }
    public void zero(IntConsumer printNumber) throws Exception {
        for (int i = 1; i <= n; i++) {
            zeroSem.acquire(); printNumber.accept(0);
            if (i % 2 == 1) oddSem.release(); else evenSem.release();
        }
    }
    public void even(IntConsumer printNumber) throws Exception {
        for (int i = 2; i <= n; i += 2) {
            evenSem.acquire(); printNumber.accept(i); zeroSem.release();
        }
    }
    public void odd(IntConsumer printNumber) throws Exception {
        for (int i = 1; i <= n; i += 2) {
            oddSem.acquire(); printNumber.accept(i); zeroSem.release();
        }
    }
}

What to say: “Zero is the coordinator. It decides whether odd or even goes next based on i. After number prints, it gives token back to zero.”

4. LeetCode 1117 — Building H2O MEDIUM

Problem: Threads call hydrogen() and oxygen(). To make water, need 2 H + 1 O. Output must be groups like HHO HHO. Never HHHO or HO.

Concept: Semaphore + Barrier. Allow 2 H + 1 O per group, then reset.

import java.util.concurrent.*;
class H2O {
    Semaphore hSem = new Semaphore(2); // allow 2 H
    Semaphore oSem = new Semaphore(1); // allow 1 O
    CyclicBarrier barrier = new CyclicBarrier(3); // wait for 3 to form H2O
    public void hydrogen(Runnable releaseHydrogen) throws Exception {
        hSem.acquire(); releaseHydrogen.run(); barrier.await(); hSem.release();
    }
    public void oxygen(Runnable releaseOxygen) throws Exception {
        oSem.acquire(); releaseOxygen.run(); barrier.await(); oSem.release();
    }
}

Non-Tech Analogy: Making a car needs 4 wheels + 1 engine. You cannot ship a car with 3 wheels. Barrier waits until all parts arrive.

Expert Note: Barrier is reusable — after 3 threads arrive, it resets for next H2O. That is why CyclicBarrier, not CountDownLatch (which is one-time).

5. LeetCode 1195 — FizzBuzz Multithreaded MEDIUM

Problem: 4 threads: fizz() prints “fizz” for multiples of 3, buzz() for multiples of 5, fizzbuzz() for multiples of 15, number() prints number otherwise. Output for n=15: 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz in order.

Concept: Shared counter + one lock + condition. Only the thread whose turn it is prints, others wait.

import java.util.function.IntConsumer;
class FizzBuzz {
    private int n; private int curr = 1;
    public FizzBuzz(int n) { this.n = n; }
    public synchronized void fizz(Runnable printFizz) throws Exception {
        while (curr <= n) {
            if (curr % 3 == 0 && curr % 5 != 0) { printFizz.run(); curr++; notifyAll(); }
            else wait();
        }
    }
    // buzz(), fizzbuzz(), number() follow same pattern:
    // buzz: curr%5==0 && curr%3!=0
    // fizzbuzz: curr%15==0
    // number: curr%3!=0 && curr%5!=0 → printNumber.accept(curr)
    public synchronized void number(IntConsumer printNumber) throws Exception {
        while (curr <= n) {
            if (curr % 3 != 0 && curr % 5 != 0) { printNumber.accept(curr++); notifyAll(); }
            else wait();
        }
    }
}

What to say: “One shared counter is the truth. Each thread checks: Is it my turn? If yes, print + increment + notifyAll. If no, wait. notifyAll is needed because we don’t know which thread is next.”

6. LeetCode 1226 — Dining Philosophers HARD

Already explained in Chapter 8. Interview twist: Interviewer may ask — “What if we use tryLock and if we fail, we put down forks and retry after random delay?” That is a valid fix. It breaks Hold & Wait and adds randomness to avoid livelock (where everyone retries at same time forever).

Real-Time Mapping: Philosophers = microservices. Forks = DB rows. Two services locking rows in opposite order = deadlock in production. Fix in production is same: lock rows in sorted order (ORDER BY id) always.

How to practice LeetCode problems for interview:
1) First write solution with synchronized + wait/notify — shows you understand basics.
2) Then rewrite with Semaphore / CountDownLatch / CyclicBarrier — shows you know modern tools.
3) Then explain trade-off: “Semaphore is cleaner, synchronized is more general.”
Interviewers give extra marks for knowing two ways to solve same problem.

Extra Theory — Short Concepts Interviewers Love to Ask

ConceptShort Theory (30 sec)Example
MonitorEvery Java object has a lock + wait-set. synchronized uses it. Only one thread can own monitor at a time.synchronized(obj){ obj.wait(); }
ReentrancySame thread can acquire same lock again without deadlock. Java locks are reentrant.Method A (sync) calls Method B (sync) on same object — works.
Spurious WakeupThread can wake from wait() without notify(). Always use while, not if.Odd-Even code uses while(n<=MAX).
Busy Waiting / Spin LockThread loops checking flag, wasting CPU. Better to wait() or use LockSupport.park().while(!ready){} = busy wait, bad.
Thread StarvationOne thread never gets lock because others always win. Fix with fair lock new ReentrantLock(true).Low-priority thread waiting forever.
Context SwitchCPU stops one thread, saves its state, starts another. Costs time. Too many threads = too many switches = slow.10000 threads slower than 100 threads.
Amda​hl’s LawIf 50% of work is sequential, even with infinite threads you can at most 2x speedup. Not all work can be parallelized.Reading file (sequential) + processing (parallel).
🧑‍🏫 Expert Deep-Dive — When synchronized is NOT enough:
• Need to lock across methods? Use explicit Lock.
• Need to cancel a waiting thread? Use lockInterruptibly().
• Need to read many times, write rarely? Use ReadWriteLock or StampedLock (Java 8+, optimistic read).
• Need high-throughput counter? Use LongAdder (splits counter into cells).
• Need to combine many async calls? Use CompletableFuture, not raw threads.
These are the answers that separate Junior from Senior in interviews.
🧑‍💼 For Non-Tech Readers — One Paragraph Summary of Whole Tutorial:
Computers do many things at once using threads. If two threads touch the same data at the same time without rules, data gets corrupted (race), or both get stuck waiting for each other (deadlock). Java gives rules — locks, queues, semaphores — to coordinate threads safely. Good engineers don’t just make code fast, they make it correct when 1000 people use it at once. That is why interviews focus on multithreading: it tests whether you can build systems that work in real life, not just on your laptop.
Advanced Deep-Dive • Complete Runnable Programs • Expert Tutor

Advanced Multithreading — ExecutorService, CompletableFuture & All Advanced Concepts With Complete Programs

Every topic below follows the same expert pattern: What is it? → What problem does it solve? → How to create its instance → Complete runnable program you can copy-paste → Step-by-step execution → Common mistake → Interview line. All programs are complete with main(), imports, and expected output. Copy, paste, run.

Why Advanced Topics Matter: Beginner topics prove you can write a thread. Advanced topics prove you can build a system that serves 10,000 users without crashing. That is what interviews test for Senior / SDE-2 roles.

1. ExecutorService — The Heart of Modern Java Concurrency

🏢 Non-Tech Analogy: A company does not hire a new employee for every single task and fire them after. It keeps a team (pool) of employees. Tasks come in a queue, team members pick tasks, finish, pick next. ExecutorService is that team manager.

Short Theory: ExecutorService is an interface. It separates what to run (task) from how to run (thread pool). You submit tasks, it manages threads for you.

What problem does it solve?

1.1 How to Create Instance — All 5 Ways (Must Know)

import java.util.concurrent.*;

// WAY 1: Fixed Pool — N threads, always. Best for most cases.
ExecutorService fixed = Executors.newFixedThreadPool(5);

// WAY 2: Cached Pool — Creates threads on demand, reuses idle. DANGEROUS if unbounded.
ExecutorService cached = Executors.newCachedThreadPool();

// WAY 3: Single Thread — One thread, tasks run one by one in order.
ExecutorService single = Executors.newSingleThreadExecutor();

// WAY 4: Scheduled Pool — Run tasks after delay, or repeatedly.
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(3);

// WAY 5: PRODUCTION RECOMMENDED — ThreadPoolExecutor with bounded queue (no OOM)
ThreadPoolExecutor production = new ThreadPoolExecutor(
    5,    // corePoolSize: always alive
    10,   // maximumPoolSize: max when queue full
    60, TimeUnit.SECONDS, // keepAliveTime for extra threads
    new ArrayBlockingQueue<>(100), // bounded queue — prevents OOM
    new ThreadPoolExecutor.CallerRunsPolicy() // when full: caller runs task, slows down producer
);
Interview Trap: Never say “I use Executors.newCachedThreadPool() in production.” Interviewer will ask: “What if 1 lakh requests come?” Cached pool creates 1 lakh threads → crash. Always say: “I use ThreadPoolExecutor with bounded queue.”

1.2 Complete Runnable Program — Fixed Pool

import java.util.concurrent.*;

public class ExecutorFixedPoolComplete {
    public static void main(String[] args) throws Exception {
        System.out.println("Main started: " + Thread.currentThread().getName());

        ExecutorService pool = Executors.newFixedThreadPool(3);

        // Submit 6 tasks — only 3 run at a time, rest wait in queue
        for (int i = 1; i <= 6; i++) {
            int taskId = i;
            pool.submit(() -> {
                System.out.println("Task " + taskId + " START by " + Thread.currentThread().getName());
                try { Thread.sleep(1000); } catch (Exception e) {}
                System.out.println("Task " + taskId + " DONE by " + Thread.currentThread().getName());
            });
        }

        pool.shutdown(); // no new tasks, finish existing
        pool.awaitTermination(10, TimeUnit.SECONDS); // wait for all
        System.out.println("All tasks done. Main ends.");
    }
}
/* EXPECTED OUTPUT (order of DONE may vary, but only 3 START at once):
Main started: main
Task 1 START by pool-1-thread-1
Task 2 START by pool-1-thread-2
Task 3 START by pool-1-thread-3
Task 1 DONE ...
Task 4 START by pool-1-thread-1  // thread reused!
*/

Step-by-step execution: 1) Pool creates 3 threads. 2) Tasks 1-3 start immediately. 3) Tasks 4-6 wait in queue. 4) As soon as Task 1 finishes, its thread picks Task 4 — thread is reused, not recreated. 5) shutdown() prevents new tasks. 6) awaitTermination() waits.

1.3 Complete Runnable Program — ThreadPoolExecutor With Rejection (Production)

import java.util.concurrent.*;

public class ThreadPoolProductionComplete {
    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
            2, 4, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(2),
            new ThreadPoolExecutor.CallerRunsPolicy()
        );
        // Total capacity = 2 running + 2 in queue + 2 extra threads = 6
        // 7th task onward: CallerRunsPolicy → main thread runs it itself
        for (int i = 1; i <= 8; i++) {
            int id = i;
            pool.submit(() -> {
                System.out.println("Task " + id + " by " + Thread.currentThread().getName());
                try { Thread.sleep(1000); } catch (Exception e) {}
            });
        }
        pool.shutdown();
        pool.awaitTermination(10, TimeUnit.SECONDS);
        System.out.println("Done. Active threads were limited, no crash.");
    }
}

What to say: “Core = 2, Max = 4, Queue = 2. When queue is full, pool creates extra threads up to max. When max also full, CallerRunsPolicy makes the caller run the task — this naturally slows down the producer instead of crashing or dropping work.”

1.4 Complete Runnable Program — ScheduledExecutorService (Delay + Repeat)

import java.util.concurrent.*;

public class ScheduledComplete {
    public static void main(String[] args) throws Exception {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

        // 1) Run once after 2 seconds delay
        scheduler.schedule(() -> System.out.println("One-time task after 2 sec"), 2, TimeUnit.SECONDS);

        // 2) Repeat every 2 seconds, fixed rate (even if task takes time, next starts on schedule)
        ScheduledFuture<?> heartbeat = scheduler.scheduleAtFixedRate(
            () -> System.out.println("Heartbeat at " + System.currentTimeMillis()),
            0, 2, TimeUnit.SECONDS);

        // 3) Repeat with delay AFTER task finishes (safe if task is slow)
        scheduler.scheduleWithFixedDelay(
            () -> System.out.println("Cleanup after previous finished"),
            1, 3, TimeUnit.SECONDS);

        Thread.sleep(8000);
        heartbeat.cancel(false);
        scheduler.shutdown();
        System.out.println("Scheduler stopped.");
    }
}

Real-time use: Heartbeat check, cache cleanup every 5 minutes, retry failed payment after 10 seconds, send reminder email daily. Difference: scheduleAtFixedRate = every 2 sec on clock. scheduleWithFixedDelay = 2 sec gap after previous finishes — use this if task can be slow.

1.5 Complete Runnable Program — Callable + Future + Exception Handling

import java.util.concurrent.*;

public class FutureComplete {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);

        Callable<Integer> successTask = () -> {
            Thread.sleep(500);
            return 10 + 20;
        };
        Callable<Integer> failTask = () -> {
            Thread.sleep(500);
            throw new RuntimeException("DB down!");
        };

        Future<Integer> f1 = pool.submit(successTask);
        Future<Integer> f2 = pool.submit(failTask);

        System.out.println("Success result = " + f1.get()); // 30

        try {
            System.out.println(f2.get()); // throws ExecutionException
        } catch (ExecutionException e) {
            System.out.println("Task failed, real cause = " + e.getCause().getMessage());
        }

        // Timeout: do not wait forever
        Future<Integer> slow = pool.submit(() -> { Thread.sleep(5000); return 1; });
        try {
            System.out.println(slow.get(1, TimeUnit.SECONDS));
        } catch (TimeoutException e) {
            System.out.println("Task timed out, cancelling...");
            slow.cancel(true);
        }
        pool.shutdown();
    }
}

Key points: Future.get() blocks. Exception inside task is wrapped in ExecutionException — always check getCause(). Always use timeout version get(1, SECONDS) in production.

2. CompletableFuture — Modern Async Java (Most Important Advanced Topic)

🍕 Non-Tech Analogy: You order pizza, burger, and drink at a food court. Old way: stand at pizza counter, wait, then go to burger, wait, then drink — 15 min. New way: Order all 3 at once, sit down, each counter calls you when ready, you combine and eat — 5 min. CompletableFuture is “order all at once”.

Short Theory: CompletableFuture is a Future that you can chain — “when this finishes, then do that”, “run these in parallel, then combine”, “if this fails, do fallback”. No blocking with get() unless you want it.

What problem does it solve? Old Future forces you to block and wait. CompletableFuture lets you build a pipeline without blocking threads. Perfect for microservices: fetch user + orders + payments in parallel.

2.1 How to Create Instance — All Ways

import java.util.concurrent.*;

// 1) Run a task that returns nothing
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> System.out.println("Hello"));

// 2) Run a task that returns a value
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> "User: Dharmendra");

// 3) Run on YOUR pool (not default ForkJoinPool) — recommended in production
ExecutorService myPool = Executors.newFixedThreadPool(5);
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "Data", myPool);

// 4) Already completed (for testing)
CompletableFuture<String> cf4 = CompletableFuture.completedFuture("Cached value");

// 5) Manually complete later (for callbacks / events)
CompletableFuture<String> cf5 = new CompletableFuture<>();
new Thread(() -> { try { Thread.sleep(1000); } catch (Exception e) {} cf5.complete("Done later"); }).start();

2.2 Complete Runnable Program — Sequential vs Parallel (See Time Difference)

import java.util.concurrent.*;

public class CompletableFutureParallelComplete {
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();

        // SEQUENTIAL would be: fetchUser (1s) + fetchOrders (1s) + fetchPayments (1s) = 3s
        // PARALLEL: all 3 at once = 1s
        CompletableFuture<String> userF = CompletableFuture.supplyAsync(() -> fetchUser());
        CompletableFuture<String> ordersF = CompletableFuture.supplyAsync(() -> fetchOrders());
        CompletableFuture<String> paymentsF = CompletableFuture.supplyAsync(() -> fetchPayments());

        // Wait for ALL, then combine
        String combined = CompletableFuture.allOf(userF, ordersF, paymentsF)
            .thenApply(v -> userF.join() + " | " + ordersF.join() + " | " + paymentsF.join())
            .get();

        System.out.println(combined);
        System.out.println("Total time = " + (System.currentTimeMillis() - start) + " ms (should be ~1000, not 3000)");
    }
    static String fetchUser() { sleep(1000); return "User: Dharmendra"; }
    static String fetchOrders() { sleep(1000); return "Orders: 5"; }
    static String fetchPayments() { sleep(1000); return "Payments: Done"; }
    static void sleep(int ms) { try { Thread.sleep(ms); } catch (Exception e) {} }
}

2.3 Complete Runnable Program — Chaining: thenApply vs thenApplyAsync vs thenCompose

import java.util.concurrent.*;

public class CompletableFutureChainingComplete {
    public static void main(String[] args) throws Exception {
        // thenApply: transform result in SAME thread (if already done)
        String r1 = CompletableFuture.supplyAsync(() -> 10)
            .thenApply(x -> x * 2)      // 20
            .thenApply(x -> "Value = " + x)
            .get();
        System.out.println(r1);

        // thenCompose: when one future returns ANOTHER future — flatten it
        // Example: getUserId() -> getOrders(userId) — second depends on first
        CompletableFuture<String> orders = CompletableFuture.supplyAsync(() -> "user-101")
            .thenCompose(userId -> CompletableFuture.supplyAsync(() -> "Orders for " + userId));
        System.out.println(orders.get());

        // thenCombine: combine TWO independent futures
        CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> "Hello");
        CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> "World");
        String combined = f1.thenCombine(f2, (a, b) -> a + " " + b).get();
        System.out.println(combined); // Hello World
    }
}

Interview rule: thenApply = transform value. thenCompose = chain futures (flatMap). thenCombine = combine 2 independent futures. If you can explain these 3, you pass CompletableFuture round.

2.4 Complete Runnable Program — Exception Handling + Timeout + Fallback

import java.util.concurrent.*;

public class CompletableFutureErrorComplete {
    public static void main(String[] args) throws Exception {
        // 1) exceptionally: fallback on error
        String r1 = CompletableFuture.<String>supplyAsync(() -> {
            throw new RuntimeException("DB down");
        }).exceptionally(ex -> "Fallback: Cached Data").get();
        System.out.println("With fallback: " + r1);

        // 2) handle: gets both result + exception, always runs
        String r2 = CompletableFuture.supplyAsync(() -> "OK")
            .handle((res, ex) -> ex != null ? "Failed" : "Success: " + res).get();
        System.out.println(r2);

        // 3) orTimeout: if not done in 1 sec, fail
        try {
            CompletableFuture.supplyAsync(() -> { try { Thread.sleep(5000); } catch (Exception e) {} return "Slow"; })
                .orTimeout(1, TimeUnit.SECONDS).get();
        } catch (Exception e) {
            System.out.println("Timed out as expected: " + e.getCause());
        }

        // 4) completeOnTimeout: fallback value on timeout (Java 9+)
        String r4 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(5000); } catch (Exception e) {} return "Slow"; })
            .completeOnTimeout("Default Value", 1, TimeUnit.SECONDS).get();
        System.out.println("Timeout fallback: " + r4);
    }
}

2.5 Complete Runnable Program — Real-Time: E-Commerce Page Load

import java.util.concurrent.*;

public class EcommercePageComplete {
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        ExecutorService pool = Executors.newFixedThreadPool(4);

        CompletableFuture<String> profile = CompletableFuture.supplyAsync(() -> { sleep(800); return "Profile"; }, pool);
        CompletableFuture<String> cart = CompletableFuture.supplyAsync(() -> { sleep(600); return "Cart(3)"; }, pool);
        CompletableFuture<String> offers = CompletableFuture.supplyAsync(() -> { sleep(500); return "Offers: 20% OFF"; }, pool);
        CompletableFuture<String> recommend = CompletableFuture.supplyAsync(() -> { sleep(700); return "Recommended: 10 items"; }, pool);

        // Even if offers fail, page should still load — exceptionally for that one
        CompletableFuture<String> offersSafe = offers.exceptionally(e -> "Offers: Unavailable");

        String page = CompletableFuture.allOf(profile, cart, offersSafe, recommend)
            .thenApply(v -> String.join(" | ", profile.join(), cart.join(), offersSafe.join(), recommend.join()))
            .get();
        System.out.println("PAGE: " + page);
        System.out.println("Time: " + (System.currentTimeMillis() - start) + " ms (parallel, not sum)");
        pool.shutdown();
    }
    static void sleep(int ms) { try { Thread.sleep(ms); } catch (Exception e) {} }
}
🧑‍🏫 Expert Note — Default Pool Danger: supplyAsync() without pool uses ForkJoinPool.commonPool() which has threads = cores - 1. If you block inside it (DB call, sleep), you block the common pool and starve other tasks. In production, always pass your own Executor for I/O tasks. This is a Senior-level answer.

3. ForkJoinPool & RecursiveTask — Divide & Conquer

What problem? One big task (sum 1 to 1 crore, sort 10 lakh items) is too big for one thread. Split it into small pieces, solve in parallel, combine results.

How to create: ForkJoinPool pool = new ForkJoinPool(4); or ForkJoinPool.commonPool().

import java.util.concurrent.*;

public class ForkJoinComplete {
    static class SumTask extends RecursiveTask<Long> {
        long start, end;
        SumTask(long s, long e) { start = s; end = e; }
        protected Long compute() {
            if (end - start <= 10000) { // small enough: do directly
                long sum = 0;
                for (long i = start; i <= end; i++) sum += i;
                return sum;
            }
            long mid = (start + end) / 2;
            SumTask left = new SumTask(start, mid);
            SumTask right = new SumTask(mid + 1, end);
            left.fork(); // run left in parallel
            long rightResult = right.compute(); // run right in this thread
            long leftResult = left.join(); // wait for left
            return leftResult + rightResult;
        }
    }
    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool(4);
        long result = pool.invoke(new SumTask(1, 1000000));
        System.out.println("Sum 1..1000000 = " + result); // 500000500000
        // EASY alternative in Java 8+: parallel stream uses ForkJoinPool internally
        long sum2 = java.util.stream.LongStream.rangeClosed(1, 1000000).parallel().sum();
        System.out.println("Parallel stream sum = " + sum2);
    }
}

Real-time: Parallel sorting, parallel image processing, parallel search in large data. Work-stealing: If one thread finishes early, it steals work from busy thread’s queue — that is why ForkJoin is efficient.

4. CountDownLatch, CyclicBarrier, Semaphore, Phaser — Complete Runnable Programs

These 4 are called Synchronizers — they coordinate threads. Each solves a different coordination problem. All have complete programs below.

4.1 CountDownLatch — Complete Program

Problem it solves: Main thread must wait until N workers finish. Example: App starts only after DB + Cache + Config are ready.

import java.util.concurrent.*;
public class LatchComplete {
    public static void main(String[] args) throws Exception {
        CountDownLatch latch = new CountDownLatch(3);
        // 3 services start in parallel
        for (String service : new String[]{"DB", "Cache", "Config"}) {
            new Thread(() -> {
                try { Thread.sleep(500); System.out.println(service + " ready"); }
                catch (Exception e) {}
                latch.countDown(); // one service done
            }).start();
        }
        System.out.println("Main waiting for all services...");
        latch.await(); // blocks until count reaches 0
        System.out.println("All services ready. App starting!");
        // CountDownLatch cannot be reused — count is 0 forever. Use CyclicBarrier for reuse.
    }
}

4.2 CyclicBarrier — Complete Program

Problem it solves: N threads must wait for EACH OTHER at a point, then all proceed together. Reusable — can be used again and again.

import java.util.concurrent.*;
public class BarrierComplete {
    public static void main(String[] args) {
        // 3 friends meet, then go together. Barrier action runs when all arrive.
        CyclicBarrier barrier = new CyclicBarrier(3,
            () -> System.out.println("--- All arrived! Going together ---"));
        for (int i = 1; i <= 3; i++) {
            int friend = i;
            new Thread(() -> {
                try {
                    System.out.println("Friend " + friend + " reached meeting point");
                    Thread.sleep(friend * 500L); // different travel times
                    barrier.await(); // wait for others
                    System.out.println("Friend " + friend + " moving together");
                    barrier.await(); // reuse barrier for second meeting point
                    System.out.println("Friend " + friend + " reached destination");
                } catch (Exception e) {}
            }).start();
        }
    }
}

4.3 Semaphore — Complete Program (Already in Ch 7, Now Full + Fairness)

import java.util.concurrent.*;
public class SemaphoreComplete {
    public static void main(String[] args) {
        Semaphore parking = new Semaphore(2, true); // 2 slots, fair = FIFO
        for (int i = 1; i <= 5; i++) {
            int car = i;
            new Thread(() -> {
                try {
                    System.out.println("Car " + car + " waiting for parking");
                    parking.acquire();
                    System.out.println("Car " + car + " PARKED");
                    Thread.sleep(2000);
                } catch (Exception e) {}
                finally { parking.release(); System.out.println("Car " + car + " LEFT, slot free"); }
            }).start();
        }
    }
}
/* Fair=true means cars get slot in order they arrived.
   Fair=false (default) is faster but can starve a waiting car. */

4.4 Phaser — Advanced Barrier (Java 7+, Interview Bonus)

Problem: Number of threads changes over time — some join, some leave. CyclicBarrier needs fixed count. Phaser allows dynamic registration.

import java.util.concurrent.*;
public class PhaserComplete {
    public static void main(String[] args) {
        Phaser phaser = new Phaser(1); // main thread registered
        for (int i = 1; i <= 3; i++) {
            int id = i;
            phaser.register(); // add a new thread
            new Thread(() -> {
                System.out.println("Worker " + id + " phase 1 done");
                phaser.arriveAndAwaitAdvance(); // wait for all
                System.out.println("Worker " + id + " phase 2 done");
                phaser.arriveAndDeregister(); // leave, reduce count
            }).start();
        }
        phaser.arriveAndAwaitAdvance();
        System.out.println("Main: Phase 1 complete for all");
        phaser.arriveAndDeregister();
        System.out.println("Main: Done");
    }
}

5. ReadWriteLock, StampedLock & ThreadLocal — Complete Programs With Problem Solved

5.1 ReadWriteLock — Complete Program

Problem: 100 threads read cache, 1 thread writes cache. If you use synchronized, readers block each other unnecessarily — slow. ReadWriteLock allows many readers together, writer alone.

import java.util.concurrent.locks.*;
import java.util.*;
public class ReadWriteComplete {
    private final ReadWriteLock rw = new ReentrantReadWriteLock();
    private final Map<String, String> cache = new HashMap<>();
    public String read(String key) {
        rw.readLock().lock();
        try { Thread.sleep(100); return cache.get(key); }
        catch (Exception e) { return null; }
        finally { rw.readLock().unlock(); }
    }
    public void write(String key, String val) {
        rw.writeLock().lock();
        try { cache.put(key, val); System.out.println("Wrote " + key + "=" + val); }
        finally { rw.writeLock().unlock(); }
    }
    public static void main(String[] args) throws Exception {
        ReadWriteComplete c = new ReadWriteComplete();
        c.write("user:1", "Dharmendra");
        // 5 readers in parallel — all can read together
        for (int i = 0; i < 5; i++) {
            new Thread(() -> System.out.println(Thread.currentThread().getName() + " read: " + c.read("user:1"))).start();
        }
        Thread.sleep(1000);
        // Writer waits for readers, then writes alone
        c.write("user:1", "Updated");
        System.out.println("Final: " + c.read("user:1"));
    }
}

5.2 StampedLock — Faster ReadWriteLock (Java 8+)

Problem: ReadWriteLock is good, but still blocks readers when writer wants lock. StampedLock has optimistic read — read without lock, then check if writer changed data during read. If changed, retry with real lock.

import java.util.concurrent.locks.StampedLock;
public class StampedLockComplete {
    private final StampedLock lock = new StampedLock();
    private int balance = 1000;
    public int optimisticRead() {
        long stamp = lock.tryOptimisticRead(); // no lock, just stamp
        int value = balance;
        // If writer wrote during read, stamp is invalid → retry with read lock
        if (!lock.validate(stamp)) {
            stamp = lock.readLock();
            try { value = balance; } finally { lock.unlockRead(stamp); }
            System.out.println("Optimistic read failed, retried with lock");
        } else {
            System.out.println("Optimistic read succeeded, no lock needed");
        }
        return value;
    }
    public void write(int amt) {
        long stamp = lock.writeLock();
        try { balance += amt; } finally { lock.unlockWrite(stamp); }
    }
    public static void main(String[] args) {
        StampedLockComplete c = new StampedLockComplete();
        System.out.println("Balance: " + c.optimisticRead());
        c.write(500);
        System.out.println("After write: " + c.optimisticRead());
    }
}
Warning: StampedLock is NOT reentrant. If same thread tries to acquire write lock twice, it deadlocks. Use only when you understand it. Interviewers ask: “Why not always use StampedLock?” Answer: “Because it is not reentrant and optimistic read can fail and retry — for simple cases ReadWriteLock is safer.”

5.3 ThreadLocal — Complete Program + Memory Leak Fix

Problem: In a web app, each request needs its own User, Transaction ID, DB Connection. If you use a shared static variable, requests overwrite each other. ThreadLocal gives each thread its own copy.

import java.text.SimpleDateFormat;
import java.util.Date;
public class ThreadLocalComplete {
    // Each thread gets its OWN SimpleDateFormat — SimpleDateFormat is NOT thread-safe
    private static ThreadLocal<SimpleDateFormat> formatter =
        ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    // Each request gets its OWN user context
    private static ThreadLocal<String> currentUser = new ThreadLocal<>();

    public static void main(String[] args) throws Exception {
        Runnable request = () -> {
            try {
                currentUser.set("User-" + Thread.currentThread().getName());
                System.out.println(currentUser.get() + " | Date: " + formatter.get().format(new Date()));
                // ... do work with currentUser ...
            } finally {
                // MUST remove in thread pools — else thread reused for next request still has old user!
                currentUser.remove();
                formatter.remove();
                System.out.println(Thread.currentThread().getName() + " cleaned ThreadLocal");
            }
        };
        Thread t1 = new Thread(request, "T1");
        Thread t2 = new Thread(request, "T2");
        t1.start(); t2.start();
        t1.join(); t2.join();
        System.out.println("Main: ThreadLocal values are isolated per thread.");
    }
}

Common mistake: Forgetting remove() in thread pool → memory leak + wrong user data leaking to next request. Always use try-finally { remove(); }.

5.4 ConcurrentHashMap — Complete Program (Why Not synchronized HashMap?)

import java.util.concurrent.*;
public class ConcurrentHashMapComplete {
    public static void main(String[] args) throws Exception {
        // WRONG: Collections.synchronizedMap locks whole map — slow
        // RIGHT: ConcurrentHashMap locks only one bucket — fast, many threads in parallel
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

        // 10 threads increment same key 1000 times each — should be 10000
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    // merge is atomic: if key absent, put 1, else add 1 — no race
                    map.merge("visits", 1, Integer::sum);
                }
            });
            threads[i].start();
        }
        for (Thread t : threads) t.join();
        System.out.println("Visits = " + map.get("visits")); // Always 10000

        // computeIfAbsent: only one thread loads from DB, others reuse — cache pattern
        String user = map.computeIfAbsent("user:101", k -> 999).toString();
        System.out.println("Cache pattern works: " + user);
    }
}

6. Virtual Threads (Java 21) — Complete Program

What problem? Platform threads are OS threads — heavy (1 MB stack). You cannot create 1 lakh of them. Virtual threads are JVM-managed, light (few KB). You can create millions of them for I/O work.

public class VirtualThreadsComplete {
    public static void main(String[] args) throws Exception {
        // OLD: Platform thread — heavy
        Thread platform = new Thread(() -> System.out.println("Platform: " + Thread.currentThread()));
        platform.start(); platform.join();

        // NEW: Virtual thread — light, same code, just ofVirtual()
        Thread virtual = Thread.ofVirtual().start(() ->
            System.out.println("Virtual: " + Thread.currentThread() + " isVirtual=" + Thread.currentThread().isVirtual()));
        virtual.join();

        // REAL POWER: 100,000 virtual threads — impossible with platform threads
        long start = System.currentTimeMillis();
        try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 10000; i++) {
                int id = i;
                executor.submit(() -> {
                    try { Thread.sleep(100); } catch (Exception e) {}
                    if (id % 5000 == 0) System.out.println("Virtual task " + id + " done");
                });
            }
        } // executor closes, waits for all
        System.out.println("10000 virtual tasks done in " + (System.currentTimeMillis() - start) + " ms");
        System.out.println("Note: Virtual threads still use same synchronized/volatile/lock concepts.");
    }
}
When to use Virtual Threads? I/O-bound (API, DB, file) → YES, huge win. CPU-bound (calculation, image processing) → NO, use platform pool with cores+1. Virtual threads do not make CPU faster, they make waiting cheaper.

7. Complete Interview Programs — Copy-Paste-Run (No Missing Parts)

Below are 3 full programs interviewers ask you to write on the spot. Each is complete — imports, class, main, output.

7.1 Complete Program — Producer-Consumer With BlockingQueue (Full)

import java.util.concurrent.*;
public class ProducerConsumerFull {
    public static void main(String[] args) throws Exception {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);
        ExecutorService pool = Executors.newFixedThreadPool(2);
        // Producer
        pool.submit(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    queue.put(i);
                    System.out.println("Produced " + i + " | Queue size: " + queue.size());
                    Thread.sleep(200);
                }
            } catch (Exception e) { Thread.currentThread().interrupt(); }
        });
        // Consumer
        pool.submit(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    int v = queue.take();
                    System.out.println("  Consumed " + v + " | Queue size: " + queue.size());
                    Thread.sleep(500);
                }
            } catch (Exception e) { Thread.currentThread().interrupt(); }
        });
        pool.shutdown();
        pool.awaitTermination(10, TimeUnit.SECONDS);
        System.out.println("Producer-Consumer done.");
    }
}

7.2 Complete Program — Thread-Safe Singleton + Test With 100 Threads

import java.util.concurrent.*;
public class SingletonFull {
    // Double-Checked Locking — volatile is MUST
    static class Singleton {
        private static volatile Singleton instance;
        private Singleton() {}
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) instance = new Singleton();
                }
            }
            return instance;
        }
    }
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(10);
        java.util.Set<Singleton> set = ConcurrentHashMap.newKeySet();
        for (int i = 0; i < 100; i++) {
            pool.submit(() -> set.add(Singleton.getInstance()));
        }
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("Unique instances created = " + set.size() + " (must be 1)");
    }
}

7.3 Complete Program — Rate Limiter + Test

import java.util.*;
import java.util.concurrent.*;
public class RateLimiterFull {
    static class RateLimiter {
        private final Map<String, Deque<Long>> map = new ConcurrentHashMap<>();
        public boolean allow(String user, int limit, long windowMs) {
            long now = System.currentTimeMillis();
            Deque<Long> q = map.computeIfAbsent(user, k -> new ArrayDeque<>());
            synchronized (q) {
                while (!q.isEmpty() && now - q.peekFirst() > windowMs) q.pollFirst();
                if (q.size() < limit) { q.offerLast(now); return true; }
                return false;
            }
        }
    }
    public static void main(String[] args) {
        RateLimiter limiter = new RateLimiter();
        // Allow 5 requests per 10 seconds for user-1
        for (int i = 1; i <= 7; i++) {
            System.out.println("Request " + i + " allowed? " + limiter.allow("user-1", 5, 10000));
        }
        // Output: first 5 = true, next 2 = false
    }
}
✅ How to Practice Advanced Topics:
Day 1: Run all ExecutorService programs (1.2, 1.3, 1.4, 1.5) — change pool size, see output change.
Day 2: Run all CompletableFuture programs (2.2, 2.3, 2.4, 2.5) — change sleep times, see parallel vs sequential.
Day 3: Run Latch, Barrier, Semaphore, Phaser programs — explain each in 1 line without looking.
Day 4: Run ReadWrite, StampedLock, ThreadLocal, ConcurrentHashMap, Virtual Threads — note common mistakes.
If you can explain why each program works, not just that it works, you are interview-ready.

❓ Q&A — Questions Students Ask

Q: Is synchronized slow?
A: Modern JVM optimizes it (biased locking, lightweight lock). It is slow only if many threads contend for same lock. Reduce lock scope or use Concurrent collections.

Q: When to use synchronized vs ConcurrentHashMap?
A: If you need to update multiple variables together (transfer money), use synchronized. If you need simple put/get, use ConcurrentHashMap — it is faster.

Q: How many threads can Java create?
A: Depends on OS and memory. Typically 1000s, but each thread uses ~1MB stack. That is why thread pools are used.

Q: What is Virtual Thread (Java 21)?
A: Lightweight threads managed by JVM, not OS. You can create millions of them. Thread.ofVirtual().start(task). Perfect for I/O-bound work. But synchronized + volatile + locks concepts remain same.