Skip to content
KALANBLON
Show contents

Chapter 6 of 7 · 30 min

Project: processing orders in parallel

By the end of this chapter, you'll be able to

  • Model a stream of events with a sealed interface and validated records
  • Parallelise slow calls with virtual threads without losing the order of results
  • Apply business rules with an exhaustive switch and guards
  • Isolate the concurrent part to keep the rest of the code simple and testable

Step 1: the architecture

The trap in such a project would be to parallelise everything. But the order of events matters: a cancellation only makes sense after its order. So we separate two phases:

  1. Price (parallel): query the pricing service for each order. These calls are independent and slow: perfect for virtual threads.
  2. Apply (sequential): walk through the events in order and keep the balances per customer. This computation is fast, and doing it on a single thread avoids any data race.

The balances, in a TreeMap, are displayed in alphabetical order.

Step 6 of 6
Text description of the animation
  1. The evening's stream: mostly orders, a few corrections.
  2. Each order gets its price on its own virtual thread: about 100 ms in total instead of 3.1 s.
  3. A missing price becomes an error for that order, not a crash of the whole run.
  4. The events are applied one by one, in their order of arrival.
  5. A when guard rejects a refund larger than the amount collected.
  6. The balances, in a TreeMap, are displayed in alphabetical order.

Step 2: the program and its tests

import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

sealed interface Event permits Order, Cancellation, Refund {}
record Order(int id, String customer, String product, int quantity) implements Event {
    Order {
        if (quantity <= 0) {
            throw new IllegalArgumentException("invalid quantity: " + quantity);
        }
    }
}
record Cancellation(int id) implements Event {}
record Refund(int id, double amount) implements Event {}

record Line(Order order, double amount) {}

/** Simulated remote service: each call takes 100 ms. */
double unitPrice(String product) throws InterruptedException {
    Thread.sleep(Duration.ofMillis(100));
    return switch (product) {
        case "solar lamp" -> 25.0;
        case "water filter" -> 40.0;
        case "bike kit" -> 60.0;
        default -> throw new IllegalArgumentException("unknown product: " + product);
    };
}

Map<Integer, Line> price(List<Order> orders, List<String> errors) throws InterruptedException {
    Map<Integer, Line> lines = new ConcurrentHashMap<>();
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        Map<Order, Future<Double>> prices = new LinkedHashMap<>();
        for (Order o : orders) {
            prices.put(o, executor.submit(() -> unitPrice(o.product())));
        }
        for (var e : prices.entrySet()) {
            Order o = e.getKey();
            try {
                lines.put(o.id(), new Line(o, e.getValue().get() * o.quantity()));
            } catch (ExecutionException ex) {
                errors.add("order " + o.id() + ": " + ex.getCause().getMessage());
            }
        }
    }
    return lines;
}

Map<String, Double> balances(List<Event> events, Map<Integer, Line> lines, List<String> errors) {
    Map<String, Double> perCustomer = new TreeMap<>();
    Map<Integer, Double> collected = new HashMap<>();
    for (Event ev : events) {
        switch (ev) {
            case Order o when lines.containsKey(o.id()) -> {
                perCustomer.merge(o.customer(), lines.get(o.id()).amount(), Double::sum);
                collected.put(o.id(), lines.get(o.id()).amount());
            }
            case Order _ -> { }
            case Cancellation(int id) when collected.containsKey(id) -> {
                String customer = lines.get(id).order().customer();
                perCustomer.merge(customer, -collected.remove(id), Double::sum);
            }
            case Refund(int id, double a) when collected.getOrDefault(id, 0.0) >= a -> {
                String customer = lines.get(id).order().customer();
                perCustomer.merge(customer, -a, Double::sum);
                collected.merge(id, -a, Double::sum);
            }
            case Cancellation c -> errors.add("cancellation refused: order " + c.id() + " unknown or already cancelled");
            case Refund r -> errors.add("refund refused: " + r.amount() + " on order " + r.id());
        }
    }
    return perCustomer;
}

void check(boolean condition, String message) {
    if (!condition) {
        throw new AssertionError(message);
    }
}

void runTests() throws InterruptedException {
    List<String> errors = new ArrayList<>();
    Order o = new Order(1, "Ana", "bike kit", 2);
    Map<Integer, Line> lines = price(List.of(o), errors);
    check(lines.get(1).amount() == 120.0, "amount of an order");
    Map<String, Double> b = balances(List.of(o, new Refund(1, 20), new Cancellation(1), new Cancellation(1)), lines, errors);
    check(b.get("Ana") == 0.0, "cancellation after a refund");
    check(errors.size() == 1, "double cancellation refused");
    IO.println("Tests: OK");
}

void main() throws InterruptedException {
    runTests();
    List<Event> events = new ArrayList<>();
    String[] customers = {"Amara", "Bao", "Carmen"};
    String[] products = {"solar lamp", "water filter", "bike kit"};
    for (int i = 1; i <= 30; i++) {
        events.add(new Order(i, customers[i % 3], products[i % 3], 1 + i % 4));
    }
    events.add(new Order(31, "Bao", "canoe", 1));
    events.add(new Cancellation(3));
    events.add(new Refund(4, 10.0));
    events.add(new Refund(5, 1000.0));
    events.add(new Cancellation(99));

    List<String> errors = new ArrayList<>();
    List<Order> orders = events.stream()
        .flatMap(ev -> ev instanceof Order o ? Stream.of(o) : Stream.empty())
        .toList();
    long start = System.nanoTime();
    Map<Integer, Line> lines = price(orders, errors);
    long ms = (System.nanoTime() - start) / 1_000_000;
    IO.println(orders.size() + " prices fetched in parallel, under one second? " + (ms < 1000));

    Map<String, Double> perCustomer = balances(events, lines, errors);
    errors.forEach(IO::println);
    perCustomer.forEach((customer, total) -> IO.println(String.format("%-7s %8.2f €", customer, total)));
}
Tests: OK
31 prices fetched in parallel, under one second? true
order 31: unknown product: canoe
refund refused: 1000.0 on order 5
cancellation refused: order 99 unknown or already cancelled
Amara     575.00 €
Bao       910.00 €
Carmen   1500.00 €

Choices worth noticing:

  • A sealed hierarchy: the switch in balances has no default. Adding a Voucher event would break compilation at this exact spot: impossible to forget it.
  • Guards for the business rules: a cancellation is accepted only if the order was collected (when collected.containsKey(id)), a refund only if it doesn't exceed the remaining amount. The unguarded cases, placed after, catch everything else and produce an error message.
  • case Order _ -> { } explicitly ignores orders whose pricing failed: the error has already been reported.
  • The futures are started before they are awaited: the first loop submits the 31 tasks, the second reads the results. The LinkedHashMap keeps the orders' order, so the order of the error messages is stable.
  • A pricing error is isolated: ExecutionException is caught order by order, and its cause becomes a message.
  • The timing is shown as a boolean (under one second?), because an exact duration varies from one machine to another.
  • The test checks the subtlest rule: a refund of 20 followed by a cancellation brings the balance back to 0 (we only cancel what remains collected), and a second cancellation is refused.

To go further, the production version would:

  • replace unitPrice with a real HTTP client (java.net.http.HttpClient), which works very well with virtual threads;
  • limit the number of simultaneous calls to the pricing service with a Semaphore, so as not to overload it;
  • use BigDecimal rather than double for amounts, to avoid rounding errors on cents;
  • test with JUnit, replacing the slow service with a fake, instant implementation.

Your turn

Worked exercise

Solved exercise: the sales report

The cooperative wants a report on 100,000 sales lines record Line(String product, String country, double amount): the revenue per product, then the number of sales of at least €15 per country. The computations are independent from one line to the next: use parallel streams (parallelStream). The display must be sorted.

Hint 1
Collectors.groupingByConcurrent(key, downstream) groups into a ConcurrentMap that all the threads fill at once.
Hint 2
A ConcurrentHashMap isn't sorted: copy it into a TreeMap before displaying it. groupingBy with TreeMap::new also works in parallel, the partial results being merged at the end.
Show the solution and common mistakes
import java.util.concurrent.ConcurrentMap;

record Line(String product, String country, double amount) {}

void main() {
    List<Line> lines = new ArrayList<>();
    String[] products = {"solar lamp", "water filter", "bike kit"};
    String[] countries = {"Senegal", "Peru", "Vietnam", "Kenya"};
    for (int i = 0; i < 100_000; i++) {
        lines.add(new Line(products[i % 3], countries[i % 4], 10 + i % 7));
    }

    ConcurrentMap<String, Double> perProduct = lines.parallelStream()
        .collect(Collectors.groupingByConcurrent(Line::product, Collectors.summingDouble(Line::amount)));
    new TreeMap<>(perProduct).forEach((p, total) -> IO.println(String.format("%-14s %10.2f", p, total)));

    Map<String, Long> perCountry = lines.parallelStream()
        .filter(l -> l.amount() >= 15)
        .collect(Collectors.groupingBy(Line::country, TreeMap::new, Collectors.counting()));
    IO.println(perCountry);
}
bike kit        433326.00
solar lamp      433342.00
water filter    433327.00
{Kenya=7142, Peru=7143, Senegal=7142, Vietnam=7143}

A parallel stream splits the list into chunks, processed on the common pool (one thread per core), then merges the partial results. It's safe as long as the operations have no side effects: no forEach that fills a shared list, only collectors.

Common mistakes:

  • Filling a plain HashMap from a parallelStream().forEach(…): sales go missing, as in the data race from the executors chapter.
  • Parallelising a small list: below a few thousand elements, splitting costs more than it brings. Measure before choosing.

Summary

  1. 1Separate the slow, independent part (parallel) from the part that depends on order (sequential).
  2. 2Start all the tasks before waiting for their results, or the parallelism disappears.
  3. 3A sealed hierarchy and a switch with guards apply the business rules without forgetting a case.
  4. 4An error in one task is isolated and turned into a message, without stopping the processing.
  5. 5Parallel streams suit large volumes without side effects, with collectors.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.