kcd
kcd

Reputation: 43

How to set countdownlatch for unknown number of threads

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

Answers (2)

kcd
kcd

Reputation: 43

Thank you for your responses. I came across the answer, and it helped. Sharing a link for reference. Flexible CountDownLatch?

Upvotes: 1

ArpanKhandelwal
ArpanKhandelwal

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:

  1. Future: https://www.baeldung.com/java-future
  2. CompletableFuture: https://www.baeldung.com/java-completablefuture
  3. CompletableFuture: https://www.callicoder.com/java-8-completablefuture-tutorial/
  4. Waiting on a list of Future

Upvotes: 0

Related Questions