Java OCA OCP Practice Question 1961

Question

Which statements about executing the following TicketTaker application multiple times are true?

package mypkg; /*  w  w w . j  a  v  a 2  s .c om*/

import java.util.concurrent.atomic.*; 
import java.util.stream.*; 

public class Main { 
  long ticketsSold; 
  final AtomicInteger ticketsTaken; 

  public Main() { 
     ticketsSold = 0; 
     ticketsTaken = new AtomicInteger(0); 
  } 
  public void performJob() { 
     IntStream.iterate(1, p -> p+1) 
        .parallel() 
        .limit(10) 
        .forEach(i -> ticketsTaken.getAndIncrement()); 
     IntStream.iterate(1, q -> q+1) 
        .limit(5) 
        .parallel() 
        .forEach(i -> ++ticketsSold); 
     System.out.print(ticketsTaken+" "+ticketsSold); 
  } 
  public static void main(String[] matinee) { 
     new Main().performJob(); 
  } 
} 
  • I. The class compiles and runs without throwing an exception.
  • II. The first number printed is consistently 10.
  • III. The second number printed is consistently 5.
  • A. I only
  • B. I and II
  • C. I, II, and III
  • D. None of the above


B.

Note

The class compiles and runs without throwing an exception, making the first statement true.

The class defines two values that are incremented by multiple threads in parallel.

The first IntStream statement uses an atomic class to update a variable.

Since updating an atomic numeric instance is thread-safe by design, the first number printed is always 10, and the second statement is true.

The second IntStream statement uses an int with the pre- increment operator (++), which is not thread-safe.

It is possible two threads could update and set the same value at the same time, a form of race condition, resulting in a value less than 5.

The third statement is not true.

Since only the first two statements are true, Option B is the correct answer.




PreviousNext

Related