Guest User

Untitled

a guest
May 25th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. package example;
  2.  
  3. import java.util.concurrent.CompletableFuture;
  4. import java.util.concurrent.ExecutionException;
  5. import org.junit.Test;
  6.  
  7. public class CompletableFutures {
  8. @Test
  9. public void chainFuturesInner() throws ExecutionException, InterruptedException {
  10. System.out.println("Executing chainFuturesInner()");
  11. final Integer result = future(1)
  12. .thenCompose(ignored1 -> future(2)
  13. .thenCompose(ignored2 -> future(3)))
  14. .get();
  15.  
  16. System.out.println("The result is " + result);
  17. System.out.println();
  18. }
  19.  
  20. @Test
  21. public void chainFuturesOuter() throws ExecutionException, InterruptedException {
  22. System.out.println("Executing chainFuturesOuter()");
  23. final Integer result = future(1)
  24. .thenCompose(ignored1 -> future(2))
  25. .thenCompose(ignored2 -> future(3))
  26. .get();
  27.  
  28. System.out.println("The result is " + result);
  29. System.out.println();
  30. }
  31.  
  32. public static CompletableFuture<Integer> future(int id) {
  33. return CompletableFuture.supplyAsync(() -> {
  34. try {
  35. Thread.sleep(500);
  36.  
  37. } catch (InterruptedException e) {
  38. throw new RuntimeException(e);
  39. }
  40.  
  41. System.out.println("Future " + id + " executed");
  42.  
  43. return id;
  44. });
  45. }
  46. }
Add Comment
Please, Sign In to add comment