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 ?
Asked
Active
Viewed 542 times
1
-
2Why not use [`Future`s](https://www.baeldung.com/java-future) instead? – Turing85 Dec 25 '19 at 12:43
-
Can you please share the code you have tried. Not able to understand the requirement. – dassum Dec 25 '19 at 14:59
2 Answers
1
Thank you for your responses. I came across the answer, and it helped. Sharing a link for reference. Flexible CountDownLatch?

kcd
- 43
- 4
0
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:
- Future: https://www.baeldung.com/java-future
- CompletableFuture: https://www.baeldung.com/java-completablefuture
- CompletableFuture: https://www.callicoder.com/java-8-completablefuture-tutorial/
- Waiting on a list of Future

ArpanKhandelwal
- 137
- 1
- 5