How to use Parallel Streams in Java?

Java 11 Certification Practice Questions (For the complete list, refer to

http://talks.skilltoz.com/java-11-certification-exam-questions/

Topic: Working with Streams and Lambda expressions

Objective: Perform decomposition and reduction, including grouping and partitioning on sequential and parallel streams

Questions

Q1. Which statements are true about the following code? (Choose all that apply.)
 Set<Integer> mySet = Set.of(5, 2, 8, 10);
   synchronized (mySet) {
      Integer num = mySet
                .parallelStream()
                .sorted()
                .findAny()
                .get();
      System.out.println("Num is " + num);
   }  

A. The first value printed will be 5
B. The first value printed will be 2
C. The code will not compile
D. The output cannot be determined ahead of time
E. The code compiles but throws an exception at runtime

Q2. What will be the output of the following program?
List<String> flowers = Arrays.asList("Jasmine", "Rose", "Lotus", "Lily", "Chrysanthemum","Marigold","Daffodils");
flowers
   .parallelStream()
   .filter(str->str.length() > 4)
   .map(String::toUpperCase)
   .sorted()
.forEach(System.out::println);

Choices

A. CHRYSANTHEMUM DAFFODILS JASMINE LILY LOTUS MARIGOLD ROSE
B. CHRYSANTHEMUM DAFFODILS JASMINE LILY LOTUS MARIGOLD
C. Does not compile
D. Causes exception at runtime
E. Output cannot be fixed as the order is not predictable

Answers

Q1. Choice D is correct. The code compiles and runs without compile time or runtime issues, but the output cannot be predicted. The findAny() method finds any element from a Stream without considering the order. For parallel streams, findAny() method will return the value from the first thread that retrieves a record. Even if sort() is invoked on the parallel stream, findAny() method might not return the first record.

To learn more about parallel streams, check out https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html

Q2. E is the correct answer. When parallel streams are executed, the Java compiler and runtime determine the order in which the stream’s elements are processed so as to maximize the benefits of parallel computing (unless otherwise specified by the stream operation). Hence, The output cannot be guessed as the order is not predictable.

For details, please visit http://talks.skilltoz.com/all-about-parallel-streams/

2 Comments

    1. That is right. Sorting on a parallel stream does not mean that findAny() will return the first matching record. In serial streams, it usually returns the first matching element, although even this behavior is not guaranteed.

Leave a Reply

Your email address will not be published. Required fields are marked *