Java OCA OCP Practice Question 1977

Question

What is the most likely result of executing the following application?.

package mypkg; //from  ww w.  j ava  2  s . c  o m
import java.util.concurrent.*; 
public class Main { 
   public void sleep() { 
      try { 
         Thread.sleep(5000); 
      } catch (Exception e) {} 
   } 
   public String getQuestion(Main r) { 
      synchronized { 
         sleep(); 
         if(r != null) r.getAnswer(null); 
         return "?"; 
      } 
   } 
   public synchronized String getAnswer(Main r) { 
      sleep(); 
      if(r != null) r.getAnswer(null); 
      return "!"; 
   } 


   public static void main(String... ununused) { 
      final Main r1 = new Main(); 
      final Main r2 = new Main(); 
      ExecutorService s = Executors.newFixedThreadPool(2); 
      s.submit(() -> r1.getQuestion(r2)); 
      s.execute(() -> r2.getAnswer(r1)); 
      s.shutdown(); 
   } 
} 
  • A. A deadlock is produced at runtime.
  • B. A livelock is produced at runtime.
  • C. The application completes successfully.
  • D. The code does not compile.


D.

Note

The synchronized block used in the getQuestion() method requires an object to synchronize on.

Without it, the code does not compile, and Option D is the correct answer.

What if the command was fixed to synchronize on the current object, such as using synchronized(this)?

Each task would obtain a lock for its respective object, then wait a couple of seconds before requesting the lock for the other object.

Since the locks are already held, both wait indefinitely, resulting in a deadlock.

In this scenario, Option A would be the correct answer since a deadlock is the most likely result.

We say most likely because even with corrected code, a deadlock is not guaranteed.

It is possible, albeit very unlikely, for the JVM to wait five seconds before starting the second task, allowing enough time for the first task to finish and avoiding the deadlock completely.




PreviousNext

Related