Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 12 / Stage 3

Concurrency

Goal: Start work on a background thread, explain and fix a race condition with synchronized, hand work to an ExecutorService, combine async results with CompletableFuture, use a thread-safe collection, and start a virtual thread. Time: ~7 hours

What you will learn

  • Thread and Runnable: starting work in the background, naming threads, daemon threads
  • Race conditions: why count++ loses updates across threads, and fixing it with synchronized
  • Visibility: why synchronized is about more than atomicity, and what volatile buys you
  • Deadlock: the hazard two synchronized blocks introduce, and the lock-ordering fix
  • ExecutorService, Callable and Future: thread pools instead of one Thread per task
  • CompletableFuture: thenApply, thenCompose, thenCombine, exceptionally, orTimeout, completeOnTimeout
  • java.util.concurrent collections: ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue
  • Virtual threads (JEP 444, finalized in Java 21): cheap threads for blocking I/O
  • Putting it together: a parallel price downloader, measured against a sequential one

About "JDK 21.0.11 Corretto": every command and output below was run on the exact JDK pinned in ../../TOOLING.md. Virtual threads are a finalized JDK 21 feature (JEP 444), not a preview — safe to use exactly as shown.

ℹ️ Why concurrency lands here, not earlier. Concurrency bugs — races, visibility, deadlock — are almost always bugs in shared mutable state, a thing you've been managing one thread at a time since Part 8's encapsulation. This part only makes sense once "two methods touching the same object" is already a natural idea (DESIGN-NOTES.md #5).

Topics in this part

Practice

Every exercise is one .java file with a public static void main(String[] args) method, the same shape as every example in this part. solutions/ex01.java through ex08.java use a non-public top-level class (class Ex01 { ... }, matching the stage-wide convention from Part 1) so the filename does not need to match the class name. Exact millisecond counts vary by machine and load — where that matters, the exercise itself prints a boolean check or marks the line (varies), the same style as this part's own examples.


Exercise 1: Courier riders packing parcels in parallel

Scenario: A delivery hub has three riders — Rahul, Simran and Aditya — each taking 150 ms to pack one parcel. Packing one at a time versus all three at once should show a real difference. What to do:

  1. Write packParcel(rider, millis) that sleeps for millis then prints <thread name> packed a parcel for <rider>.
  2. Time packing for all three riders one at a time, on the main thread, and check the total took at least 450 ms.
  3. Time packing all three again, this time starting one named Thread per rider (via a Runnable), and join()-ing all three before checking the total took under 450 ms.
  4. Start one Thread, set as a daemon, that loops Thread.sleep(1000) forever; print isDaemon() and a line explaining it dies silently when main ends.

Sample output:

== one rider at a time ==
main packed a parcel for Rahul
main packed a parcel for Simran
main packed a parcel for Aditya
sequential took at least 450 ms: true

== three riders at once ==
rider-Simran packed a parcel for Simran
rider-Rahul packed a parcel for Rahul
rider-Aditya packed a parcel for Aditya
threaded took less than 450 ms: true

== a daemon thread for a background ping, stopped when main ends ==
is daemon: true
main ends now; the daemon dies with it, never printing anything

💡 Hint: The three riders may finish in any order once threaded — the JVM schedules threads, and that order is never guaranteed. Call .start(), never .run() directly, or nothing actually moves to the background.


Exercise 2: A canteen token counter, raced and fixed

Scenario: A college canteen hands out numbered tokens from four counters at once. Counting with a plain int loses tokens; synchronized doesn't. What to do:

  1. Write issueUnsafe() (unsafeTokens = unsafeTokens + 1) and a synchronized issueSafe() (safeTokens = safeTokens + 1).
  2. Start 4 threads, each calling issueUnsafe() 200,000 times; join() them all, then print the expected total, the actual (unsafe) total marked (varies -- a different wrong number on every run), and whether updates were lost.
  3. Repeat with issueSafe(), printing the expected total, the actual (safe) total, and whether it was correct every time.

Sample output (run live — unsafe count varies):

== without synchronized: a lost-update race ==
expected tokens: 800000
actual (unsafe): 254134  (varies -- a different wrong number on every run)
lost updates happened: true

== with synchronized: every issue counted ==
expected tokens: 800000
actual (safe): 800000
correct every time: true

💡 Hint: unsafeTokens = unsafeTokens + 1 is read-add-write — three separate steps a second thread can interleave with. synchronized on the whole method makes those three steps atomic from every other thread's point of view.


Exercise 3: Two UPI transfers, deadlocked and then fixed

Scenario: Ramesh pays Suresh, and at the exact same moment Suresh pays Ramesh back — both wallets get locked in opposite order, and both transfers hang forever. What to do:

  1. Write a Wallet(id, balanceRupees) and transfer(from, to, amount, pauseMillisBetweenLocks) that locks from, sleeps pauseMillisBetweenLocks, then locks to and moves the money.
  2. Start one daemon thread transferring ramesh -> suresh and another suresh -> ramesh at the same time, both with a 100 ms pause between locks. After 500 ms, print both threads' getState() and whether both are BLOCKED.
  3. Write safeTransfer(from, to, amount) that always locks the wallet with the smaller id first, regardless of transfer direction. Run a priya -> kabir and a kabir -> priya transfer this way, join() both, and print the final balances and that the total is unchanged.

Sample output:

== two transfers, opposite lock order: a deadlock ==
ramesh-to-suresh state: BLOCKED
suresh-to-ramesh state: BLOCKED
deadlocked (both BLOCKED, neither can finish): true

== the fix: always lock wallets in the same order ==
both transfers finished (no deadlock)
priya balance: 3300, kabir balance: 2700
total unchanged: true

💡 Hint: Thread.getState() reporting BLOCKED for both threads, at the same time, with neither ever finishing, is deadlock made visible. The fix needs no new API — just one fixed rule for which lock to take first, applied identically regardless of transfer direction.


Exercise 4: GST invoices on a thread pool, one of them broken

Scenario: A billing job computes GST-inclusive invoices for four customers at once on a fixed pool — and one customer's stored amount is garbage data. What to do:

  1. Write a Map<String, String> of customer to a raw amount string, with one value deliberately not a number.
  2. Write a Callable<String> factory that sleeps 150 ms, parses the amount with Double.parseDouble, multiplies by 1.18, and formats <customer> Rs. <amount> -> Rs. <withGst> with GST.
  3. invokeAll the four tasks on a newFixedThreadPool(4); for each Future, print its result, or — on ExecutionException — print <customer> failed: <exception type>: <message>.
  4. Print whether all four finished in under 450 ms, then shut the pool down and print whether it terminated cleanly.

Sample output:

== a fixed thread pool, 4 invoices of 150 ms, submitted together ==
Nikhil  Rs. 1,200.00 -> Rs. 1,416.00 with GST
Shreya  Rs. 2,500.00 -> Rs. 2,950.00 with GST
Imran failed: NumberFormatException: For input string: "not-a-number"
Pooja   Rs. 899.00 -> Rs. 1,060.82 with GST
4 invoices of 150 ms on 4 threads finished in under 450 ms: true
pool terminated cleanly: true

💡 Hint: Future.get() re-throws a failing task's exception wrapped in ExecutionException — the real cause is e.getCause(), not e itself. One failing task doesn't stop the other three from completing or being reported.


Exercise 5: Shipping estimate, chained and combined

Scenario: An order's shipping estimate needs the order's warehouse first (one async call), then that warehouse's ETA (a second, dependent async call) — but the packaging fee can be fetched independently, in parallel, and an unknown order should fail softly. What to do:

  1. Write lookupWarehouse(orderId, pool) (sleeps 150 ms, looks up a Map, throws IllegalArgumentException if missing), fetchEtaDays(warehouse, pool) and fetchPackagingFee(orderId, pool) — each returning a CompletableFuture.
  2. Use thenCompose to build "<order> ships from <warehouse>, arrives in <days> day(s)" for an order that exists.
  3. Use thenCombine to fetch an ETA and a packaging fee in parallel for a different warehouse/order, and check the combined call took under 280 ms.
  4. Use exceptionally on an unknown order ID to print a fallback message instead of throwing.
  5. Show orTimeout failing a slow (2000 ms) call after 100 ms, and completeOnTimeout recovering the same kind of slow call with a cached value instead.

Sample output:

== thenCompose: the ETA needs the warehouse first ==
ORD-201 ships from pune-wh-1, arrives in 1 day(s)

== thenCombine: ETA and packaging fee fetched in parallel ==
eta 3 day(s), packaging fee Rs. 60.0
ran in parallel, under 280 ms: true

== exceptionally: recover instead of crashing ==
fallback: no such order: ORD-999

== orTimeout: give up on a call that is taking too long ==
timed out: TimeoutException

== completeOnTimeout: fall back to a cached value instead ==
cached: pune-wh-1 (stale)

💡 Hint: thenApply where the next step is itself async leaves you holding a CompletableFuture<CompletableFuture<T>> — that's exactly why step 2 needs thenCompose, not thenApply.


Exercise 6: Election votes and railway booking slips

Scenario: A polling booth's vote tally is updated from four counting threads at once, and a railway counter hands booking slips to two clerks through one queue. What to do:

  1. Count a fixed list of 9 votes ("INDIA", "BJP", "NOTA" in some order) into a ConcurrentHashMap<String, Integer>, split across 4 threads by index (shard, shard + 4, shard + 8, …), using merge(vote, 1, Integer::sum). Print each party's count and whether the total matches the vote list's size.
  2. Put 5 passenger names onto a LinkedBlockingQueue<String> from one producer, with two clerk threads take()-ing from it and collecting issued names into a CopyOnWriteArrayList. Use a "__STOP__" sentinel, one per clerk, to end each clerk's loop. Print the issued count and whether all five passengers were issued a slip.

Sample output:

== ConcurrentHashMap: vote counts updated from four threads ==
INDIA: 4, BJP: 3, NOTA: 2
total counted matches total votes: true

== BlockingQueue: one producer, two counter clerks, no explicit lock ==
issued count: 5
all five passengers issued: true

💡 Hint: take() blocks until something is in the queue — no synchronized, no polling loop. You need exactly as many "__STOP__" slips as there are clerk threads, or one clerk will wait on take() forever.


Exercise 7: 5,000 bank status checks, platform threads vs. virtual threads

Scenario: A reconciliation job checks 5,000 accounts' status, each call blocking for 20 ms. Compare a capped platform-thread pool against one virtual thread per task. What to do:

  1. Print isVirtual() and isDaemon() for one unstarted virtual thread (Thread.ofVirtual().unstarted(...)).
  2. Submit 5,000 tasks (each Thread.sleep(20) then increments an AtomicInteger) to a newFixedThreadPool(100); time it, print how many completed, and the time taken, marked (varies).
  3. Reset the counter and submit the same 5,000 tasks to newVirtualThreadPerTaskExecutor(); time it the same way.
  4. Print whether the virtual-thread run finished faster than the capped platform-pool run.

Sample output (timings vary by machine):

== a virtual thread, up close ==
isVirtual: true
isDaemon: true

== 5,000 blocking bank status checks, platform threads (capped pool) ==
completed: 5000
100 platform threads took: 1173 ms  (varies)

== the same 5,000 checks, one virtual thread per task ==
completed: 5000
5,000 virtual threads took: 38 ms  (varies)
virtual threads finished faster than the capped platform pool: true

💡 Hint: try (ExecutorService pool = Executors.newFixedThreadPool(100)) — closing the try-with-resources block calls close(), which waits for every submitted task to finish, which is exactly the timing boundary you want here.


Exercise 8 (capstone): Train seat checks that never wait on the slowest one

Scenario: A seat-availability dashboard checks 6 trains against a (local, offline) booking API. Five answer quickly; one (SLOW1) is stuck and would otherwise hold up the whole dashboard. What to do:

  1. Start a local com.sun.net.httpserver.HttpServer with one context, /availability/<train>, that sleeps 100 ms and returns "train <train>: 12 seats available" — except for train "SLOW1", which sleeps 3000 ms first.
  2. For each of the 6 trains, build a CompletableFuture on a newVirtualThreadPerTaskExecutor() that calls the endpoint with HttpClient, apply .completeOnTimeout("train <train>: unknown, try again later", 500, TimeUnit.MILLISECONDS), then thenAccept the result into a shared ConcurrentHashMap<String, String>.
  3. Wait for all 6 with CompletableFuture.allOf(...).join(), time it, then print every train's stored result in order.
  4. Print whether all 6 trains have a stored result, whether SLOW1's result is the fallback message, and whether the whole check finished well under SLOW1's own 3000 ms delay.

Sample output:

6 trains, checked in parallel, SLOW1 deliberately too slow
train 12345: 12 seats available
train 12951: 12 seats available
train 22691: 12 seats available
train 12627: 12 seats available
train SLOW1: unknown, try again later
train 16032: 12 seats available

all trains answered (fallback counts as answered): true
SLOW1 fell back instead of blocking everyone: true
finished well under the slow train's own 3000 ms delay: true  (varies)

💡 Hint: Do not put the virtual-thread pool in a try-with-resources around the join() here — ExecutorService.close() waits for every submitted task, including the still-running SLOW1 call, which would quietly undo the entire point of completeOnTimeout. Create the pool normally, measure the timing you care about, and only call shutdownNow() afterward to abandon the one call that's still hanging.

Show the solutions for Part 12 (8 files)

solutions/ex01.java

// Exercise 1: three courier riders prepare parcels in parallel threads, started
// from Runnables, each named, with the main thread waiting on all three with join().

import java.util.ArrayList;
import java.util.List;

class Ex01 {

    static void packParcel(String rider, long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
        System.out.println(Thread.currentThread().getName() + " packed a parcel for " + rider);
    }

    public static void main(String[] args) throws InterruptedException {
        List<String> riders = List.of("Rahul", "Simran", "Aditya");

        System.out.println("== one rider at a time ==");
        long start = System.currentTimeMillis();
        for (String rider : riders) {
            packParcel(rider, 150);
        }
        long sequentialMs = System.currentTimeMillis() - start;
        System.out.println("sequential took at least 450 ms: " + (sequentialMs >= 450));

        System.out.println();
        System.out.println("== three riders at once ==");
        start = System.currentTimeMillis();
        List<Thread> workers = new ArrayList<>();
        for (String rider : riders) {
            Runnable task = () -> packParcel(rider, 150);
            Thread worker = new Thread(task, "rider-" + rider);
            workers.add(worker);
            worker.start();
        }
        for (Thread worker : workers) {
            worker.join();
        }
        long threadedMs = System.currentTimeMillis() - start;
        System.out.println("threaded took less than 450 ms: " + (threadedMs < 450));

        System.out.println();
        System.out.println("== a daemon thread for a background ping, stopped when main ends ==");
        Thread ping = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    return;
                }
            }
        });
        ping.setDaemon(true);
        ping.start();
        System.out.println("is daemon: " + ping.isDaemon());
        System.out.println("main ends now; the daemon dies with it, never printing anything");
    }
}

solutions/ex02.java

// Exercise 2: a canteen token counter incremented from four threads --
// unsafe (lost updates) vs. safe (synchronized).

import java.util.ArrayList;
import java.util.List;

class Ex02 {

    static int unsafeTokens = 0;
    static int safeTokens = 0;

    static void issueUnsafe() {
        unsafeTokens = unsafeTokens + 1;   // read, add, write: three separate steps
    }

    static synchronized void issueSafe() {
        safeTokens = safeTokens + 1;       // only one thread runs this body at a time
    }

    public static void main(String[] args) throws InterruptedException {
        int threads = 4;
        int issuesPerThread = 200_000;
        int expected = threads * issuesPerThread;

        System.out.println("== without synchronized: a lost-update race ==");
        List<Thread> unsafeWorkers = new ArrayList<>();
        for (int t = 0; t < threads; t++) {
            Thread worker = new Thread(() -> {
                for (int i = 0; i < issuesPerThread; i++) {
                    issueUnsafe();
                }
            });
            unsafeWorkers.add(worker);
            worker.start();
        }
        for (Thread worker : unsafeWorkers) {
            worker.join();
        }
        System.out.println("expected tokens: " + expected);
        System.out.println("actual (unsafe): " + unsafeTokens + "  (varies -- a different wrong number on every run)");
        System.out.println("lost updates happened: " + (unsafeTokens != expected));

        System.out.println();
        System.out.println("== with synchronized: every issue counted ==");
        List<Thread> safeWorkers = new ArrayList<>();
        for (int t = 0; t < threads; t++) {
            Thread worker = new Thread(() -> {
                for (int i = 0; i < issuesPerThread; i++) {
                    issueSafe();
                }
            });
            safeWorkers.add(worker);
            worker.start();
        }
        for (Thread worker : safeWorkers) {
            worker.join();
        }
        System.out.println("expected tokens: " + expected);
        System.out.println("actual (safe): " + safeTokens);
        System.out.println("correct every time: " + (safeTokens == expected));
    }
}

solutions/ex03.java

// Exercise 3: two UPI wallet transfers, locked in opposite order -- a deadlock --
// then the fix: always lock wallets in the same order.

class Ex03 {

    static class Wallet {
        final String id;
        int balanceRupees;

        Wallet(String id, int balanceRupees) {
            this.id = id;
            this.balanceRupees = balanceRupees;
        }
    }

    static void transfer(Wallet from, Wallet to, int amount, long pauseMillisBetweenLocks) {
        synchronized (from) {
            try {
                Thread.sleep(pauseMillisBetweenLocks);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
            synchronized (to) {
                from.balanceRupees -= amount;
                to.balanceRupees += amount;
            }
        }
    }

    static void safeTransfer(Wallet from, Wallet to, int amount) {
        Wallet first = from.id.compareTo(to.id) <= 0 ? from : to;
        Wallet second = first == from ? to : from;
        synchronized (first) {
            synchronized (second) {
                from.balanceRupees -= amount;
                to.balanceRupees += amount;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("== two transfers, opposite lock order: a deadlock ==");
        Wallet ramesh = new Wallet("ramesh", 2000);
        Wallet suresh = new Wallet("suresh", 2000);

        Thread t1 = new Thread(() -> transfer(ramesh, suresh, 50, 100), "ramesh-to-suresh");
        Thread t2 = new Thread(() -> transfer(suresh, ramesh, 50, 100), "suresh-to-ramesh");
        t1.setDaemon(true);
        t2.setDaemon(true);
        t1.start();
        t2.start();

        Thread.sleep(500);
        System.out.println(t1.getName() + " state: " + t1.getState());
        System.out.println(t2.getName() + " state: " + t2.getState());
        boolean bothBlocked = t1.getState() == Thread.State.BLOCKED && t2.getState() == Thread.State.BLOCKED;
        System.out.println("deadlocked (both BLOCKED, neither can finish): " + bothBlocked);

        System.out.println();
        System.out.println("== the fix: always lock wallets in the same order ==");
        Wallet priya = new Wallet("priya", 3000);
        Wallet kabir = new Wallet("kabir", 3000);

        Thread t3 = new Thread(() -> safeTransfer(priya, kabir, 200), "safe-priya-to-kabir");
        Thread t4 = new Thread(() -> safeTransfer(kabir, priya, 500), "safe-kabir-to-priya");
        t3.start();
        t4.start();
        t3.join();
        t4.join();
        System.out.println("both transfers finished (no deadlock)");
        System.out.println("priya balance: " + priya.balanceRupees + ", kabir balance: " + kabir.balanceRupees);
        System.out.println("total unchanged: " + (priya.balanceRupees + kabir.balanceRupees == 6000));
    }
}

solutions/ex04.java

// Exercise 4: an ExecutorService computes a GST-inclusive invoice for several
// customers in parallel; one task fails, and Future.get() re-throws it wrapped.

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class Ex04 {

    static final Map<String, String> AMOUNT_BY_CUSTOMER = Map.of(
            "Nikhil", "1200",
            "Shreya", "2500",
            "Imran", "not-a-number",
            "Pooja", "899"
    );

    static Callable<String> invoiceTask(String customer) {
        return () -> {
            Thread.sleep(150);   // pretend this calls a slow billing system
            double amount = Double.parseDouble(AMOUNT_BY_CUSTOMER.get(customer));
            double withGst = amount * 1.18;
            return String.format("%-7s Rs. %,.2f -> Rs. %,.2f with GST", customer, amount, withGst);
        };
    }

    public static void main(String[] args) throws InterruptedException {
        List<String> customers = List.of("Nikhil", "Shreya", "Imran", "Pooja");

        System.out.println("== a fixed thread pool, 4 invoices of 150 ms, submitted together ==");
        ExecutorService pool = Executors.newFixedThreadPool(4);
        try {
            long start = System.nanoTime();
            List<Future<String>> futures = pool.invokeAll(customers.stream().map(Ex04::invoiceTask).toList());
            for (int i = 0; i < futures.size(); i++) {
                try {
                    System.out.println(futures.get(i).get());
                } catch (ExecutionException e) {
                    System.out.println(customers.get(i) + " failed: " + e.getCause().getClass().getSimpleName()
                            + ": " + e.getCause().getMessage());
                }
            }
            long tookMs = (System.nanoTime() - start) / 1_000_000;
            System.out.println("4 invoices of 150 ms on 4 threads finished in under 450 ms: " + (tookMs < 450));
        } finally {
            pool.shutdown();
            boolean terminated = pool.awaitTermination(5, TimeUnit.SECONDS);
            System.out.println("pool terminated cleanly: " + terminated);
        }
    }
}

solutions/ex05.java

// Exercise 5: CompletableFuture chaining -- thenCompose for a dependent call,
// thenCombine for two independent calls, exceptionally for a fallback, and
// completeOnTimeout for a slow call that should not block the whole chain.

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Ex05 {

    static final Map<String, String> WAREHOUSE_BY_ORDER = Map.of("ORD-201", "pune-wh-1", "ORD-202", "chennai-wh-1");
    static final Map<String, Integer> ETA_DAYS_BY_WAREHOUSE = Map.of("pune-wh-1", 1, "chennai-wh-1", 3);
    static final Map<String, Double> WEIGHT_KG_BY_ORDER = Map.of("ORD-201", 2.0, "ORD-202", 5.0);

    static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    static CompletableFuture<String> lookupWarehouse(String orderId, ExecutorService pool) {
        return CompletableFuture.supplyAsync(() -> {
            sleep(150);
            String warehouse = WAREHOUSE_BY_ORDER.get(orderId);
            if (warehouse == null) {
                throw new IllegalArgumentException("no such order: " + orderId);
            }
            return warehouse;
        }, pool);
    }

    static CompletableFuture<Integer> fetchEtaDays(String warehouse, ExecutorService pool) {
        return CompletableFuture.supplyAsync(() -> {
            sleep(150);
            return ETA_DAYS_BY_WAREHOUSE.getOrDefault(warehouse, 7);
        }, pool);
    }

    static CompletableFuture<Double> fetchPackagingFee(String orderId, ExecutorService pool) {
        return CompletableFuture.supplyAsync(() -> {
            sleep(150);
            double kg = WEIGHT_KG_BY_ORDER.getOrDefault(orderId, 1.0);
            return kg <= 3.0 ? 20.0 : 60.0;
        }, pool);
    }

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(4);
        try {
            System.out.println("== thenCompose: the ETA needs the warehouse first ==");
            String report = lookupWarehouse("ORD-201", pool)
                    .thenCompose(warehouse -> fetchEtaDays(warehouse, pool)
                            .thenApply(days -> "ORD-201 ships from " + warehouse + ", arrives in " + days + " day(s)"))
                    .join();
            System.out.println(report);

            System.out.println();
            System.out.println("== thenCombine: ETA and packaging fee fetched in parallel ==");
            long start = System.nanoTime();
            String both = fetchEtaDays("chennai-wh-1", pool)
                    .thenCombine(fetchPackagingFee("ORD-202", pool),
                            (days, fee) -> "eta " + days + " day(s), packaging fee Rs. " + fee)
                    .join();
            long tookMs = (System.nanoTime() - start) / 1_000_000;
            System.out.println(both);
            System.out.println("ran in parallel, under 280 ms: " + (tookMs < 280));

            System.out.println();
            System.out.println("== exceptionally: recover instead of crashing ==");
            String recovered = lookupWarehouse("ORD-999", pool)
                    .thenApply(warehouse -> "found " + warehouse)
                    .exceptionally(error -> "fallback: " + error.getCause().getMessage())
                    .join();
            System.out.println(recovered);

            System.out.println();
            System.out.println("== orTimeout: give up on a call that is taking too long ==");
            try {
                CompletableFuture.supplyAsync(() -> {
                    sleep(2000);
                    return "very late warehouse";
                }, pool).orTimeout(100, TimeUnit.MILLISECONDS).join();
            } catch (CompletionException e) {
                System.out.println("timed out: " + e.getCause().getClass().getSimpleName());
            }

            System.out.println();
            System.out.println("== completeOnTimeout: fall back to a cached value instead ==");
            String cached = CompletableFuture.supplyAsync(() -> {
                sleep(2000);
                return "very late warehouse";
            }, pool).completeOnTimeout("cached: pune-wh-1 (stale)", 100, TimeUnit.MILLISECONDS).join();
            System.out.println(cached);
        } finally {
            pool.shutdownNow();
        }
    }
}

solutions/ex06.java

// Exercise 6: ConcurrentHashMap counts votes cast from several threads at once,
// and a BlockingQueue hands railway booking slips from one producer to two clerks.

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;

class Ex06 {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("== ConcurrentHashMap: vote counts updated from four threads ==");
        Map<String, Integer> voteCounts = new ConcurrentHashMap<>();
        List<String> votes = List.of("INDIA", "NOTA", "INDIA", "BJP", "INDIA", "BJP", "NOTA", "BJP", "INDIA");
        List<Thread> counters = new ArrayList<>();
        for (int t = 0; t < 4; t++) {
            int shard = t;
            Thread worker = new Thread(() -> {
                for (int i = shard; i < votes.size(); i += 4) {
                    voteCounts.merge(votes.get(i), 1, Integer::sum);
                }
            });
            counters.add(worker);
            worker.start();
        }
        for (Thread worker : counters) {
            worker.join();
        }
        System.out.println("INDIA: " + voteCounts.get("INDIA") + ", BJP: " + voteCounts.get("BJP")
                + ", NOTA: " + voteCounts.get("NOTA"));
        int total = voteCounts.values().stream().mapToInt(Integer::intValue).sum();
        System.out.println("total counted matches total votes: " + (total == votes.size()));

        System.out.println();
        System.out.println("== BlockingQueue: one producer, two counter clerks, no explicit lock ==");
        BlockingQueue<String> bookingSlips = new LinkedBlockingQueue<>();
        String stop = "__STOP__";
        List<String> issued = new CopyOnWriteArrayList<>();
        List<Thread> clerks = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            Thread clerk = new Thread(() -> {
                while (true) {
                    String slip;
                    try {
                        slip = bookingSlips.take();   // waits here until a slip arrives
                    } catch (InterruptedException e) {
                        return;
                    }
                    if (slip.equals(stop)) {
                        return;
                    }
                    issued.add(slip);
                }
            });
            clerks.add(clerk);
            clerk.start();
        }
        for (String passenger : List.of("Amit", "Fatima", "Suresh", "Divya", "Kiran")) {
            bookingSlips.put(passenger);
        }
        bookingSlips.put(stop);
        bookingSlips.put(stop);   // one stop signal per clerk
        for (Thread clerk : clerks) {
            clerk.join();
        }
        System.out.println("issued count: " + issued.size());
        System.out.println("all five passengers issued: " + (new java.util.HashSet<>(issued).containsAll(
                List.of("Amit", "Fatima", "Suresh", "Divya", "Kiran"))));
    }
}

solutions/ex07.java

// Exercise 7: 5,000 blocking "bank status check" calls, compared on a capped
// platform-thread pool versus one virtual thread per task.

import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

class Ex07 {

    public static void main(String[] args) {
        System.out.println("== a virtual thread, up close ==");
        Thread virtual = Thread.ofVirtual().name("bank-check-", 0).unstarted(() -> {});
        System.out.println("isVirtual: " + virtual.isVirtual());
        System.out.println("isDaemon: " + virtual.isDaemon());

        int tasks = 5_000;
        AtomicInteger done = new AtomicInteger();

        System.out.println();
        System.out.println("== 5,000 blocking bank status checks, platform threads (capped pool) ==");
        long platformStart = System.nanoTime();
        try (ExecutorService platformPool = Executors.newFixedThreadPool(100)) {
            for (int i = 0; i < tasks; i++) {
                platformPool.submit(() -> {
                    try {
                        Thread.sleep(Duration.ofMillis(20));
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                    done.incrementAndGet();
                });
            }
        }
        long platformMs = (System.nanoTime() - platformStart) / 1_000_000;
        System.out.println("completed: " + done.get());
        System.out.println("100 platform threads took: " + platformMs + " ms  (varies)");

        done.set(0);
        System.out.println();
        System.out.println("== the same 5,000 checks, one virtual thread per task ==");
        long virtualStart = System.nanoTime();
        try (ExecutorService virtualPool = Executors.newVirtualThreadPerTaskExecutor()) {
            IntStream.range(0, tasks).forEach(i -> virtualPool.submit(() -> {
                try {
                    Thread.sleep(Duration.ofMillis(20));
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
                done.incrementAndGet();
            }));
        }
        long virtualMs = (System.nanoTime() - virtualStart) / 1_000_000;
        System.out.println("completed: " + done.get());
        System.out.println("5,000 virtual threads took: " + virtualMs + " ms  (varies)");
        System.out.println("virtual threads finished faster than the capped platform pool: " + (virtualMs < platformMs));
    }
}

solutions/ex08.java

// Exercise 8 (capstone): check seat availability for 6 trains against a local,
// JDK-only HttpServer, in parallel on virtual threads, each call wrapped in a
// CompletableFuture with completeOnTimeout so one slow train never holds up the rest.

import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Ex08 {

    static final List<String> TRAINS = List.of("12345", "12951", "22691", "12627", "SLOW1", "16032");
    static final long NORMAL_DELAY_MS = 100;
    static final long SLOW_DELAY_MS = 3000;   // "SLOW1" never answers within the timeout below

    static HttpServer startAvailabilityServer() throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/availability/", exchange -> {
            String train = exchange.getRequestURI().getPath().substring("/availability/".length());
            try {
                Thread.sleep(train.equals("SLOW1") ? SLOW_DELAY_MS : NORMAL_DELAY_MS);
                String body = "train " + train + ": 12 seats available";
                byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
                exchange.sendResponseHeaders(200, bytes.length);
                exchange.getResponseBody().write(bytes);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                exchange.close();
            }
        });
        server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
        server.start();
        return server;
    }

    static String fetch(HttpClient client, String baseUrl, String train) throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + "/availability/" + train)).build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = startAvailabilityServer();
        String baseUrl = "http://127.0.0.1:" + server.getAddress().getPort();
        HttpClient client = HttpClient.newHttpClient();
        Map<String, String> results = new ConcurrentHashMap<>();
        try {
            System.out.println(TRAINS.size() + " trains, checked in parallel, SLOW1 deliberately too slow");
            long start = System.nanoTime();
            // NOT try-with-resources on purpose: ExecutorService.close() waits for every
            // submitted task to finish, including the still-running SLOW1 call -- that would
            // silently cancel the whole point of completeOnTimeout below. Shut it down,
            // unawaited, only after the timing that matters is already captured.
            ExecutorService virtualPool = Executors.newVirtualThreadPerTaskExecutor();
            List<CompletableFuture<Void>> checks = TRAINS.stream()
                    .map(train -> CompletableFuture
                            .supplyAsync(() -> {
                                try {
                                    return fetch(client, baseUrl, train);
                                } catch (IOException | InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                            }, virtualPool)
                            .completeOnTimeout("train " + train + ": unknown, try again later", 500, TimeUnit.MILLISECONDS)
                            .thenAccept(result -> results.put(train, result)))
                    .toList();
            CompletableFuture.allOf(checks.toArray(new CompletableFuture[0])).join();
            long tookMs = (System.nanoTime() - start) / 1_000_000;
            virtualPool.shutdownNow();   // cleanup now; the still-running SLOW1 call is abandoned

            for (String train : TRAINS) {
                System.out.println(results.get(train));
            }
            System.out.println();
            System.out.println("all trains answered (fallback counts as answered): " + (results.size() == TRAINS.size()));
            System.out.println("SLOW1 fell back instead of blocking everyone: "
                    + results.get("SLOW1").contains("unknown, try again later"));
            System.out.println("finished well under the slow train's own 3000 ms delay: " + (tookMs < 1500) + "  (varies)");
        } finally {
            server.stop(0);
        }
    }
}

Common mistakes

Mistake Why it is wrong Fix
Calling thread.run() instead of thread.start() Runs the code on the current thread, like any normal method call — nothing happens in the background Always start() to actually hand work to a new thread
count++ (or any read-modify-write) on a field shared across threads, unguarded Not atomic: a lost update is a real possibility, and "it worked in testing" proves nothing synchronized, an AtomicInteger/AtomicLong, or a java.util.concurrent collection's atomic method
Reading a plain (non-volatile, non-synchronized) flag from another thread in a spin loop No guarantee the write is ever seen — may spin forever volatile for a simple flag; synchronized when more than one variable needs to move together
Acquiring two locks in different orders in different threads Deadlock: both threads wait forever, each holding what the other needs Always acquire locks in one fixed, agreed order
Submitting work to an ExecutorService and never calling shutdown() The pool's worker threads keep running, keeping the JVM alive past main pool.shutdown() (or a try-with-resources ExecutorService, Java 19+) when done
thenApply where the function returns another CompletableFuture Leaves you with a CompletableFuture<CompletableFuture<T>>, not the value you wanted thenCompose when the next step is itself async
new ArrayList<>() / new HashMap<>() shared and mutated across threads, with no protection at all ConcurrentModificationException, lost updates, or silent corruption A java.util.concurrent collection, or your own synchronized guard around every access
Running CPU-bound work on virtual threads expecting a speed-up Virtual threads help with blocking I/O; CPU-bound work still occupies a carrier the whole time Platform threads (or a fixed pool sized to CPU cores) for CPU-bound work

Quick recap

  • Thread wraps a Runnable; start() runs it in the background, join() waits for it; setDaemon(true) lets it die silently with the JVM.
  • A race condition is a bug in shared mutable state's timing, not its logic; synchronized fixes atomicity, volatile fixes visibility for a simple flag, and both matter.
  • Two synchronized blocks locked in opposite order by two threads deadlock; always lock in one fixed order.
  • ExecutorService reuses a pool of threads for many tasks; Callable+Future returns a value (or re-throws a wrapped exception) instead of just running.
  • CompletableFuture chains async work without blocking a thread to wait: thenCompose for dependent steps, thenCombine for independent ones, exceptionally/completeOnTimeout for fallbacks.
  • ConcurrentHashMap, CopyOnWriteArrayList and BlockingQueue are already thread-safe, often without you writing a single synchronized block.
  • A virtual thread (JEP 444, Java 21) is cheap and shines for blocking I/O; it buys nothing for CPU-bound work, and a synchronized block that blocks still pins it to its carrier in Java 21.

Checklist

  • I started a Thread from a Runnable, named it, and used join() to wait for it.
  • I reproduced a lost-update race on purpose, then fixed it with synchronized.
  • I can explain why a plain boolean flag can fail to be seen by another thread, and what volatile fixes.
  • I reproduced a deadlock with two locks in opposite order, then fixed it with a fixed lock order.
  • I submitted Callable tasks to an ExecutorService and read results back through Future, including a failed one.
  • I chained a CompletableFuture with thenCompose (dependent) and thenCombine (independent), and handled a timeout.
  • I used ConcurrentHashMap.merge and a BlockingQueue producer/consumer without writing my own lock.
  • I ran the same blocking workload on a capped platform-thread pool and on virtual threads, and compared the timings myself.
  • I built the parallel price downloader and confirmed all three methods return identical prices.

Search the guide