Is it possible to associate the size of a semaphore with the order of execution of threads?

After looking at some literature for exam 1Z0-804, I find this example for him:

Consider the following program:

class ATMRoom { 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 parameter is true if you replace statement # 1 with the following expression? Semaphore machines = new Semaphore(2, true);

Omitting Answers

Explaining the correct answer caught my attention:

The second parameter specifies the equity policy of the semaphore object. However, there are two permissions for the semaphore object; therefore, you cannot predict the order in which waiting people will receive permission to access the ATM.

I would say that the order cannot be predicted simply because of the non-deterministic nature of the flows, and not because of the number of permissions in the Semaphore, and that the justice parameter ensures that the waiting flows are awakened in the same order they acquired the semaphore, but still the acquisition order cannot to be determined. Is my interpretation correct?

+4
source share
2 answers

As far as I understand, yes, your idea is correct, since a fair semaphore uses FairSync, and the mechanism for obtaining it does not relay according to the number of permissions available, but only in the first thread in the thread queue:

  protected int tryAcquireShared(int acquires) { for (;;) { if (getFirstQueuedThread() != Thread.currentThread() && hasQueuedThreads()) return -1; .... 
+1
source

I would say, since they all call start in their constructor, you can guarantee the order in which the threads are created and their initial order, you cannot say anything about the order that their run methods are called.

So - essentially - you are right, the number of semaphores does not play a role at all in order.

0
source

Source: https://habr.com/ru/post/1483582/


All Articles