Java OCA OCP Practice Question 2596

Question

Consider the following program:

import java.util.concurrent.Semaphore;

class Main {/*  w  w  w  .  j av  a 2  s  .  c  o  m*/
   public static void main(String[] args) {
      Semaphore machines = new Semaphore(2); // #1
      new Person(machines, "Mickey");
      new Person(machines, "Donald");
      new Person(machines, "Tom");
      new Person(machines, "Jerry");
      new Person(machines, "Casper");
   }
}

class Person extends Thread {
   private Semaphore machines;

   public Person(Semaphore machines, String name) {
      this.machines = machines;
      this.setName(name);
      this.start();
   }

   public void run() {
      try {
         System.out.println(getName() + " waiting to access an ATM machine");
         machines.acquire();
         System.out.println(getName() + " is accessing an ATM machine");
         Thread.sleep(1000);

         System.out.println(getName() + " is done using the ATM machine");
         machines.release();
      } catch (InterruptedException ie) {
         System.err.println(ie);
      }
   }
}

Which one of the options is true if you replace the statement #1 with the following statement?

Semaphore machines = new Semaphore(2, true);
  • a) The exact order in which waiting persons will get the ATM machine cannot be predicted.
  • b) The ATM machine will be accessed in the order of waiting persons (because of the second parameter in semaphore constructor).
  • c) It will not compile since second parameter in semaphore instantiation is not allowed.
  • d) It will result in throwing an IllegalMonitorStateException.


a)

Note

The second parameter states the fairness policy of the semaphore object.

However, there are two permits for the semaphore object; so you cannot predict the order in which waiting people will get the permission to access the ATM.




PreviousNext

Related