I am trying to understand the usefulness of fairness property in Semaphore
class.
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?
The semaphore waiting queue is First-In First-Out (FIFO).
Methods of Semaphore Class. Acquires the given number of permits, if they are available, and returns immediately, reducing the number of available permits by the given amount. If the current thread is interrupted while waiting for a permit then InterruptedException is thrown.
Explanation of above program : The program uses a semaphore to control access to the count variable, which is a static variable within the Shared class.
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.
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