Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package example;
- import java.util.concurrent.CompletableFuture;
- import java.util.concurrent.ExecutionException;
- import org.junit.Test;
- public class CompletableFutures {
- @Test
- public void chainFuturesInner() throws ExecutionException, InterruptedException {
- System.out.println("Executing chainFuturesInner()");
- final Integer result = future(1)
- .thenCompose(ignored1 -> future(2)
- .thenCompose(ignored2 -> future(3)))
- .get();
- System.out.println("The result is " + result);
- System.out.println();
- }
- @Test
- public void chainFuturesOuter() throws ExecutionException, InterruptedException {
- System.out.println("Executing chainFuturesOuter()");
- final Integer result = future(1)
- .thenCompose(ignored1 -> future(2))
- .thenCompose(ignored2 -> future(3))
- .get();
- System.out.println("The result is " + result);
- System.out.println();
- }
- public static CompletableFuture<Integer> future(int id) {
- return CompletableFuture.supplyAsync(() -> {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- System.out.println("Future " + id + " executed");
- return id;
- });
- }
- }
Add Comment
Please, Sign In to add comment