9

My situation is quite simple.

I have a list I want to perform logic on each item asynchronically.

when all the threads are done, i want to call a close connection.

like so:

bucketsList.parallelStream().forEach(t -> {
//some logic
});
 try {
 RestApi.getInstance().closeClientConnection();
 } catch (IOException e) {
     e.printStackTrace();
 }

is there a way to make the closeConnection part wait for the parallel Stream to finish going through all of its objects?

EDIT: I cannot use CountDownLatch as i dont know how many items i will have in bucketsList

0

1 Answer 1

14

An operation on a ParallelStream is still blocking and will wait for all the threads it spawned to finish. These threads are executed asynchronously (they don't wait for a previous one to finish), but that doesn't mean your whole code starts behaving asynchronously !

If you're actually making asynchronous calls and working on the resulting CompletableFuture<T> in your forEach, you should instead make your terminal operation a reduce producing a single CompletableFuture<T>. Intermediate operations could be a peek or an identity map with side-effects (both are frowned upon, but I don't know any best-practice solution). You would close the connection upon resolve of the single resulting CompletableFuture<T>.

If you're not, then your code looks good enough, as the closeClientConnection() will only be executed once the ParallelStream has been processed.

Sign up to request clarification or add additional context in comments.

1 Comment

You are indeed correct! it appears that i had a different problem that reset my counter ( the logic i did was also async and i manage it manually to know how many requests are still running). once i fixed the reset counter issue this code worked!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.