JAVA-240 · Lesson 12 of 12 · 33 min

Capstone: a concurrent order processor

▶ Video coming soon A video version of this lesson is on the way.

The plan for the first week of April 2028 is simple to say and harder to do. Hamza will turn OrderRun, Kofi's one-order-at-a-time program from lesson 1, into OrderDesk, which handles a spring Saturday's inbox concurrently without losing a part, selling a pad twice or putting three bikes into a slot that two mechanics can serve. On Monday, April 10, 2028, he will walk Ingrid, Kofi and Odile through it in the back room, and Odile will decide whether it runs on the first busy Saturday. This lesson is that build, written ahead of time like the rest of the course. Every listing that prints output was compiled and run on Java 21, many times, with identical results.

A capstone is less about new tools than about choosing among the ones you have. Every lesson so far gave Hamza at least one tool; OrderDesk needs about half of them, and the skill being tested is knowing which half, and why the others would be wrong here.

The requirements

Odile and Kofi wrote the requirements on one page. Hamza numbered them so that the review can go through them one by one, and so that each piece of the code can say which requirement it serves.

OrderDesk requirements
#RequirementWhere it comes from
R1Read every inbox line once, in order, and produce exactly one result per lineOdile: no order may vanish, and none may be handled twice
R2Never hold more than 5 connections to the supplier at onceThe supplier's limit for small shops
R3Reserve stock first come, first served by inbox order, never below zero, with any shortfall put on backorderKofi's minus-one tube bug from lesson 3
R4Book repairs only from 9:00 to 15:00 starts, at most 2 bikes per hour, at most 12 on the rackTamsin's two mechanics and the 12-bike rack
R5If a price check takes more than half a second, use the last known priceThe counter cannot wait on a slow supplier
R6An unknown part or a bad line produces an error result, not a crashOne bad form must not stop a Saturday
R7Print the results sorted by order number, with totals and remaining stockThe picking list and the counter screen
R8Finish a full inbox in a few seconds, and shut down cleanlyOrderRun took more than a second per order

R1 and R7 are about correctness and order; R2, R5 and R8 are about time and limits; R3 and R4 are about shared state. That grouping matters, because each group calls for a different kind of tool.

From requirements to tools

Ingrid's advice is to decide, before writing code, where every piece of shared mutable state lives and who may change it. OrderDesk has only three pieces: the stock counts, the repair bookings and the results. Everything else, the inbox lines, the requests built from them and the prices, is either immutable or belongs to a single task.

Each need mapped to the tool that serves it
NeedToolLesson
Many slow price checks at onceA virtual-thread-per-task executor8
At most 5 supplier connectionsA Semaphore with 5 permits8
Stock that many threads may changeConcurrentHashMap with computeIfPresent5
Strict first-come order for stockReserving on the single intake thread3 and 10
Bookings with several linked rulesThread confinement on a single-thread executor6
A price with a time limit and a fallbackCompletableFuture with completeOnTimeout7
Results gathered from many tasksConcurrentHashMap, then a sorted TreeMap copy5
Waiting for everything to finishtry-with-resources on the executors6
A flow diagram. On the left, an inbox file feeds an intake thread that parses each line and reserves stock in a concurrent map. From the intake thread, part orders go to many virtual threads, which pass through a semaphore of five permits to the supplier, and repair bookings go to a single booking desk thread that owns the slot table. Both paths write into a results map, which is copied into a sorted map and printed as the picking list.
OrderDesk: one intake thread, many pricing tasks, one booking desk

The figure shows the shape. One intake thread reads the inbox in order. Part orders reserve their stock right there, on the intake thread, and then go to virtual threads for pricing, which hand the supplier call itself to a third executor. Repair bookings go to a booking desk, a single thread that alone owns the slot table. Every task writes its result into a concurrent map keyed by order number, and when all the executors have closed, main copies that map into a TreeMap and prints it.

Stock: atomic and in order

R3 has two halves. Never below zero is an atomicity problem: the check of what is left and the subtraction must happen as one step, which is exactly what ConcurrentHashMap's compute methods give. First come, first served is an ordering problem, and no map can solve it, because when two pricing tasks reach the map at nearly the same moment, which one gets there first is up to the scheduler. Hamza's answer is to reserve on the intake thread, which sees the lines in inbox order. The reserve method is still safe to call from any thread, and the program below proves it by calling it from a thousand virtual threads at once.

Java Example · Main.java
import java.util.*;
import java.util.concurrent.*;

public class Main {
    static final ConcurrentHashMap<String, Integer> stock = new ConcurrentHashMap<>(Map.of("PAD-ROAD", 500));

    static int reserve(String part, int qty) {
        int[] got = new int[1];
        stock.computeIfPresent(part, (k, left) -> {
            got[0] = Math.min(left, qty);
            return left - got[0];
        });
        return got[0];
    }

    public static void main(String[] args) throws Exception {
        List<Future<Integer>> futures = new ArrayList<>();
        try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 1_000; i++) {
                futures.add(ex.submit(() -> reserve("PAD-ROAD", 1)));
            }
        }
        int handedOut = 0;
        for (Future<Integer> f : futures) handedOut += f.get();
        System.out.println("requests: " + futures.size());
        System.out.println("pads handed out: " + handedOut);
        System.out.println("pads left: " + stock.get("PAD-ROAD"));
        System.out.println("unknown part: " + reserve("SPOKE-286", 4));
    }
}
Output
requests: 1000
pads handed out: 500
pads left: 0
unknown part: 0

What this code does

A thousand virtual threads each try to reserve one road pad from a stock of 500. Because computeIfPresent runs the check and the subtraction atomically for that key, exactly 500 requests get a pad and the stock stops at zero rather than going negative. An unknown part has no entry, so computeIfPresent does nothing and the method returns zero.

The one-element array got carries the amount out of the lambda, since a lambda cannot assign to a local variable. It is safe here because each call creates its own array and the map runs the lambda once, on the calling thread. Using computeIfPresent rather than compute means an unknown part is not quietly added to the map with a stock of zero.

Prices: a limited, slow supplier

Each price check holds a supplier connection for about a tenth of a second in the next program, and for 20 milliseconds in the full OrderDesk rehearsal, standing in for the real second. Virtual threads make it cheap to start one task per order, but R2 says no more than five may talk to the supplier at once. A Semaphore with five permits, from lesson 8, enforces that, and a try and finally block makes sure the permit goes back even when the check fails. The next program measures the limit instead of trusting it.

Java Example · Main.java
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static final Semaphore supplier = new Semaphore(5);
    static final AtomicInteger inUse = new AtomicInteger();
    static final AtomicInteger mostAtOnce = new AtomicInteger();

    static int supplierPrice(int n) throws InterruptedException {
        supplier.acquire();
        try {
            mostAtOnce.accumulateAndGet(inUse.incrementAndGet(), Math::max);
            Thread.sleep(100);
            return 1000 + n;
        } finally {
            inUse.decrementAndGet();
            supplier.release();
        }
    }

    public static void main(String[] args) throws Exception {
        long start = System.nanoTime();
        List<Future<Integer>> prices = new ArrayList<>();
        try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int n = 0; n < 40; n++) {
                int part = n;
                prices.add(ex.submit(() -> supplierPrice(part)));
            }
        }
        long millis = (System.nanoTime() - start) / 1_000_000;
        int sum = 0;
        for (Future<Integer> f : prices) sum += f.get();
        System.out.println("prices fetched: " + prices.size() + ", sum " + sum);
        System.out.println("most connections at once: " + mostAtOnce.get());
        System.out.println("at least 800 ms (8 rounds of 5): " + (millis >= 800));
        System.out.println("well under 4 s (one at a time): " + (millis < 2_000));
    }
}
Output
prices fetched: 40, sum 40780
most connections at once: 5
at least 800 ms (8 rounds of 5): true
well under 4 s (one at a time): true

What this code does

Forty price checks start at once on virtual threads, but the semaphore lets only five hold a connection at the same time, as the mostAtOnce counter confirms. With five at a time and a tenth of a second each, forty checks need at least eight rounds, so the run takes at least 800 milliseconds but far less than the four seconds that one-at-a-time checking would need. The timings are printed as true or false so the output is the same on every run.

This is also where virtual threads earn their place. Forty platform threads would be fine, but on a spring Saturday the inbox may hold several hundred lines, and most of their threads would spend their lives waiting for a permit. A waiting virtual thread costs a few hundred bytes of heap; a waiting platform thread costs an operating system thread and its stack.

R5 adds a time limit. CompletableFuture's completeOnTimeout, from lesson 7, completes the future with a fallback value if the real one has not arrived in time. Kofi keeps a small table of last known prices; if a part has no entry, the fallback is minus one, which the review will want to discuss. Note that completeOnTimeout does not stop the slow task. The supplier call keeps running until it returns, and the executor's close waits for it, which is why the whole run below takes a little over two seconds even though no order waits more than half a second for its price.

Bookings: one owner for linked rules

R4 has three rules that depend on each other: the hour must be open, the hour must have a free mechanic, and the rack must have room. A ConcurrentHashMap could make each counter safe on its own, but the rules must be checked and applied together, so a booking needs one lock around all three checks, or one thread that alone touches the table. Hamza chooses the second. The booking desk is a single-thread executor, and the slot table and the rack count are plain fields that only that thread reads or writes. Because the intake thread submits bookings in inbox order, and a single-thread executor runs its tasks in the order they were submitted, bookings are also first come, first served.

Confinement is easy to break by accident: one helper method called from a pricing task would bring back every race from lesson 3. So the code keeps the booking method next to the executor that owns it, and a comment says that the table belongs to the booking desk. In the review, Kofi will ask what happens if the rack ever needs to be read from the counter screen too. The answer is that the screen asks the desk, by submitting a task and waiting on its future, instead of reading the fields directly.

The whole program

Here is OrderDesk as it will be shown on April 10, with a rehearsal inbox of sixteen lines that covers every requirement: orders that fit, orders that run short, an unknown part, a slow price, full and closed repair slots and an open one. In production the inbox comes from the web form's file and the prices from the supplier; here both are small tables so the run can be checked.

Java Example · Main.java
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

public class Main {
    sealed interface Request permits PartOrder, RepairBooking {}
    record PartOrder(int id, String part, int qty) implements Request {}
    record RepairBooking(int id, String bike, int hour) implements Request {}
    record Result(int id, String text, int cents) {}

    // R2: the supplier allows 5 connections; a rehearsal price check takes 20 ms
    static final Semaphore supplier = new Semaphore(5);
    static final Map<String, Integer> priceList = Map.of(
            "TUBE-700x25", 899, "PAD-ROAD", 1499, "CHAIN-11", 3999,
            "BELL", 1250, "CABLE-BRAKE", 450, "PUMP-FLOOR", 3450);
    static final Map<String, Integer> lastKnown = Map.of("PUMP-FLOOR", 3299);

    static int supplierPrice(String part) throws InterruptedException {
        supplier.acquire();
        try {
            Thread.sleep(part.equals("PUMP-FLOOR") ? 2_000 : 20);
            Integer cents = priceList.get(part);
            if (cents == null) throw new IllegalArgumentException("unknown part " + part);
            return cents;
        } finally {
            supplier.release();
        }
    }

    // R3: reserve stock atomically; never below zero
    static final ConcurrentHashMap<String, Integer> stock = new ConcurrentHashMap<>(Map.of(
            "TUBE-700x25", 14, "PAD-ROAD", 3, "CHAIN-11", 1, "BELL", 3, "CABLE-BRAKE", 20, "PUMP-FLOOR", 2));

    static int reserve(String part, int qty) {
        int[] got = new int[1];
        stock.computeIfPresent(part, (k, left) -> {
            got[0] = Math.min(left, qty);
            return left - got[0];
        });
        return got[0];
    }

    // R4: Saturday repair slots 9:00 to 15:00, two mechanics per hour, at most 12 bikes on the rack
    static final Map<Integer, Integer> booked = new TreeMap<>();
    static int bikesOnRack = 0;

    static String book(RepairBooking b) {
        if (b.hour() < 9 || b.hour() > 15) return "no slot at " + b.hour() + ":00";
        if (bikesOnRack == 12) return "rack full";
        int taken = booked.getOrDefault(b.hour(), 0);
        if (taken == 2) return b.hour() + ":00 full";
        booked.put(b.hour(), taken + 1);
        bikesOnRack++;
        return "booked " + b.hour() + ":00";
    }

    static Request parse(String line) {
        String[] f = line.split(",");
        int id = Integer.parseInt(f[0]);
        return switch (f[1]) {
            case "P" -> new PartOrder(id, f[2], Integer.parseInt(f[3]));
            case "R" -> new RepairBooking(id, f[2], Integer.parseInt(f[3]));
            default -> throw new IllegalArgumentException("bad line " + line);
        };
    }

    static Result handlePart(PartOrder o, int got, ExecutorService ex) {
        CompletableFuture<Integer> price = CompletableFuture
                .supplyAsync(() -> {
                    try { return supplierPrice(o.part()); }
                    catch (InterruptedException e) { throw new CompletionException(e); }
                }, ex)
                .completeOnTimeout(lastKnown.getOrDefault(o.part(), -1), 500, TimeUnit.MILLISECONDS);
        int cents;
        try {
            cents = price.join();
        } catch (CompletionException e) {
            return new Result(o.id(), o.part() + ": " + e.getCause().getMessage(), 0);
        }
        String note = got == o.qty() ? "" : ", " + (o.qty() - got) + " on backorder";
        return new Result(o.id(), o.part() + ": " + got + " of " + o.qty() + " at " + cents + note, got * cents);
    }

    public static void main(String[] args) throws Exception {
        List<String> inbox = List.of(
                "2001,P,TUBE-700x25,2", "2002,R,commuter,10", "2003,P,PAD-ROAD,2", "2004,P,CHAIN-11,1",
                "2005,R,cargo bike,10", "2006,P,PUMP-FLOOR,1", "2007,R,tandem,10", "2008,P,PAD-ROAD,2",
                "2009,P,SPOKE-286,4", "2010,P,BELL,1", "2011,R,road bike,17", "2012,P,CHAIN-11,1",
                "2013,P,CABLE-BRAKE,4", "2014,R,kids bike,11", "2015,P,TUBE-700x25,3", "2016,P,BELL,2");

        long start = System.nanoTime();
        Map<Integer, Result> results = new ConcurrentHashMap<>();
        // closed in reverse order: workers first, then the booking desk, then the supplier calls
        try (ExecutorService supplierCalls = Executors.newVirtualThreadPerTaskExecutor();
             ExecutorService bookingDesk = Executors.newSingleThreadExecutor();
             ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor()) {
            for (String line : inbox) {
                Request r = parse(line);
                switch (r) {
                    case RepairBooking b -> bookingDesk.submit(() -> results.put(b.id(), new Result(b.id(), b.bike() + ": " + book(b), 0)));
                    case PartOrder o -> {
                        int got = reserve(o.part(), o.qty());
                        workers.submit(() -> results.put(o.id(), handlePart(o, got, supplierCalls)));
                    }
                }
            }
        }
        long millis = (System.nanoTime() - start) / 1_000_000;

        int total = 0;
        for (Result res : new TreeMap<>(results).values()) {
            System.out.println(res.id() + "  " + res.text());
            total += res.cents();
        }
        System.out.println("requests: " + inbox.size() + ", results: " + results.size());
        System.out.println("parts total: " + total + " cents");
        System.out.println("stock left: " + new TreeMap<>(stock));
        System.out.println("finished in under 10 seconds: " + (millis < 10_000));
    }
}
Output
2001  TUBE-700x25: 2 of 2 at 899
2002  commuter: booked 10:00
2003  PAD-ROAD: 2 of 2 at 1499
2004  CHAIN-11: 1 of 1 at 3999
2005  cargo bike: booked 10:00
2006  PUMP-FLOOR: 1 of 1 at 3299
2007  tandem: 10:00 full
2008  PAD-ROAD: 1 of 2 at 1499, 1 on backorder
2009  SPOKE-286: unknown part SPOKE-286
2010  BELL: 1 of 1 at 1250
2011  road bike: no slot at 17:00
2012  CHAIN-11: 0 of 1 at 3999, 1 on backorder
2013  CABLE-BRAKE: 4 of 4 at 450
2014  kids bike: booked 11:00
2015  TUBE-700x25: 3 of 3 at 899
2016  BELL: 2 of 2 at 1250
requests: 16, results: 16
parts total: 21840 cents
stock left: {BELL=0, CABLE-BRAKE=16, CHAIN-11=0, PAD-ROAD=0, PUMP-FLOOR=1, TUBE-700x25=9}
finished in under 10 seconds: true

What this code does

The intake loop in main parses each line into a sealed Request, reserves stock for part orders in inbox order, and hands pricing to virtual threads and bookings to the single booking desk thread. The three executors close in reverse order of declaration, workers first and supplier calls last, and each close waits for its tasks, so main reads the results map only after all writes have finished. Results are printed in order-number order from a TreeMap copy, which makes the picking list identical on every run.

Read the output against the requirements. Every one of the sixteen lines produced exactly one result (R1). Each part line shows how many units were reserved out of how many were asked for. There were three road pads: order 2003 asked for two and got both, so when 2008 asked for two more only one was left, and the other went on backorder. The single chain went to 2004, the earlier order, and 2012 got none of its one. Run the program as often as you like and the same orders win, because the reservations happen on the intake thread in inbox order (R3).

Order 2006 asked for a floor pump. The rehearsal supplier takes two seconds for that part, so after half a second the future completed with Kofi's last known price of 3,299 cents instead of the current 3,450 (R5). Order 2009 named a part the supplier does not know, and it produced an error result while every other order carried on (R6). The 10:00 slot took the commuter and the cargo bike and turned the tandem away, a 17:00 booking was refused, and the kids' bike got 11:00 (R4). The parts total counts only what was actually reserved, so backordered units are not charged. And the last line confirms that the run finished well inside its time budget (R8). On a normal machine it takes a little over two seconds, almost all of it the one slow supplier call; the check is printed as true or false against a generous ten-second limit, so that a busy machine cannot change the output, while OrderRun would have needed sixteen seconds for the same inbox.

Why each choice, and what was rejected

Hamza expects to be asked why he did not use the simplest tool for each job, so he wrote his reasons down. A synchronized method on a shared Shop object for stock would have worked, but it would have made every pricing task wait for every other, even for unrelated parts; the map locks only per key. A fixed pool of five platform threads would have met R2 without a semaphore, but it would also have held back the bookings and the error handling behind slow price checks; the semaphore limits only the thing that is actually limited. A BlockingQueue pipeline from lesson 10 would be the right shape if the inbox were a stream that never ends, and that is the plan for when the web form writes directly to OrderDesk instead of to a file. For a file that is read once each morning, three executors and a results map are simpler.

Choices Hamza expects to defend
AlternativeWhy it was not chosen
One big lock around all shared stateCorrect, but price checks for different parts would wait for each other
A fixed pool of 5 threads for everythingBookings and errors would queue behind slow price checks
Reserving stock inside the pricing tasksSafe, but the scheduler, not the inbox, would decide who gets the last pad
A ConcurrentHashMap for each booking counterEach counter safe alone, but the three rules must be checked together
Printing results as tasks finishThe picking list would come out in a different order every run
cancel on the slow futurecancel on a CompletableFuture does not interrupt the supplier call

Shutting down and failing well

R8 asks for a clean shutdown as well as speed. The try-with-resources block does the work: close on an ExecutorService stops new tasks and waits for submitted ones, so by the time main prints, no task is still writing. If something must stop OrderDesk early, for example the shop's power failing over to the battery, shutdownNow interrupts the tasks; supplierPrice is written to let InterruptedException escape, and the pricing lambda wraps it in a CompletionException, so an interrupted check turns into an error result rather than a missing one.

The order of the executors in that try statement matters, and Hamza learned it the hard way. His first draft sent each supplier call to the same executor as the pricing tasks. When the intake loop finished, closing that executor called shutdown, and any pricing task that had not yet reached its supplyAsync call was refused with a RejectedExecutionException. The exception went into the task's Future, which nobody read, so on a busy machine the run printed only five results for sixteen requests, and on a quiet one it printed all sixteen. Giving the supplier calls their own executor, declared first so that it closes last, fixed it, and the rehearsal inbox, run many times, now prints the same sixteen results every time. It is lesson 11's warning in miniature: an exception in a task is silent unless something reads its future.

Leif's checklist from lesson 11 is the last pass. Each piece of shared state has one documented owner or one thread-safe class. The only lock-like object, the semaphore, is released in a finally block. Every wait is bounded: price lookups by completeOnTimeout, and the executors by tasks that themselves finish. And there is a stress test, the thousand-thread reservation program above, for the one method that many threads can reach. Hamza adds one more item: the rehearsal inbox is kept as a test, and its expected output is checked into the build, so a later change that breaks first-come order or the rack limit fails the build the same day.

What OrderDesk might look like on Java 28

Structured concurrency, a preview feature since Java 21 that is planned to become final in Java 28, would give the pricing step a clearer shape. Instead of a future with a timeout attached, each order's work would run inside a scope that owns its subtasks, cancels the rest when one fails, and cannot outlive its block. The listing below shows the idea in the shape of the preview API in Java 25; it is not compiled in this course, and the exact method names may differ in the final release.

Java Example
// Java 25 preview API shape; not compiled in this course
static Result priceOrder(PartOrder o, int got) throws InterruptedException {
    try (var scope = StructuredTaskScope.open(
            StructuredTaskScope.Joiner.<Integer>anySuccessfulResultOrThrow(),
            cf -> cf.withTimeout(Duration.ofMillis(500)))) {
        scope.fork(() -> supplierPrice(o.part()));
        int cents = scope.join();
        return new Result(o.id(), o.part() + ": " + got + " of " + o.qty() + " at " + cents, got * cents);
    } catch (StructuredTaskScope.TimeoutException e) {
        int cents = lastKnown.getOrDefault(o.part(), -1);
        return new Result(o.id(), o.part() + ": " + got + " of " + o.qty() + " at " + cents, got * cents);
    }
}

What this code does

In this shape the scope owns the supplier subtask, and leaving the block, whether normally or through the timeout, cancels any subtask that is still running. That fixes the one wart in the Java 21 version, where the slow supplier call kept running after its fallback price had been used. The rest of OrderDesk, the intake thread, the reservations and the booking desk, would not change.

Ingrid's point in showing this is not that Hamza should wait for it. It is that the design, one owner for each piece of state and bounded waits everywhere, survives a change of tools. The code that would change is the few lines of pricing; the reasoning would not.

The review on April 10

Ingrid has said how the review will run. Hamza will go through R1 to R8 and, for each one, point to the line of code that serves it and the line of output that shows it. Kofi will try to break it: an inbox with two hundred lines for the same pad, a supplier that never answers, a booking at 15:00 when the rack already holds eleven bikes. Odile will ask what the counter staff see when something goes wrong, because a backorder note or a fallback price is only useful if someone reads it. If OrderDesk passes, it runs alongside OrderRun for two Saturdays, with both outputs compared, before OrderRun is retired.

Hamza's own list of open questions goes on the last page of his notes: whether a fallback price of minus one should block an order instead of passing through; whether backorders should be stored so they can be filled when stock arrives; and how the counter screen should be told about each result as it arrives, which is the CopyOnWriteArrayList of listeners from lesson 5 waiting for its turn.

Try it yourself

Reserve first come, first served

Complete reserve so that it takes up to qty units from the map atomically with computeIfPresent, never letting the stock go below zero, and returns how many it took. Unknown parts must return 0 and must not be added to the map.

With stock of 3 road pads and requests for 2, 2 and 1, the program should print 2001 got 2, 2002 got 1, 2003 got 0 and then left: {PAD-ROAD=0}.

import java.util.*;
import java.util.concurrent.*;

public class Main {
    static final ConcurrentHashMap<String, Integer> stock = new ConcurrentHashMap<>(Map.of("PAD-ROAD", 3));

    static int reserve(String part, int qty) {
        // take up to qty atomically with computeIfPresent and return how many were taken
        return 0;
    }

    public static void main(String[] args) {
        int[][] orders = {{2001, 2}, {2002, 2}, {2003, 1}};
        for (int[] o : orders) System.out.println(o[0] + " got " + reserve("PAD-ROAD", o[1]));
        reserve("SPOKE-286", 4);
        System.out.println("left: " + new TreeMap<>(stock));
    }
}

Try it yourself

A price with a deadline

The slow supplier takes a full second for a floor pump. Change the lookup so that if the price has not arrived within 200 milliseconds, the future completes with the last known price of 3299 instead.

The program should print price: 3299.

import java.util.concurrent.*;

public class Main {
    static int slowPrice() {
        try { Thread.sleep(1_000); } catch (InterruptedException e) { return -1; }
        return 3450;
    }

    public static void main(String[] args) {
        try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
            CompletableFuture<Integer> price = CompletableFuture.supplyAsync(Main::slowPrice, ex);
            System.out.println("price: " + price.join());
        }
    }
}

Common mistakes

  • MistakeReserving stock inside concurrent tasks and expecting inbox order.

    InsteadAtomic methods prevent overselling, but only a single thread that sees the lines in order can make reservations first come, first served.

  • MistakeMaking each booking counter thread-safe separately.

    InsteadRules that depend on each other need one lock around all of them, or one thread that owns the whole table.

  • MistakeUsing a small fixed pool to enforce a supplier limit.

    InsteadLimit only the scarce resource with a Semaphore, so other work does not queue behind it.

  • MistakeAssuming completeOnTimeout stops the slow task.

    InsteadIt completes the future with a fallback; the task keeps running until it returns, and close waits for it.

  • MistakePrinting results as tasks finish.

    InsteadCollect results by key and print a sorted copy after the executors have closed.

  • MistakeSubmitting new work to an executor that may already be shutting down.

    InsteadGive follow-up work its own executor that closes after the tasks that use it, and read every future so a rejection is noticed.

Summary and key terms

  • OrderDesk turns the requirements R1 to R8 into a small set of tools, chosen by first deciding where each piece of shared mutable state lives.
  • One intake thread reads the inbox in order and reserves stock with ConcurrentHashMap's computeIfPresent, which makes each reservation atomic and keeps inbox order.
  • Pricing runs on virtual threads, limited to five supplier connections by a Semaphore released in finally, with completeOnTimeout supplying the last known price when the supplier is slow.
  • Repair bookings are confined to a single-thread booking desk, because their three rules must be checked together.
  • Results go into a concurrent map and are printed from a sorted copy after try-with-resources has closed all three executors.
  • Each rejected alternative has a reason, the rehearsal inbox becomes a test, and structured concurrency on a later Java release would change only the pricing step.
Requirement
A numbered, testable statement of what the program must do.
Intake thread
The single thread that reads the inbox in order and starts the work for each line.
Thread confinement
Keeping data reachable from only one thread so it needs no lock.
Booking desk
OrderDesk's single-thread executor that alone owns the repair slot table.
Fallback price
The last known price used when the supplier does not answer in time.
Backorder
The part of an order that could not be filled from current stock.
Rehearsal inbox
A small, fixed input that covers every requirement and is kept as a test.
Structured concurrency
An API in which a scope owns its subtasks and cannot finish before them.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why does OrderDesk reserve stock on the intake thread instead of in the pricing tasks?

    Show answer

    Only the intake thread sees the lines in inbox order, so reserving there makes stock first come, first served.

  2. Which tool enforces the supplier's limit of five connections?

    Show answer

    A Semaphore with five permits, acquired before each price check and released in finally.

  3. Why are bookings confined to one thread rather than kept in a ConcurrentHashMap?

    Show answer

    The hour, mechanic and rack rules must be checked and applied together.

  4. Why does the full run take about two seconds even though no order waits more than half a second?

    Show answer

    completeOnTimeout does not stop the slow supplier call, and closing the executor waits for it.

  5. How does OrderDesk print the same picking list on every run?

    Show answer

    It prints from a TreeMap copy of the results after all three executors have closed.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz