I see absolutely no reason why this is not a per-call option. The semaphore may be downed in different code paths (master checking progress / workers grabbing work from queue / ...) with different fairness requirements. Perhaps in one case we want to check progress fairly, while in the other we want the same few workers working if there is only enough work for the running workers, to optimize L1 cache hits etc.)
tryAcquire is non-fair even if you have set fair to true in the constructor.
Even when this semaphore has been set to use a fair ordering policy, a call to
tryAcquire()will immediately acquire a permit if one is available, whether or not other threads are currently waiting. This "barging" behavior can be useful in certain circumstances, even though it breaks fairness. If you want to honor the fairness setting, then usetryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS)which is almost equivalent (it also detects interruption).
-- https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html#tryAcquire()
I think this behavior would be sufficient to enable the scenario you outlined (checking progress vs. grabbing work).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With