×

java · level 3 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a future you can keep building on.

With a plain Future, you must call get and wait before doing anything with the answer. A CompletableFuture lets you say what happens next, before the answer even exists. That is code: start now, finish later, block nobody.

starts the job on a background thread and returns at once. adds a step that runs on the answer when it arrives. Chain as many steps as you like.

At the very end, join() waits for the final answer. Use runAsync for jobs with no answer at all, like sending an email.

import java.util.concurrent.CompletableFuture;
public class Main {
    static String fetchBasket() {
        return "apples:3,bread:1,milk:2";
    }
    static int countItems(String basket) {
        int total = 0;
        for (String entry : basket.split(",")) {
            total = total + Integer.parseInt(entry.split(":")[1]);
        }
        return total;
    }
    public static void main(String[] args) {
        CompletableFuture<String> message = CompletableFuture
            .supplyAsync(() -> fetchBasket())
            .thenApply(basket -> countItems(basket))
            .thenApply(count -> "Your basket has " + count + " items");
        System.out.println("Working on it...");
        System.out.println(message.join());
    }
}

join is like get, but it throws no checked exceptions, so main needs no throws.