Java OCA OCP Practice Question 2842

Question

What statements about the following code are true? (Choose all that apply.)

import java.util.Arrays;

public class Main {

   public static void main(String[] args) {
      Integer i1 = Arrays.asList(1, 2, 3, 4, 5).stream().findAny().get();
      synchronized (i1) { // y1
         Integer i2 = Arrays.asList(6, 7, 8, 9, 10).parallelStream().sorted() // y2
               .findAny().get(); // y3
         System.out.println(i1 + " " + i2);
      }//from w  w w . j a  va 2s.co m

   }
}
  • A. It outputs 1 6.
  • B. It outputs 1 10.
  • C. The code will not compile because of line y1.
  • D. The code will not compile because of line y2.
  • E. The code will not compile because of line y3.
  • F. It compiles but throws an exception at runtime.
  • G. The output cannot be determined ahead of time.
  • H. It compiles but waits forever at runtime.


G.

Note

The code compiles and runs without issue, so C, D, E, F, and H are incorrect.

There are two important things to notice: first, synchronizing on the first output doesn't actually impact the results of the code.

Second, sorting on a parallel stream does not mean that findAny() will return the first record.

The findAny() method will return the value from the first thread that retrieves a record.

Therefore, the output is not guaranteed for either serial or parallel stream.

Since the results cannot be predicted ahead of time, G is the correct answer.




PreviousNext

Related