Java 8 Streams parallelism introduction.
In java, processing elements with an explicit for-loop is inherently serial processing. Streams facilitate
parallel execution as well. All streams operations can execute either in serial or in parallel. The stream implementations
in the JDK create serial streams unless parallelism is explicitly requested. For example, Collection has methods Collection.stream() and
Collection.parallelStream(), which produce sequential and parallel streams respectively; other stream-bearing methods such
as IntStream.range(int, int) produce sequential streams but these streams can be efficiently parallelized by invoking their
BaseStream.parallel() method.
Stream pipeline serial or parallel execution id directly depends on the orientation of the stream on which it is invoked.
Whether a stream will execute in serial or parallel can be determined with the isParallel() method, and the orientation of a stream can
be modified with the BaseStream.sequential() and BaseStream.parallel() operations. When the terminal operation is initiated, the stream
pipeline is executed sequentially or in parallel depending on the mode of the stream on which it is invoked.
Here is a simple example on Steam parallelism: The below example, combines filtering a list based on
number of characters, converting them to upper case, sorting and finally printing them into single line of code, which is the power of
streams.
package com.java2novice.streams;
import java.util.Arrays;
import java.util.List;
public class ParallelStreamIntroEx {
public static void main(String a[]) {
List<String> vehicles = Arrays.asList("bus", "car", "bicycle", "flight", "train");
vehicles.parallelStream().filter(str->str.length() > 3).map(String::toUpperCase).sorted().forEach(System.out::println);;
}
}
|
|