java 8 parallel stream, blockingcode possible?

前端 未结 1 349
囚心锁ツ
囚心锁ツ 2021-01-14 10:33

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 conne

相关标签:
1条回答
  • 2021-01-14 11:07

    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.

    0 讨论(0)
提交回复
热议问题