Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 CompletableFuture - how to run multiple functions on same input

I've the following working piece of code using CompleteableFuture:

CompletableFuture<SomeObject> future = CompletableFuture.
            supplyAsync( () -> f1() ).
            thenApplyAsync( f1Output -> f2( f1Output ) ).
            thenApplyAsync( f2Output -> f3( f2Output ) );

Is it possible to run another future that receives f1Output as an input? Something like:

CompletableFuture<SomeObject> future = CompletableFuture.
            supplyAsync( () -> f1() ).
            thenApplyAsync( f1Output -> f2( f1Output ) ).
            someApiThatRuns( f1Output -> f4( f1Output ) ). // <-- 
            thenApplyAsync( f2Output -> f3( f2Output ) );

If this simplifies things one can ignore the result returned by f4().

like image 626
Seffy Avatar asked Sep 01 '25 23:09

Seffy


1 Answers

If you don't mind running f2 and f4 in sequence, the simplest is just to call both in your lambda:

CompletableFuture<SomeObject> future = CompletableFuture.
            supplyAsync(() -> f1() ).
            thenApplyAsync(f1Output -> { f4(f1Output); return f2(f1Output); } ).
            thenApplyAsync(f2Output -> f3(f2Output));

If however you want to run f2 and f4 in parallel, you can just store the intermediate future in a variable:

CompletableFuture<SomeObject> f1Future = CompletableFuture.supplyAsync(() -> f1());

CompletableFuture<SomeObject> future = f1Future.
            thenApplyAsync(f1Output -> f2(f1Output)).
            thenApplyAsync(f2Output -> f3(f2Output));

f1Future.thenAcceptAsync(f1Output -> f4(f1Output));
like image 64
Didier L Avatar answered Sep 03 '25 13:09

Didier L