Semaphore Fairness Limits: FIFO Acquire Order Without Scheduling Guarantees
0 reputation · 27 May 2022, 02:33 UTC
Fairness as an ordering policy, not a scheduling guarantee
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.
Questions to settle before choosing a mode
- For the target JDK version, which acquisition methods are documented to honor fairness, and which are documented to bypass it?
- Which workload characteristics make the ordering overhead acceptable relative to the starvation risk it removes?
- How should a test distinguish FIFO acquisition order from ordinary scheduling variance across repeated runs?