What happens to the "SupplyAsync" portion of CompletableFuture when same one is called twice

Viewed 115

I have the following CompletableFuture with supplyAync that uses a client to call an external http endpoint.

CompletableFuture<T> future = CompletableFuture.supplyAsync(() ->  {

   **call to external client**
})

If I were to do future.get twice with different timeouts for both calls, would that mean the external client is being called twice as well? I am not sure what the behavior that is in the future is at this point.

Thanks

1 Answers

The documentation is sort of telling you already:

Waits if necessary for this future to complete, and then returns its result

which implies that if the future is already completed, you will get its result without waiting, since it is already known. "known" here means that your call was already executed and the result is already "saved", thus no need to execute it twice.

You can sneak pick into the implementation too and see that your call to external client is a Runnable under the hood (besides other things). CompletableFuture::supplyAsync will schedule that Runnable and your two threads will pool for the result (this is a very simplified explanation).

Related