Skip to content
Related Articles

Related Articles

What is Java Parallel Streams?
  • Last Updated : 27 Aug, 2020

Java Parallel Streams is a feature of Java 8 and higher, meant for utilizing multiple cores of the processor. Normally any java code has one stream of processing, where it is executed sequentially. Whereas by using parallel streams, we can divide the code into multiple streams that are executed in parallel on separate cores and the final result is the combination of the individual outcomes. The order of execution, however, is not under our control.

Therefore, it is advisable to use parallel streams in cases where no matter what is the order of execution, the result is unaffected and the state of one element does not affect the other as well as the source of the data also remains unaffected.

There are two ways we can create parallel streams in Java:

1. Using parallel() method on a stream

The parallel() method of the BaseStream interface returns an equivalent parallel stream. Let us explain how it would work with the help of an example.



 In the code given below, we create a file object which points to a pre-existent txt file in the system. Then we create a Stream that reads from the text file one line at a time. Then we use the parallel() method to print the read file on the console. The order of execution is different for each run, you can observe this in the output. The two outputs given below have different orders of execution.

Java




// An example to understand the parallel() method
  
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.stream.Stream;
  
public class ParallelStreamTest {
  
    public static void main(String[] args) throws IOException {
  
        // Create a File object 
        File fileName = new File("M:\\Documents\\Textfile.txt");
          
        // Create a Stream of String type
        // Using the lines() method to read one line at a time
        // from the text file
        Stream<String> text = Files.lines(fileName.toPath());
          
        // Use StreamObject.parallel() to create parallel streams
        // Use forEach() to print the lines on the console
        text.parallel().forEach(System.out::println);
          
        // Close the Stream
        text.close();
    }
}

Output 1:

Output 1

Output 2:

Output 2

2. Using parallelStream() on a Collection

The parallelStream() method of the Collection interface returns a possible parallel stream with the collection as the source. Let us explain the working with the help of an example.

In the code given below, we are again using parallel streams but here we are using a List to read from the text file. Therefore, we need the parallelStream() method.

Java




// An example of parallelStream() method
  
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
  
public class ParallelStreamsTest3 {
  
    public static void main(String[] args) throws IOException {
  
        // Create a File object
        File fileName = new File("M:\\Documents\\List_Textfile.txt");
  
        // Create a List
        // Using readAllLines() read the lines of the text file
        List<String> text = Files.readAllLines(fileName.toPath());
          
        // Using parallelStream() to create parallel streams
        text.parallelStream().forEach(System.out::println);
    }
}

Output:

Output

Why Parallel Streams?

Parallel Streams were introduced to increase the performance of a program, but opting for parallel streams isn’t always the best choice. There are certain instances in which we need the code to be executed in a certain order and in these cases, we better use sequential streams to perform our task at the cost of performance. The performance difference between the two kinds of streams is only of concern for large scale programs or complex projects. For small scale programs, it may not even be noticeable. Basically you should consider using Parallel Streams when the sequential stream behaves poorly.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :