Learn

Now that we know what Java Streams are and how they work, we can start to understand why they’re good for parallel processing. They ultimately don’t alter the original object passed to them, which helps with the thread-safe problem.

Additionally, Java normally has one stream for processing code, which uses sequential execution and is the default when performing normal threading.

Java Parallel Streams divide a running process into multiple streams that execute in parallel on separate cores, returning a combined result of all the individual outcomes. However, the order of execution is not under our control.

This means we want to try to only use parallel streams when the order of execution doesn’t matter.

To create a parallel stream, we need to invoke the operation Collection.parallelStream. Implementing this may look something like this:

File file = new File(filePath); List<String> textLines = Files.readAllLines(file.toPath()); textLines.parallelStream().forEach(System.out::println);

Alternatively, we can also invoke the operation BaseStream.parallel. Implementing this may look something like this:

File file = new File(filePath); Stream<String> textLines = Files.lines(file.toPath()); textLines.parallel().forEach(System.out::println); textLines.close();

Instructions

1.

Once you understand streams, creating parallel streams is very straightforward. We’ll demonstrate this by using a text file called test.txt, which contains a message over several lines, one word per line.

Below where we print out “[ Parallel streaming from list: ]”, add this line:

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

This method creates a parallel stream from a List, which we’re simply calling a terminal operation on to print out each element. However, the order this happens is random.

Run the code and take note of the random output.

2.

Below where we print out “[ Parallel streaming from stream: ]”, add this line:

textLineStream.parallel().forEach(System.out::println);

Instead of creating parallel streams from a List, this does the reverse. It creates a Stream of type String and streams the text from the file one line at a time.

Run the code and take note of the random output.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?