Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Java's Semaphore fairness an argument to the constructor rather than the acquire() / tryAcquire() calls?

Tags:

java

semaphore

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.)

like image 571
Ata Roboubi Avatar asked Dec 19 '25 12:12

Ata Roboubi


1 Answers

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 use tryAcquire(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).

like image 155
Mike Clark Avatar answered Dec 21 '25 00:12

Mike Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!