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

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

http://talks.skilltoz.com/all-about-parallel-streams

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

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 *