Reputation: 1489
I am really confused why this feature need by java. Please share some real examples when fairness mode can be used with ex: ReentrantLock, ReadWriteLock, Semaphore
.
Upvotes: 1
Views: 406
Reputation: 17705
Fairness is useful when you have a situation that needs better representation of order.
A case when I have used a fair lock, was in a logging queue (no, I could not use log4j or whatever), and I wanted to have concurrency, while still managing to log the output in an order similar to the order it arrived in.
I could have used a concurrent queue, but there were other factors at play, and locking on the thread level was better than having a queue where perhaps threads could add multiple values before they got their turn again. It was complicated... but, adding a fair lock allowed items to go through in a representative order.
In fact, thinking of the fair lock as being approximately an arrival-order queue for the threads, is useful, and the threads can't just drop their load and leave and do other things like a concurrent queue would do. Here you queue the threads, not the workload.
Note, the order is not guaranteed, but, for the most part, the order was indistinguishable from that.
Upvotes: 1