java 8并行流,blockingcode可能吗? [英] java 8 parallel stream, blockingcode possible?

查看:99
本文介绍了java 8并行流,blockingcode可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况很简单.

我有一个列表,我想异步地对每个项目执行逻辑.

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.

像这样:

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

是否有一种方法可以使closeConnection部分等待并行Stream完成其所有对象的访问?

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

我无法使用CountDownLatch,因为我不知道bucketsList中将有多少个物品

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

推荐答案

ParallelStream的操作仍在阻塞,将等待它产生的所有线程完成.这些线程是异步执行的(它们不等待上一个线程完成),但这并不意味着您的整个代码便开始异步运行!

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 !

如果您实际上是在进行异步调用并在forEach中处理生成的CompletableFuture<T>,则应将终端操作设置为reduce并生成单个CompletableFuture<T>.中间操作可能是带有副作用的peek或标识map(两者都不满意,但我不知道任何最佳实践解决方案).解析单个结果CompletableFuture<T>后,您将关闭连接.

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>.

如果不是,那么您的代码看起来就足够好了,因为closeClientConnection()仅在处理ParallelStream之后才会执行.

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

这篇关于java 8并行流,blockingcode可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆