简体   繁体   中英

What are pragmatic use cases of parallel stream in Java?

Beginning from Java-8, we can use parallel stream (java.util.stream package)

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.

Moreover, Parallel stream has bit overhead in managing parallelism and abundance caution is required.

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. 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. Also, in web environment, request from a user is independent from other users. In that case, parallel stream is also good.

Parallel streams runs operations over stream in parallel mode. 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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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