Core Java · Chapter 39 of 48

Executors and futures

By the end of this chapter you can hand jobs to a pool of threads, get their results back, shut the pool down, and chain what happens next with CompletableFuture. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Beyond the basics
  • 5 tasks
  • Java
  • In the all labs plan

The first 2 chapters of Core Java are free. This one comes with the all labs plan.

Why you need this

The morning report asks every station for its stock: SBC, NDLS, CSMT, and soon thirty more. Ravi wants the answers, not threads, and he wants a slow or broken station to give a fallback instead of stopping the report.

With what you know, each station gets a new Thread. That is thirty threads for thirty stations and thousands for the whole country, and a Thread cannot hand back a result: its run() returns void. You would need a shared map, a join for every thread, and some way to notice that one of them threw.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    StationJobs.java: run every station's job on a pool of two threads

    In StationJobs.java, make runAll(jobs) run every job on a fixed pool of 2 threads that the method makes itself, so that two jobs run at the same time and none runs on the calling thread. Return the jobs' results in the order of the jobs, and shut the pool down before returning, so its threads have stopped.

    For example, jobs giving SBC: 120, NDLS: 80 and CSMT: 95, where the first two each wait until the other has started, return [SBC: 120, NDLS: 80, CSMT: 95].

  2. Task 2

    StationJobs.java: a job's result, or a fallback when it failed

    In StationJobs.java, make fetchOrFallback(pool, job, fallback) give the job to the pool it is given, wait for the result and return it. When the job threw an exception, return the fallback instead. Leave the pool running: the caller owns it and shuts it down.

    For example, a job returning 120 gives 120; a job that throws IllegalStateException("the SBC till is offline"), with the fallback unknown, gives unknown.

  3. Task 3

    StationJobs.java: look up a price in the background, as a label

    In StationJobs.java, make priceLabel(item, price, executor) run the price lookup on the given executor (never on the calling thread) and return at once a CompletableFuture that completes with the label: the item, a colon, a space, the rupee sign and the price.

    For example, Masala chai with a lookup giving 40 completes with Masala chai: ₹40, and Bun maska with 50 completes with Bun maska: ₹50.

  4. Task 4

    StationJobs.java: one bill total from two amounts

    In StationJobs.java, make billTotal(chai, snacks) return a CompletableFuture of the sum of the two amounts that completes only once both have completed. When either amount fails, the total fails too, with that same exception as the cause.

    For example, chai completing with 80 and snacks with 50 gives 130, and the total is not done while only chai has completed. With 40 and an amount that fails with IllegalStateException, the total fails with that IllegalStateException as its cause.

  5. Task 5

    StationJobs.java: fall back to cash when the UPI check fails

    In StationJobs.java, make upiStatus(gateway, executor) ask the gateway for its status on the given executor (never on the calling thread) and return a CompletableFuture of the status. When the gateway throws, the future completes normally with UPI down, take cash instead of failing.

    For example, a gateway returning UPI ok gives UPI ok; a gateway that throws IllegalStateException("bank timeout") gives UPI down, take cash.

What you will learn

  • ExecutorService: a pool of threads with a queue; you give it jobs.
  • Callable and Future: a job that returns a value, and a receipt you redeem later for that value, or for its exception.
  • Shutting down: a pool's threads keep a program alive until it is closed.
  • CompletableFuture: say what happens with a result when it arrives, instead of waiting for it.

More in Beyond the basics

Build "Executors and futures" yourself

Tapri runs chai counters at railway stations, and every counter runs a Java program you write. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Core Java are free. This one comes with the all labs plan.