Java OCA OCP Practice Question 2001

Question

Assuming 10 seconds is enough time for all of the tasks to finish, what is the output of the following application?.

package mypkg; /*from w  ww.j  a  va  2 s  . c  o  m*/

import java.util.concurrent.*; 

public class Main { 
   static int cookies = 0; 
   public synchronized void deposit(int amount) { 
      cookies += amount; 
   } 
   public static synchronized void withdrawal(int amount) { 
      cookies -= amount; 
   } 
   public static void main(String[] amount) throws Exception { 
      ExecutorService teller = Executors.newScheduledThreadPool(50); 
      Main bank = new Main(); 
      for(int i=0; i<25; i++) { 
         teller.submit(() -> bank.deposit(5)); 
         teller.submit(() -> bank.withdrawal(5)); 
      } 
      teller.shutdown(); 
      teller.awaitTermination(10, TimeUnit.SECONDS); 
      System.out.print(bank.cookies); 
   } 
} 
  • A. 0
  • B. The code does not compile.
  • C. The result is unknown until runtime.
  • D. An exception is thrown at runtime.


C.

Note

The program compiles and does not throw an exception at runtime, making Options B and D incorrect.

The class attempts to add and remove values from a single cookie variable in a thread-safe manner but fails to do so because the methods deposit() and withdrawal() synchronize on different objects.

The instance method deposit() synchronizes on the bank object, while the static method withdrawal() synchronizes on the static Main.class object.

Even though method calls of the same type are protected, calls across the two different methods are not.

Since the compound assignment operators (+=) and (-=) are not thread-safe, it is possible for one call to modify the value of cookies while the other is already operating on it, resulting in a loss of information.

For this reason, the output cannot be predicted, and Option C is the correct answer.

If the two sets of calls were properly synchronized on the same object, then the cookies variable would be protected from concurrent modifications, and Option A would be the correct answer.




PreviousNext

Related