Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 51
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import java.util.stream.IntStream;
- public class Test {
- public static void main(String[] args) {
- List<Integer> list = Collections.synchronizedList(new ArrayList<>());
- IntStream stream = IntStream.rangeClosed(1, 7);
- stream.parallel().map(x -> {
- list.add(x); //Line 13
- return x;
- }).forEach(System.out::print); //Line 15
- System.out.println();
- list.forEach(System.out::print); //Line 17
- }
- }
Which of the following statement is true about above code?
-
A
Line 15 and Line 17 will print exact same output on to the console
-
B
Output cannot be predicted
-
C
Line 15 and Line 17 will not print exact same output on to the console
Reveal correct answer
Correct answer: B
Explanation
Line 13 is changing the state of list object and hence it should be avoided in parallel stream. You can never predict the order in which elements will be added to the stream.
Line 13 and Line 15 doesn't run in synchronized manner, hence as the result, output of Line 17 may be different from that of Line 15.
On my machine below is the output of various executions:
Execution 1:
5427163
5412736
Execution 2:
5476231
5476123
Execution 3:
5476231
5476231
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
