简体   繁体   English

Java中并行stream的实用用例是什么?

[英]What are pragmatic use cases of parallel stream in Java?

Beginning from Java-8, we can use parallel stream (java.util.stream package)从Java-8开始,我们可以并行使用stream(java.util.stream包)

As per theory, it is well-known that the Java's parallel stream is suited when operation needs to be executed in parallel, in contrast to (sequential) stream of Java.根据理论,众所周知,Java 的并行 stream 适用于需要并行执行操作的情况,而 ZD52387880E1EA22817A72D375921 的(顺序)stream 则相反。

Moreover, Parallel stream has bit overhead in managing parallelism and abundance caution is required.此外,并行 stream 在管理并行性方面有一些开销,需要非常小心。

What are practical use cases where it can be used?可以使用哪些实际用例? Also, how it'd outwit cost of parallelism in such practical use cases?此外,在这种实际用例中,它如何胜过并行性成本?

When you need to fetch a lot of independent data, parallel stream is good.当您需要获取大量独立数据时,并行 stream 很好。 For example, you have a large database application, where multiple applications are fetching there stored data from independent tables or maybe separate databases, parallel stream will be really good.例如,您有一个大型数据库应用程序,其中多个应用程序从独立的表或单独的数据库中获取存储的数据,并行 stream 将非常好。 Also, in web environment, request from a user is independent from other users.此外,在 web 环境中,来自用户的请求独立于其他用户。 In that case, parallel stream is also good.在这种情况下,并行 stream 也不错。

Parallel streams runs operations over stream in parallel mode.并行流以并行模式在 stream 上运行操作。 When you want your list/record processing to be fast, as multiple threads are used for processing the data.当您希望列表/记录处理速度更快时,因为使用多个线程来处理数据。 Also, there can be case when you want to process the data and output it in any random sequence as processing of data done by multiple threads so sequence can be anything.此外,当您想以任何随机顺序处理数据和 output 时,可能会出现这样的情况,因为数据处理由多个线程完成,因此顺序可以是任何东西。

list.parallelStream().forEach(System.out::println);

Parallel streams use ForkJoinPool for processing as it is a common pool used by JVM that can be very restrictive.并行流使用 ForkJoinPool 进行处理,因为它是 JVM 使用的通用池,可能非常严格。 You can control the parallelism level upto a extent, the most efficient way to take parallelism level is acording to the CPU cores, ie take parallelism level as 2*CPU_CORES可以在一定程度上控制并行度,获取并行度最有效的方法是根据CPU核心,即并行度为2*CPU_CORES

Like that in below example you can control parallelism:就像在下面的示例中一样,您可以控制并行度:

    final int parallelism = 10;
    ForkJoinPool forkJoinPool = new ForkJoinPool(parallelism);
    forkJoinPool.submit(() ->
    list.parallelStream().forEach(System.out::println)); 

But be careful using the parallelism, using a large value of parallelism can degrade the performance of the application.但是要小心使用并行度,使用较大的并行度值会降低应用程序的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM