kuriouscoder kuriouscoder - 7 months ago 32
Java Question

Fairness setting in semaphore class

I am trying to understand the usefulness of fairness property in


Specifically to quote the Javadoc mentions that:

Generally, semaphores used to control resource access should be initialized as fair, to ensure that no thread is starved out from accessing a resource. When using semaphores for other kinds of synchronization control, the throughput advantages of non-fair ordering often outweigh fairness considerations.

Could someone provide an example where barging might be desired here. I cannot think past resource access use case. Also, why is that the default is non-fair behavior?

Lastly, are there any performance implications in using the fairness behavior?


Java's built-in concurrency constructs (synchronized, wait(), notify(),...) do not specify which thread should be freed when a lock is released. It is up to the JVM implementation to decide which algorithm to use.

Fairness gives you more control: when the lock is released, the thread with the longest wait time is given the lock (FIFO processing). Without fairness (and with a very bad algorithm) you might have a situation where a thread is always waiting for the lock because there is a continuous stream of other threads.

If the Semaphore is set to be fair, there's a small overhead because it needs to maintain a queue of all the threads waiting for the lock. Unless you're writing a high throughput/high performance/many cores application, you won't probably see the difference though!

Scenario where fairness is not needed

If you have N identical worker threads, it doesn't matter which one gets a task to execute

Scenario where fairness is needed

If you have N tasks queues, you don't want one queue to be waiting forever and never acquiring the lock.