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.
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.
| Word | Meaning in Simple English | Example |
|---|---|---|
| Atomicity | All-or-nothing. Either full work happens, or nothing happens. | Money transfer: debit + credit both happen, or none. |
| Visibility | If one thread changes a value, other threads can see the new value. | One thread sets stop = true, other thread stops. |
| Ordering | Steps 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.
One application doing many things at the same time — without waiting.
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).
| Process | Thread |
|---|---|
| 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. |
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.
There are 3 ways. Learn all 3 — interviewers ask the difference.
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.
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();
}
}
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();
}
}
| Runnable | Callable |
|---|---|
| Returns void | Returns a value |
| Cannot throw checked exception | Can throw exception |
| Use with Thread or Executor | Use with Executor + Future |
start() not called.start() called, waiting for CPU.wait() / sleep() / join().run() finished.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
run() directly, there is no multithreading. Always call start(). Calling start() twice throws IllegalThreadStateException.| Method | Releases Lock? | Where Used? | Meaning |
|---|---|---|---|
sleep(1000) | No | Anywhere | Pause thread for time |
wait() | Yes | Inside synchronized only | Wait until notify() |
join() | No | On thread object | Main waits for thread to finish |
yield() | No | Anywhere | Hint: 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");
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().
This is the #1 reason multithreading is hard. Understand this chapter deeply.
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.Problem: 100 threads, each increments a counter 1000 times. Expected = 100,000. But you get 97,432 or 98,101. Why?
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.
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
}
}
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.
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; }
}
}
static synchronized locks on Class object, not on instance. Two different objects still block each other for static method. Use for static counters.
synchronized is not the only tool. Learn when to use lighter tools.
volatile means “always write to whiteboard immediately, always read from whiteboard.” No private notebook.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.
// 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;
}
}
volatile int i; i++ is still NOT thread-safe. volatile gives visibility, but i++ is 3 steps. Use AtomicInteger for i++.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.
| Tool | Visibility? | Atomicity? | Use When |
|---|---|---|---|
volatile | Yes | No | Flag, stop signal, single write |
AtomicInteger | Yes | Yes (for single var) | Counter, ID generator |
synchronized | Yes | Yes (for block) | Multiple variables, complex logic |
volatile boolean isRunning to stop a background thread. AtomicLong for request ID generator. synchronized for bank transfer (needs to update two accounts together).Threads don’t just run alone — they must wait for each other and share work.
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();
}
}
while re-checks the condition after waking. Always use while with wait().Problem: Producer makes items, Consumer eats them. Buffer size = 5. Producer must wait if full. Consumer must wait if empty.
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.
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;
}
}
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.”
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.
synchronized is simple, but sometimes you need more control — timeout, fairness, try-lock.
| Feature | synchronized | ReentrantLock |
|---|---|---|
| Release | Automatic | Manual in finally |
| Timeout | No, waits forever | Yes, tryLock(1, SECONDS) |
| Interrupt | No | Yes, lockInterruptibly() |
| Fairness | No | Yes, new ReentrantLock(true) |
| Multiple wait-sets | One | Multiple 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
}
}
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();
}
}
}
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.
The most asked multithreading coding question. Learn to write it, run it, and fix it.
Two threads wait for each other forever. Program hangs, no error, no progress.
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.
// Both threads take lock1 FIRST, then lock2 - no circle
Thread t2Fixed = new Thread(() -> {
synchronized (lock1) {
sleep(100);
synchronized (lock2) { /* work */ }
}
});
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.
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.
jstack <pid> or VisualVM → Threads → Detect Deadlock.Never create threads manually in production. Use a pool.
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.
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);
}
}
threads = cores + 1threads = cores × (1 + wait / compute)Executors.newCachedThreadPool() in production — unbounded, can create 10,000 threads and crash. Always use bounded ThreadPoolExecutor.| Tool | One Line | Example |
|---|---|---|
| CountDownLatch | Main waits for N workers. One-time. | Start server only after 3 services are ready. |
| CyclicBarrier | Workers wait for each other. Reusable. | 3 friends meet, then go together, repeat. |
| Semaphore | Limit 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");
}
}
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){} }
}
computeIfAbsent() is atomic — perfect for cache.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; }
}
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.
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.
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.
if instead of while with wait() — spurious wakeup.unlock() in finally for ReentrantLock — deadlock on exception.volatile i++ thinking it is atomic — it is not.run() instead of start() — no new thread.InterruptedException — swallowing it silently.| Question | One-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. |
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.
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.
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.
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.”
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).
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.”
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.
synchronized + wait/notify — shows you understand basics.Semaphore / CountDownLatch / CyclicBarrier — shows you know modern tools.| Concept | Short Theory (30 sec) | Example |
|---|---|---|
| Monitor | Every Java object has a lock + wait-set. synchronized uses it. Only one thread can own monitor at a time. | synchronized(obj){ obj.wait(); } |
| Reentrancy | Same thread can acquire same lock again without deadlock. Java locks are reentrant. | Method A (sync) calls Method B (sync) on same object — works. |
| Spurious Wakeup | Thread can wake from wait() without notify(). Always use while, not if. | Odd-Even code uses while(n<=MAX). |
| Busy Waiting / Spin Lock | Thread loops checking flag, wasting CPU. Better to wait() or use LockSupport.park(). | while(!ready){} = busy wait, bad. |
| Thread Starvation | One thread never gets lock because others always win. Fix with fair lock new ReentrantLock(true). | Low-priority thread waiting forever. |
| Context Switch | CPU stops one thread, saves its state, starts another. Costs time. Too many threads = too many switches = slow. | 10000 threads slower than 100 threads. |
| Amdahl’s Law | If 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). |
lockInterruptibly().ReadWriteLock or StampedLock (Java 8+, optimistic read).LongAdder (splits counter into cells).CompletableFuture, not raw threads.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.
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?
new Thread() for every request is costly (memory + OS thread creation).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
);
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.
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.”
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.
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.
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.
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();
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) {} }
}
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.
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);
}
}
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) {} }
}
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.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.
These 4 are called Synchronizers — they coordinate threads. Each solves a different coordination problem. All have complete programs below.
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.
}
}
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();
}
}
}
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. */
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");
}
}
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"));
}
}
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());
}
}
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(); }.
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);
}
}
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.");
}
}
Below are 3 full programs interviewers ask you to write on the spot. Each is complete — imports, class, main, output.
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.");
}
}
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)");
}
}
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
}
}
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.