Advertisement
Guest User

CompletableFuture.thenComposeAsync example

a guest
Dec 18th, 2014
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.19 KB | None | 0 0
  1. import java.util.concurrent.CompletableFuture;
  2. import java.util.concurrent.Executor;
  3. import java.util.concurrent.Executors;
  4.  
  5. public class Test {
  6.  
  7.     public static void main(String argv[]) throws Exception {
  8.  
  9.         int nThreads = 1;
  10.         Executor executor = Executors.newFixedThreadPool( nThreads );
  11.  
  12.         CompletableFuture.completedFuture(true)
  13.             .thenComposeAsync((unused)->{
  14.  
  15.                 System.err.println("About to enqueue task");
  16.                 CompletableFuture<Boolean> innerFuture = new CompletableFuture<>();
  17.                 executor.execute(() -> {
  18.  
  19.                     // pretend this is some really expensive computation done asynchronously
  20.  
  21.                     System.err.println("Inner task");
  22.                     innerFuture.complete(true);
  23.                 });
  24.                 System.err.println("Task enqueued");
  25.  
  26.                 return innerFuture;
  27.             }, executor).get();
  28.  
  29.         // This is never reached.  The inner runnable (with pretend... in its comment) is
  30.         // starved because the single threaded executor is blocking in the call to thenComposeAsync
  31.         System.err.println("All done");
  32.         System.exit(0);
  33.     }
  34.  
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement