Reputation: 43
I have to start unknown number of threads then wait or all threads to finish their job. I am using executor service. I tried using countdownlatch - so that I may wait till countdown is zero. But there is no way I can get number of threads I have started. Can someone give me any idea how may I achieve this ?
Upvotes: 1
Views: 799
Reputation: 43
Thank you for your responses. I came across the answer, and it helped. Sharing a link for reference. Flexible CountDownLatch?
Upvotes: 1
Reputation: 157
In case that you want combine a List of CompletableFutures
, you can do this :
// Waits for *all* futures to complete and returns a list of results.
// If *any* future completes exceptionally then the resulting future will also complete exceptionally.
public static <T> CompletableFuture<List<T>> all(List<CompletableFuture<T>> futures) {
CompletableFuture[] cfs = futures.toArray(new CompletableFuture[futures.size()]);
return CompletableFuture.allOf(cfs)
.thenApply(ignored -> futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList())
);
}
For more details on Future & CompletableFuture, useful links:
Upvotes: 0