简体   繁体   中英

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

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM