Parallel Stream in Java
Java 8 and higher have a feature called Java Parallel Streams that allows you to make use of many processor cores. Any Java code typically has a single processing stream where it is carried out in order. The ultimate output is a mixture of the individual results when employing parallel streams, which divide the code into many streams that are performed concurrently on different cores. However, we have no influence over the execution order.
Therefore, it is recommended when using parallel streams in situations where the outcome is unaffected by the sequence of execution, the state with one element doesn't really affect the other, and the source of the information likewise does not change.
Why Parallel Stream in Java
In order to improve program performance, parallel streams were invented; nevertheless, choosing parallel streams isn't always the best option. There are some situations in which we require the code to run in a specific order, and in these situations, sequential streams work better to complete our task at the expense of performance.
Large-scale programs or intricate projects are the only ones that should be concerned about the performance disparity between the two types of streams. For little programs, it might not even be apparent. Basically, when the consecutive stream functions poorly, you should think about adopting parallel streams.
Analysis of a Java Parallel Stream
Parallel streams are implemented to improve a program's performance. Employing a parallel stream won't necessarily improve the outcome, though. One situation can call for the execution of code in a specific order.
In some situations, it is necessary to use sequential streams rather than parallel streams because we need the code to run in a specific order.
Methods for Making Streams
We can create two different approaches, which are given below and explained in more detail below:
- Using the stream's parallel() method
- Using a Collection and parallelStream()
It is built on applying the parallel() or parallelStream() methods to collections or streams, respectively.
Syntax:
List<Object> list=new ArrayList<Object>();
list.parallelStream();
Explanation:
- Firstly, we create an array list of collections.
- paralleStream() method was used on an array collection.
- We come to the conclusion that parallelStream() only applied to collections.
Syntax:
IntStream inStream=IntStream.rangeClosed(initialValue, finalValue); inStream.parallel();
Explanation:
- An IntStream stream is first created.
- applied the parallel() function to the stream.
- We reach the conclusion that parallel() is only applied to streams.
Method 1: Using the stream's parallel() method
An analogous parallel stream is produced via the BaseStream interface's parallel() function.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) throws IOException {
File fileName = new File("M:\\Documents\\Textfile.txt");
Stream<String> text = Files.lines(fileName.toPath());
text.parallel().forEach(System.out::println);
text.close();
}
}
Method 2: Applying parallelStream() to a Collection
The Collection interface's parallelStream() method returns a potential parallel stream with both the collection and the source. Let's use an example to describe how it works.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
public class Demo {
public static void main(String[] args)
throws IOException
{
File fileName
= new File("M:\\Documents\\List_Textfile.txt");
List<String> text
= Files.readAllLines(fileName.toPath());
text.parallelStream().forEach(System.out::println);
}
}
Examples
Example 1
import java.util.stream.IntStream;
public class ParallelStream
{
public static void main(String[] argvs)
{
System.out.println("In Normal\n");
IntStream r = IntStream.rangeClosed(1, 5);
r.forEach(System.out::println);
System.out.println("In Parallel\n");
IntStream r1 = IntStream.rangeClosed(1, 5);
r1.parallel().forEach(System.out::println);
}
}
The output of the above program
In Normal
1
2
3
4
5
In Parallel
3
5
4
2
1
Example 2
import java.util.List;
import java.util.ArrayList;
public class ParallelStream2
{
public static void main(String[] argvs)
{
System.out.println("In Normal");
List<String> l1 = getData();
l1.stream().forEach(System.out::println);
System.out.println("In Parallel");
List<String> l2 = getData();
l2.parallelStream().forEach(System.out::println);
}
private static List<String>getData()
{
List<String> l1 = new ArrayList<>();
int alphabets = 97;
while (alphabets <= 106)
{
char ch = (char)alphabets;
l1.add(String.valueOf(ch));
alphabets = alphabets + 1;
}
return l1;
}
}
The output of the above program
In Normal
a
b
c
d
e
f
g
h
i
j
In Parallel
F
g
i
j
h
c
d
e
a
b
Example 3
import java.util.stream.IntStream;
public class ParallelStream3
{
public static void main(String[] args)
{
System.out.println("In Normal");
IntStream r = IntStream.rangeClosed(1, 5);
if(r.isParallel())
{
System.out.println("Running concurrently is the stream.");
}
else
{
System.out.println("Not Running concurrently is the stream.");
}
r.forEach(System.out::println);
System.out.println("In Parallel");
IntStream r2 = IntStream.rangeClosed(1, 5);
IntStream r2Parallel = r2.parallel();
if(r2.isParallel())
{
System.out.println("Running concurrently is the stream..");
}
else
{
System.out.println("Not Running concurrently is the stream..");
}
r2Parallel.forEach(System.out::println);
}
}
The output of the above program
In Normal
Not Running concurrently is the stream.
1
2
3
4
5
In Parallel
Running concurrently is the stream..
35
4
2
1