Cork Kochi
Cork Kochi

Reputation: 1891

CompletableFuture dependent chain to run asynchronously

How can I execute this full CompletableFuture chain to run asynchronously using a separate executor

  .thenApply(r -> {
            return validateStudents();
            })
  .thenCompose(r -> {
          return fetchAll(r);
            })
  .thenCompose(r -> {
          return processAll(r);
            })      
  .whenComplete((r, t) -> {

            });
    });

Upvotes: 0

Views: 1278

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 39978

You can use the Async methods from CompletableFuture with the default ForkJoinPool

All async methods without an explicit Executor argument are performed using the ForkJoinPool.commonPool() (unless it does not support a parallelism level of at least two, in which case, a new Thread is created to run each task)

System.out.println(Thread.currentThread().getName());
CompletableFuture.supplyAsync(()->{
    System.out.println(Thread.currentThread().getName());
    return "supplyAsync";
}).thenApplyAsync(supply->{
    System.out.println(Thread.currentThread().getName()+"----"+supply);
    return "applyAsync";
}).thenComposeAsync(compose->{
    System.out.println(Thread.currentThread().getName()+"----"+compose);
    return CompletableFuture.completedStage("composeAsync");

});

Output :

main
ForkJoinPool.commonPool-worker-3
ForkJoinPool.commonPool-worker-3----supplyAsync
ForkJoinPool.commonPool-worker-3----applyAsync

You can also define custom thread pool and you can use that thread pool

ExecutorService pool = Executors.newFixedThreadPool(1);

    System.out.println(Thread.currentThread().getName());
CompletableFuture.supplyAsync(()->{
    System.out.println(Thread.currentThread().getName());
    return "supplyAsync";
},pool).thenApplyAsync(supply->{
    System.out.println(Thread.currentThread().getName()+"----"+supply);
    return "applyAsync";
},pool).thenComposeAsync(compose->{
    System.out.println(Thread.currentThread().getName()+"----"+compose);
    return CompletableFuture.completedStage("composeAsync");

},pool);

Output :

main
pool-1-thread-1
pool-1-thread-1----supplyAsync
pool-1-thread-1----applyAsync

Upvotes: 1

Related Questions