Reputation: 2040
I am trying to wait for a list of CompletionStage
. What's the difference between the two approaches:
1. CompletableFuture.allOf(test.toArray(new CompletableFuture[0])).join();
2. CompletableFuture.allOf(test.stream().map(CompletionStage::toCompletableFuture)
.toArray(CompletableFuture[]::new)).join();
IntelliJ shows warning for the 1st that says expected type is CompletableFuture[]
and not CompletionStage[]
.
I wrote a small test and seems both behave the same. Is there a one preferred or "correct" way over the other?
Thanks. (Mainly looking to see if I am making a fundamental error or if one of the style is more correct way).
Upvotes: 1
Views: 643
Reputation: 276
The second one is the safest IMO. As you say both work correctly, but CompletionStage
is the super interface of CompletableFuture
(in other words CompletableFuture is an implementation if CompletionStage), so doing a toArray
as in the first method could theoretically cause a runtime exception if the actual type of the elements was not CompletableFuture
.
On the other hand, the second approach leverages the API method toCompletableFuture()
designed explicitly to interoperate from any CompletionStage
implementation class to CompletableFuture
.
Upvotes: 1