September 2019
Intermediate to advanced
816 pages
18h 47m
English
Let's assume that we want to organize a raffle for our customers:
List<String> customers = Arrays.asList( "#1", "#4", "#2", "#7", "#6", "#5");
We can start to solve this problem by defining the following trivial method:
public static CompletableFuture<String> raffle(String customerId) { return CompletableFuture.supplyAsync(() -> { Thread.sleep(new Random().nextInt(5000)); return customerId; });}
Now, we can create an array of CompletableFuture<String> instances, as follows:
CompletableFuture<String>[] cfCustomers = customers.stream() .map(CustomerAsyncs::raffle) .toArray(CompletableFuture[]::new);
To find the winner of the raffle, we want to run cfCustomers in parallel, and the first CompletableFuture that completes ...