Java OCA OCP Practice Question 1979

Question

What is the output of the following application?.

package pkg; /*from   w  ww.ja va  2s  .  c om*/
import java.util.concurrent.*; 
public class Main { 
   int stroke = 0; 
   public synchronized void swimming() { 
      stroke++; 
   } 
   public static void main(String... laps) { 
      ExecutorService s = Executors.newFixedThreadPool(10); 
      Main a = new Main(); 
      for(int i=0; i<1000; i++) { 
         s.execute(() -> a.swimming()); 
      } 
      s.shutdown(); 
      System.out.print(a.stroke); 
   } 
} 
  • A. 1000
  • B. The code does not compile.
  • C. The result is unknown until runtime because stroke is not accessed in a thread-safe manner and a write may be lost.
  • D. The result is unknown until runtime for some other reason.


D.

Note

The application compiles, so Option B is incorrect.

The stroke variable is thread- safe in the sense that no write is lost since all writes are wrapped in a synchronized method, making Option C incorrect.

Even though the method is thread-safe, the value of stroke is read while the threads may still be executing.

The result is it may output 0, 1000, or anything in-between, making Option D the correct answer.

If the ExecutorService method awaitTermination() is called before the value of stroke is printed and enough time elapses, then the result would be 1000, and Option A would be the correct answer.




PreviousNext

Related