Semaphore Fairness Limits: FIFO Acquire Order Without Scheduling Guarantees
0 reputation · 27 May 2022, 02:33 UTC
0 reputation · 27 May 2022, 02:33 UTC
java.util.concurrent.Semaphore exposes a constructor that accepts a fairness boolean, and the class has offered that parameter since Java 5. Setting it to true makes threads blocked in acquire() obtain permits in FIFO order, which limits starvation among contending threads. The default, false, leaves acquisition order nondeterministic.
The unresolved part is the scope of the guarantee. Fairness constrains the order in which waiting threads are released by this semaphore; it says nothing about which thread the operating system schedules next, so a fair semaphore does not yield deterministic execution order or bounded latency. Fair mode also adds ordering bookkeeping relative to the barging-friendly default.
34775 reputation · 27 May 2022, 10:30 UTC
acquire(), acquire(int permits), acquireUninterruptibly(), acquireUninterruptibly(int permits), acquire(long timeout, TimeUnit unit), acquire(int permits, long timeout, TimeUnit unit). These methods consult the semaphore’s internal FIFO queue when fair is true.tryAcquire(), tryAcquire(int permits), tryAcquire(long timeout, TimeUnit unit) do not respect fairness; they return immediately based on the current permit count.doAcquire routine performs the fairness check; any method that ultimately calls doAcquire is subject to the flag.Semaphore sem = new Semaphore(1, true);CountDownLatch to start all worker threads simultaneously.acquire() into a thread‑safe list.Even with fair = true, the semaphore only guarantees that permits are handed out in FIFO order. Once a thread receives a permit, it becomes a runnable task in the JVM’s thread pool, and the underlying OS scheduler decides when it actually runs. Therefore:
run() invocations is not achieved.To tailor the recommendation precisely, could you confirm which Java Development Kit (JDK) version you are targeting? The documented behavior of fairness‑sensitive methods can vary subtly between JDK 8, 11, 17, and 21.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.