|
| 1 | +package java_streams; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +public class StreamsExample { |
| 7 | + public static void main(String... args) { |
| 8 | + /**reference: https://www.baeldung.com/java-when-to-use-parallel-stream*/ |
| 9 | + System.out.println("Program started."); |
| 10 | + sequentialStreams(); |
| 11 | + parallelStreams(); |
| 12 | + System.out.println("Program ended."); |
| 13 | + } |
| 14 | + |
| 15 | + private static void sequentialStreams() { |
| 16 | + /**By default, any stream operation in Java is processed sequentially, unless explicitly specified as parallel. |
| 17 | + Sequential streams use a single thread to process the pipeline like below: |
| 18 | + */ |
| 19 | + List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4); |
| 20 | + listOfNumbers.stream().forEach(number -> |
| 21 | + System.out.println(number + " from this thread: " + Thread.currentThread().getName()) |
| 22 | + ); |
| 23 | + } |
| 24 | + |
| 25 | + private static void parallelStreams() { |
| 26 | + /** |
| 27 | + * Any stream in Java can easily be transformed from sequential to parallel. |
| 28 | + * We can achieve this by adding the parallel method to a sequential stream or by creating a stream using the parallelStream method of a collection: |
| 29 | + * */ |
| 30 | + List<Integer> listOfNumbers = Arrays.asList(5, 6, 7, 8); |
| 31 | + listOfNumbers.parallelStream().forEach(number -> |
| 32 | + System.out.println(number + " from this thread: " + Thread.currentThread().getName()) |
| 33 | + ); |
| 34 | + /** |
| 35 | + * Parallel streams enable us to execute code in parallel on separate cores. |
| 36 | + * The final result is the combination of each individual outcome. |
| 37 | + * However, the order of execution is out of our control.*/ |
| 38 | + |
| 39 | + /** |
| 40 | + * Parallel streams make use of the fork-join framework and its common pool of worker threads. |
| 41 | + * The fork-join framework was added to java.util.concurrent in Java 7 to handle task management between multiple threads.*/ |
| 42 | + } |
| 43 | +} |
0 commit comments