我应该尽可能使用并行流吗? [英] Should I always use a parallel stream when possible?

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

问题描述

使用Java 8和lambdas,可以很容易地将集合作为流进行迭代,同样易于使用并行流。 文档中的两个示例,第二个使用parallelStream:

With Java 8 and lambdas it's easy to iterate over collections as streams, and just as easy to use a parallel stream. Two examples from the docs, the second one using parallelStream:

myShapesCollection.stream()
    .filter(e -> e.getColor() == Color.RED)
    .forEach(e -> System.out.println(e.getName()));

myShapesCollection.parallelStream() // <-- This one uses parallel
    .filter(e -> e.getColor() == Color.RED)
    .forEach(e -> System.out.println(e.getName()));

只要我不关心订单,使用并行总是有益的?人们会认为将更多核心的工作划分得更快。

As long as I don't care about the order, would it always be beneficial to use the parallel? One would think it is faster dividing the work on more cores.

还有其他考虑因素吗?什么时候应该使用并行流?什么时候应该使用非并行?

Are there other considerations? When should parallel stream be used and when should the non-parallel be used?

(这个问题被要求引发关于如何以及何时使用并行的讨论流,不是因为我认为总是使用它们是个好主意。)

推荐答案

并行流有很多与顺序相比,开销更高。协调线程需要花费大量时间。我会默认使用顺序流,只考虑并行流,如果

A parallel stream has a much higher overhead compared to a sequential one. Coordinating the threads takes a significant amount of time. I would use sequential streams by default and only consider parallel ones if


  • 我有大量要处理的项目(或者处理每个项目需要时间并且可以并行化。)

  • I have a massive amount of items to process (or the processing of each item takes time and is parallelizable)

我首先遇到性能问题

我还没有在多线程环境中运行该进程(例如:在Web容器中,如果我已经有很多请求并行处理,在每个请求中添加额外的并行层可能会有比正面效果更负面)

I don't already run the process in a multi-thread environment (for example: in a web container, if I already have many requests to process in parallel, adding an additional layer of parallelism inside each request could have more negative than positive effects)

在你的例子中,性能无论如何都会被同步访问<$驱动c $ c> System.out.println(),并且使这个过程并行将不起作用,甚至是否定的。

In your example, the performance will anyway be driven by the synchronized access to System.out.println(), and making this process parallel will have no effect, or even a negative one.

此外,请记住,并行流不会神奇地解决所有同步问题。如果进程中使用的谓词和函数使用共享资源,则必须确保所有内容都是线程安全的。特别是,如果你并行,副作用就是你真正需要担心的事情。

Moreover, remember that parallel streams don't magically solve all the synchronization problems. If a shared resource is used by the predicates and functions used in the process, you'll have to make sure that everything is thread-safe. In particular, side effects are things you really have to worry about if you go parallel.

无论如何,测量,不要猜!只有衡量标准才能告诉您并行性是否值得。

In any case, measure, don't guess! Only a measurement will tell you if the parallelism is worth it or not.

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

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