Java OCA OCP Practice Question 2846

Question

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

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {

   public static void main(String[] args) throws Exception{
      Object o1 = new Object(); 
      Object o2 = new Object(); 
      ExecutorService service = Executors.newFixedThreadPool(2); 
      Future<?> f1 = service.submit(() -> { 
         synchronized (o1) { 
            synchronized (o2) { System.out.println("Tortoise"); } // t1 
         } //from w  ww . j  a v a 2 s. c om
      }); 
      Future<?> f2 = service.submit(() -> { 
         synchronized (o2) { 
            synchronized (o1) { System.out.println("Hare"); } // t2 
         } 
      }); 
      f1.get(); 
      f2.get(); 
   }
}
A.   If the code does output anything, the order cannot be determined.
B.   The code will always output Tortoise followed by Hare.
C.   The code will always output Hare followed by Tortoise.
D.   The code does not compile because of line t1.
E.   The code does not compile because of line t2.
F.   The code may produce a deadlock at runtime.
G.   The code may produce a livelock at runtime.
H.   It compiles but throws an exception at runtime.


A, F.

Note

The code compiles without issue, so D and E are incorrect.

Since both tasks are submitted to the same thread executor pool, the order cannot be determined, so B and C are incorrect and A is correct.

The key here is that the way the resources o1 and o2 are synchronized, a deadlock could appear if the first thread gets o1 and the second thread gets o2; therefore F is correct.

The code cannot produce a live lock, since both threads are waiting, so G is incorrect.

Finally, if a deadlock does occur, an exception will not be thrown, so H is incorrect.




PreviousNext

Related