Java – fair setting in semaphore class
I'm trying to understand the usefulness of fair property in semaphore grade
Specifically, reference Javadoc to mention:
Someone can provide an example where a barge may be needed I can't think of past resource access use cases In addition, why is default unfair?
Finally, what is the performance impact of using fair behavior?
Solution
Java's built-in concurrency structure (synchronized, wait(), notify(),...) does not specify which thread should be released when the lock is released The JVM implementation determines which algorithm to use
Fairness gives you more control: when the lock is released, the thread with the longest waiting time is given the lock (FIFO processing) Without fairness (and using a very bad algorithm), you may encounter a thread always waiting for a lock because there is a continuous flow of other threads
If the semaphore is set to fair, its overhead is small because it needs to maintain the queue of all threads waiting for locks Unless you're writing high throughput / high performance / many Kernel Applications, you won't see the difference!
There is no need for a fair scene
If you have n identical worker threads, it doesn't matter if any task is executed
Need a fair scene
If you have n task queues, you do not need a queue to wait forever and never acquire locks