The Itinera bookJava edition

Part 4: Running it for real, Chapter 26

Running async journeys while others wait

What you want to do

The shop's bank and carriers answer over the network, and while one order waits for them, the program's thread waits too. You want the shop to take other orders forward in the meantime.

The code

Itinera has two execution modes, synchronous and asynchronous, and Java writes workflows in the synchronous one only: every step, hook, provider and reporter is an ordinary method, and a journey runs on the thread that calls run. So the shop runs journeys side by side the way Java runs any work side by side: each on a thread of its own.

The shop is chapter 25's, unchanged but for what answers over the network. The faked bank and carriers now call Network.roundTrip() before each answer, which waits a moment, as a real call does while the other side answers, and holds its thread meanwhile. The order book answers from the shop's own records, without the network, so it stays as chapter 22 shows it:

Java, from the program ch26_running_async_journeys_while_others_wait
/** The network the fakes answer over. */
final class Network {
  private Network() {}

  /** Waits for the other side to answer, as a real call does, holding its thread meanwhile. */
  static void roundTrip() {
    try {
      Thread.sleep(10);
    } catch (InterruptedException interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}

/**
 * The shop's bank, faked: a card is its holder's name and the year it expires, and the bank
 * declines a card that expired before this year. Its network fails on any amount over 100. It
 * prints what it does.
 */
final class Bank implements Payments {
  private final int thisYear;

  Bank(int thisYear) {
    this.thisYear = thisYear;
  }

  @Override
  public Optional<String> charge(String order, String card, long amount) throws NetworkDown {
    Network.roundTrip();
    if (amount > 100) {
      System.out.println("the bank's network fails while charging order " + order);
      throw new NetworkDown();
    }
    if (expiry(card) < thisYear) {
      System.out.println("the bank declines card " + card + ": it has expired");
      return Optional.empty();
    }
    System.out.println("the bank charges " + amount + " for order " + order);
    return Optional.of("R-" + order);
  }

  /**
   * A card that expired in the last three years was replaced by its holder's card that expires in
   * three years. An older one was not.
   */
  @Override
  public Optional<String> replacement(String card) {
    Network.roundTrip();
    if (expiry(card) + 3 < thisYear) {
      System.out.println("the bank says nothing replaced card " + card);
      return Optional.empty();
    }
    String replacement = card.substring(0, card.lastIndexOf('-')) + "-" + (thisYear + 3);
    System.out.println("the bank says card " + card + " was replaced by " + replacement);
    return Optional.of(replacement);
  }

  /** The year a card expires: the part of it after its last {@code -}. */
  private static int expiry(String card) {
    return Integer.parseInt(card.substring(card.lastIndexOf('-') + 1));
  }
}

The workflow class calls it too, in the methods of its roles, since telling a customer and giving money back go over the network as well:

Java, from the program ch26_running_async_journeys_while_others_wait
@Override
public void tell(String customer, String message) {
  Network.roundTrip();
  System.out.println(channel + " to " + customer + ": " + message);
}

@Override
public void refund(String receipt, long amount) {
  Network.roundTrip();
  System.out.println("the bank gives " + amount + " back on receipt " + receipt);
}

Journeys that run at the same time print at the same time, and their lines would mix in another order on every run. So the program gives its journeys a console of its own, which keeps what each thread prints apart until that thread takes it:

Java, from the program ch26_running_async_journeys_while_others_wait
/**
 * The program's console, as its journeys print to it: it keeps what each thread prints apart from
 * what the others print, until that thread takes it.
 */
final class Console extends OutputStream {
  private final ThreadLocal<ByteArrayOutputStream> kept =
      ThreadLocal.withInitial(ByteArrayOutputStream::new);

  @Override
  public void write(int b) {
    kept.get().write(b);
  }

  @Override
  public void write(byte[] bytes, int offset, int length) {
    kept.get().write(bytes, offset, length);
  }

  /** What this thread has printed, which the console no longer keeps. */
  String take() {
    String printed = kept.get().toString(StandardCharsets.UTF_8);
    kept.remove();
    return printed;
  }
}

main runs three of the day's orders, Ann's, Gil's and Jo's, at the same time. It makes a pool of three threads with Executors.newFixedThreadPool, and starts each order's journey on it with CompletableFuture.supplyAsync, both from java.util.concurrent. journey makes each one's instance as chapter 25's main did, runs it with a LocalExecutor of its own, and gives back what the journey printed, with its result. Once every journey has ended, main prints each journey's lines together, in the order of the orders, so the output is the same on every run. NewOrder is chapter 25's, and Parcel chapter 21's:

Java, from the program ch26_running_async_journeys_while_others_wait
/** A journey that has ended: what it printed, and its result. */
record Ran(String printed, JourneyResult result) {}

final class Main {
  private Main() {}

  /** Runs an order's journey with an executor of its own, and keeps what it printed. */
  static Ran journey(NewOrder order, Console console) {
    var instance = new Orders("email").instance().initialData(order).create();
    try {
      var result = new LocalExecutor().run(instance);
      return new Ran(console.take(), result);
    } catch (Refusal refusal) {
      throw new CompletionException(refusal);
    }
  }

  public static void main(String[] args) {
    // Each order: its number, its customer, its price, its discount if it has one, its parcel, as
    // its weight in kg and its size in cm, and the card.
    var orders =
        List.of(
            new NewOrder(
                "A-1",
                "Ann",
                40,
                Optional.of(10L),
                new Parcel(2, List.of(30L, 20L, 10L)),
                Optional.of("ann-2028"),
                false),
            new NewOrder("A-7", "Gil", 45, new Parcel(60, List.of(120L, 80L, 60L)), "gil-2027"),
            new NewOrder("A-8", "Jo", 30, new Parcel(1, List.of(20L, 15L, 5L)), "jo-2024"));
    var screen = System.out;
    var console = new Console();
    System.setOut(new PrintStream(console, true, StandardCharsets.UTF_8));
    var pool = Executors.newFixedThreadPool(orders.size());
    try {
      var running =
          orders.stream()
              .map(order -> CompletableFuture.supplyAsync(() -> journey(order, console), pool))
              .toList();
      var ran = running.stream().map(CompletableFuture::join).toList();
      for (var journey : ran) screen.print(journey.printed());
      for (var journey : ran) {
        var result = journey.result();
        var ended = result.isSucceeded() ? "succeeded" : "failed";
        screen.println("order " + result.journeyId() + " " + ended);
      }
    } finally {
      pool.shutdown();
      System.setOut(screen);
    }
  }
}

It prints:

What ch26_running_async_journeys_while_others_wait prints, recorded in ch26_running_async_journeys_while_others_wait.txt
log orders A-1 #1 journey_started order, customer, price, discount, parcel, card, giftCard
log orders A-1 #2 attempt_started lookup, attempt 1
log orders A-1 #3 service_provided lookup gets orderBook from ledger, a ch26_running_async_journeys_while_others_wait.Ledger
the order book has no order A-1 yet
log orders A-1 #4 step_succeeded lookup
log orders A-1 #5 contribution_committed completed
log orders A-1 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-1 #7 attempt_started price, attempt 1
log orders A-1 #8 step_succeeded price
log orders A-1 #9 contribution_committed amount
log orders A-1 #10 attempt_started charge, attempt 1
log orders A-1 #11 service_provided charge gets payments from bank, a ch26_running_async_journeys_while_others_wait.Bank
the bank charges 30 for order A-1
log orders A-1 #12 step_succeeded charge
log orders A-1 #13 contribution_committed receipt
log orders A-1 #14 hook_called audit: on step success of charge
log orders A-1 #15 contribution_committed audit
log orders A-1 #16 attempt_started ship, attempt 1
log orders A-1 #17 input_adapter_supplied ship gets weight from parcels
log orders A-1 #18 service_provided ship gets carrier from carriers, a ch26_running_async_journeys_while_others_wait.MainCarrier
the main carrier books order A-1
log orders A-1 #19 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 #20 step_succeeded ship
log orders A-1 #21 contribution_committed tracking
log orders A-1 #22 optional_input_absent code
email to Ann: Order A-1 is on its way, tracking T-A-1.
log orders A-1 #23 hook_called notify: on workflow success
log orders A-1 #24 journey_succeeded
log orders A-7 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-7 #2 attempt_started lookup, attempt 1
log orders A-7 #3 service_provided lookup gets orderBook from ledger, a ch26_running_async_journeys_while_others_wait.Ledger
the order book has no order A-7 yet
log orders A-7 #4 step_succeeded lookup
log orders A-7 #5 contribution_committed completed
log orders A-7 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-7 #7 attempt_started price, attempt 1
log orders A-7 #8 optional_input_absent discount
log orders A-7 #9 step_succeeded price
log orders A-7 #10 contribution_committed amount
log orders A-7 #11 attempt_started charge, attempt 1
log orders A-7 #12 service_provided charge gets payments from bank, a ch26_running_async_journeys_while_others_wait.Bank
the bank charges 45 for order A-7
log orders A-7 #13 step_succeeded charge
log orders A-7 #14 contribution_committed receipt
log orders A-7 #15 hook_called audit: on step success of charge
log orders A-7 #16 contribution_committed audit
log orders A-7 #17 attempt_started ship, attempt 1
log orders A-7 #18 input_adapter_supplied ship gets weight from parcels
log orders A-7 #19 service_provided ship gets carrier from carriers, a ch26_running_async_journeys_while_others_wait.MainCarrier
the main carrier books order A-7
log orders A-7 #20 step_failed ship: too-heavy
log orders A-7 #21 hook_called failedShipping: on step retry of ship
log orders A-7 #22 step_retrying ship
log orders A-7 #23 attempt_started ship, attempt 2
log orders A-7 #24 input_adapter_supplied ship gets weight from parcels
log orders A-7 #25 service_provided ship gets carrier from carriers, a ch26_running_async_journeys_while_others_wait.BackupCarrier
the backup carrier books order A-7
log orders A-7 #26 step_info ship: the parcel leaves with receipt R-A-7
log orders A-7 #27 step_succeeded ship
log orders A-7 #28 contribution_committed tracking
log orders A-7 #29 optional_input_absent code
email to Gil: Order A-7 is on its way, tracking B-A-7.
log orders A-7 #30 hook_called notify: on workflow success
log orders A-7 #31 journey_succeeded
log orders A-8 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-8 #2 attempt_started lookup, attempt 1
log orders A-8 #3 service_provided lookup gets orderBook from ledger, a ch26_running_async_journeys_while_others_wait.Ledger
the order book has no order A-8 yet
log orders A-8 #4 step_succeeded lookup
log orders A-8 #5 contribution_committed completed
log orders A-8 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-8 #7 attempt_started price, attempt 1
log orders A-8 #8 optional_input_absent discount
log orders A-8 #9 step_succeeded price
log orders A-8 #10 contribution_committed amount
log orders A-8 #11 attempt_started charge, attempt 1
log orders A-8 #12 service_provided charge gets payments from bank, a ch26_running_async_journeys_while_others_wait.Bank
the bank declines card jo-2024: it has expired
log orders A-8 #13 step_failed charge: card-expired
log orders A-8 #14 step_rescuing charge: failure, rescued by charge_rescue
log orders A-8 #15 attempt_started charge_rescue, attempt 1
the bank says card jo-2024 was replaced by jo-2029
log orders A-8 #16 step_succeeded charge_rescue
log orders A-8 #17 contribution_committed card
log orders A-8 #18 data_overwritten card
log orders A-8 #19 step_rescued charge by charge_rescue
log orders A-8 #20 attempt_started charge, attempt 2
the bank charges 30 for order A-8
log orders A-8 #21 step_succeeded charge
log orders A-8 #22 contribution_committed receipt
log orders A-8 #23 hook_called audit: on step success of charge
log orders A-8 #24 contribution_committed audit
log orders A-8 #25 attempt_started ship, attempt 1
log orders A-8 #26 input_adapter_supplied ship gets weight from parcels
log orders A-8 #27 service_provided ship gets carrier from carriers, a ch26_running_async_journeys_while_others_wait.MainCarrier
the main carrier books order A-8
log orders A-8 #28 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 #29 step_succeeded ship
log orders A-8 #30 contribution_committed tracking
log orders A-8 #31 optional_input_absent code
email to Jo: Order A-8 is on its way, tracking T-A-8.
log orders A-8 #32 hook_called notify: on workflow success
log orders A-8 #33 journey_succeeded
order A-1 succeeded
order A-7 succeeded
order A-8 succeeded

How it works

  1. A Java workflow is in the synchronous execution mode, and so is every part of it. The asynchronous mode, where a part waits for an answer without holding its thread, belongs to languages whose code can suspend, such as Kotlin with its coroutines. Java's part waits by holding its thread, so a program that wants many journeys at once gives each one a thread.
  2. LocalExecutor runs a journey on the thread that calls its run, here a thread of the pool. The journeys end as they did in chapter 25: Gil's parcel goes with the backup carrier, and Jo's card is renewed.
  3. A journey that waits lets the others go on. While Ann's charge waits for the bank, her thread waits with it, and Gil's and Jo's journeys go on, on their own threads. The three journeys run at the same time, and each one's events are still numbered from #1: every journey counts its own, and every line names its journey.
  4. The executor chooses no thread. It never starts one: the journey runs wherever run is called. The pool here has a thread for each order; a shop with many orders makes a pool of the size it can afford, and supplyAsync queues the rest until a thread is free.
  5. An executor runs one journey at a time, as chapter 24 showed, so each journey that runs at the same time as others gets an executor of its own.
  6. A refusal still ends the program. A Refusal is checked, and the work supplyAsync runs can't throw a checked exception, so journey wraps it in a CompletionException, which join() throws in main, as the refusal itself did in chapter 24.

Ann's, Gil's and Jo's journeys now go on together, each while the others wait. But the only way to know that the shop still gives the same answers after a change is to run every order again, against the bank and the carriers, and read the log.

Outcomes

We have shown how the shop runs journeys at the same time, each on a thread of its own while others wait.

The usual way With Itinera
Running requests side by side often means sharing one client or one handler between threads, and guarding everything it keeps. Each journey runs on its own thread with an executor of its own, and its steps and policies are built for it, so nothing in one journey is shared with another.