Java OCA OCP Practice Question 2594

Question

Consider the following program:

import java.util.concurrent.locks.*;

public class Main {
        public static void main(String []args) {
                Lock lock1 = new ReentrantLock();
                Lock lock2 = new ReentrantLock();
                try {
                        System.out.println("Going to lock...");
                        lock1.lock();/*from  ww  w.ja va2  s  .c o  m*/
                        System.out.println("In critical section");
                } finally {
                        lock2.unlock();
                        System.out.println("Unlocking ...");
                }
        }
}

Which one of the following options is correct?

a)      This program will print the following:
      "Going to lock..."
      "In critical section"
      Unlocking ...//  w  ww  .j  a  va  2 s. c  o m

b)      This program will print the following:
      "Going to lock..."
      "In critical section"
      and then terminate normally.

c)      This program will print the following:
     "Going to lock..."
     "In critical section"
     and then enter into a deadlock because lock2.unlock() waits for lock2 to get locked first.

d)     This program will throw an IllegalMonitorStateException.


d)

Note

Note that in this program you call the lock() method on the lock1 variable and call the unlock() method on the lock2 variable.

Hence, in lock2.unlock(), you are attempting to call unlock() before calling lock() on a Lock object and this results in throwing an IllegalMonitorStateException.




PreviousNext

Related