java · level 3 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Does thenApply change the old future? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> 20);
CompletableFuture<Integer> withTip = price.thenApply(p -> p + 3);
CompletableFuture<String> label = withTip.thenApply(p -> "Total: " + p);
System.out.println(price.join() + " | " + label.join());
}
}
your turn
Your turn. Finish the weather report.
On line 10, add a step that turns the temperature into a sentence, like It is 18.5C today.
output
press run to see what happens
fix it
The inbox counter will not compile. Can you fix it?
output
press run to see what happens
- Java says a
CompletableFuture<Void>cannot become aCompletableFuture<Integer>. Which method made it? runAsyncis for jobs with no answer, so its future holds nothing:Void.- Change
runAsynctosupplyAsyncon line 7, then run.
nailed it
your code can plan ahead without waiting. :D
supplyAsyncstarts a job and returns a future at once.thenApplyadds a step that runs when the answer arrives.joinwaits for the final answer at the end.
new words in your collection
- asynchronous
- CompletableFuture
- supplyAsync
- thenApply
This lesson isn’t saved. A free account remembers every lesson you finish.