1

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.

fashuser
  • 2,152
  • 3
  • 29
  • 51
  • 4
    *"When set true, under contention, locks favor granting access to the longest-waiting thread."* [Source](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html) What is unclear? – T.J. Crowder Oct 19 '14 at 21:26
  • 1
    Go to a post office or a supermarket, and suggest the postman or the cashier to serve the last people in the queue first. You'll understand why fairness can be important. – JB Nizet Oct 19 '14 at 21:39
  • Actually I am aware how this feature works. The main questions was when to use this. I didn't find any valuable example with this stuff. I would like to find some example from the real project. Thanks! – fashuser Oct 20 '14 at 18:55

1 Answers1

1

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.

rolfl
  • 17,539
  • 7
  • 42
  • 76