Parallel Processing in Java
- Difference Between the Parallel and Sequential Processing
-
Parallel Processing in Java Using
parallelStream()
-
Parallel Processing in Java Using
parallel()
-
Parallel Processing in Java Using
CompletableFuture
Parallel processing is a new trend in modern programming. This processing allows us to run multiple tasks simultaneously, lessening the processing time, but the tasks should be independent.
In this article, we will see the parallel processing in Java, along with necessary examples and explanations to make the topic easier.
Difference Between the Parallel and Sequential Processing
In sequential processing, all the independent processes of a task run one by one, and when one process is working, another process needs to wait.
On the other hand, in parallel processing, multiple processes can run at a time, and they need not wait for the end of one process. Parallel processing is essential for multitasking.
Parallel Processing in Java Using parallelStream()
This example will illustrate how we can perform parallel processing in Java. Let’s take a look at our below example:
// importing necessary packages
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class JavaParallal {
public static void main(String[] args) {
// Creating an integer array
Integer[] IntArray = {1, 2, 3, 4, 5, 6, 7, 8};
// Creating a list from the integer array
List<Integer> NumList = new ArrayList<>(Arrays.asList(IntArray));
System.out.println("The list elements using Serial Stream:");
NumList.stream().forEach(num -> System.out.print(num + " ")); // Sequencial processing here
System.out.println("");
System.out.println("The list elements using Parallel Stream:");
NumList.parallelStream().forEach(
num -> System.out.print(num + " ")); // Parallal processing here
System.out.println("");
}
}
We already commanded the purposes of each line. When you execute this code, you should get an output like the one below in your console:
The list elements using Serial Stream:
1 2 3 4 5 6 7 8
The list elements using Parallel Stream:
6 5 8 3 7 4 2 1
Parallel Processing in Java Using parallel()
In our below example, we illustrated how we could perform parallel processing using the method parallel()
.
Suppose we have a text file with the below contents:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
Observe the sample code below:
// importing necessary packages
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.stream.Stream;
public class JavaParallal {
public static void main(String[] args) throws IOException {
// Locating the file
File MyFile = new File("G:\\Java Projects\\SimpleJavaCodes\\src\\SampleTexts.txt");
Stream<String> FileContent = Files.lines(MyFile.toPath()); // Reading the file
FileContent.parallel().forEach(System.out::println); // Parallal
FileContent.close();
}
}
We already commanded the purposes of each line. When you execute this code, you will obtain an output like the one below in your console:
This is line 6
This is line 5
This is line 2
This is line 1
This is line 4
This is line 7
This is line 8
This is line 3
Parallel Processing in Java Using CompletableFuture
In our below example, we demonstrated how we could perform parallel processing using the method CompletableFuture
. Have a look at the below sample code:
// importing necessary packages
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class JavaCompleteTableFuture {
public static void main(String[] args) {
try {
List<Integer> MyList = Arrays.asList(2, 3, 5); // Declaring a list element
MyList.stream()
.map(Number -> CompletableFuture.supplyAsync(() -> GetNumber(Number)))
.map(CompletableFuture -> CompletableFuture.thenApply(N -> N * N))
.map(T -> T.join())
.forEach(S -> System.out.println(S + " "));
} catch (Exception e) {
e.printStackTrace();
}
}
private static int GetNumber(int a) {
return a + a;
}
}
In our above example,
supplyAsync()
- This method completes a job asynchronously. By default, the methodForkJoinPool.commonPool()
run the task from the supplier.thenApply()
- This method accepts a function as an argument and returns a newCompletableStage
after the current stage completes normally.join()
- This method returns the result after it’s completely done.
When you run the above command, you will get an output like the one below in your console:
16
36
100
Please note that the example codes shared here are in Java, and you must install Java on your environment if your system doesn’t have it.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn