Parallel Data Processing in Java | Set 1

We know that new Stream in Java (introduced in Java 8) interface let us manipulate collections of data in a declarative way.
In this topic, we will discover how the Stream interface gives us the opportunity to execute operations in parallel on a collection of data without much effort. It lets us declaratively turn a sequential stream into a parallel one

Definition and Making into Parallel Streams:
A parallel stream is one that splits the elements into multiple streams and assigns them into multiple chunks on different threads. Thus we can divide the workload of a given operation on the core of multiprocessors and thus it will make the CPU busy. We can convert the stream into parallel by attaching the keyword ‘parallel’.

Following example just gives us the idea how we can convert a stream into a parallel one!

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple Java program to demonstrate parallel
// processing.
import java.util.stream.*;
import java.util.Collections.*;
public class JavaApplication1 {
  
    static long sumparallel(long n)
    {
        // Stream converted to parallel stream 
        return Stream.iterate(1L, i->i + 1).
                       limit(n).parallel(). 
                       reduce(0L, Long::sum);
    }
  
    // Driver code
    public static void main(String[] args)
    {
        long c = sumparallel(10);
        System.out.println("Sum is " + c);
    }
}

chevron_right


Output :

Sum is 55

In the next part, we will see the difference between the performance of parallel streams, sequential streams and iterative process and taking a review on certain more specialized methods in parallel streams.




Reference :

https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html

This article is contributed by keshav_786. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.