2

ReentrantLock API doc says:

  1. The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread.
  2. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock.

I am not able to understand points 2:

If one thread obtain lock multiple times in succession, then as per point 1, other threads will wait for longer and that does mean they will get the lock next time. Then how this does not affect (fairness of) thread scheduling? Thus, I feel fair lock is nothing but longest waiting time first thread scheduling.

MsA
  • 2,599
  • 3
  • 22
  • 47
  • 1
    A fair lock is pretty simple to understand. A lock is "fair" if, when one thread releases the lock while more than one other thread is waiting for it, the winner always is the one that's been waiting the longest. My _guess_ is, the author was trying to warn newbies who might get the wrong idea that simply dropping a fair lock into an application would guarantee that the threads competing for it will all politely take turns. – Solomon Slow Mar 28 '20 at 19:57
  • @SolomonSlow The problem is that a Java fair ReentrantLock does not work this way. What you describe would result in FIFO processing. Unfortunately my experience of fair ReentrantLock in Java 11 is that the processing is not FIFO, more like random which thread gets lock next. See also https://stackoverflow.com/a/38955729/150978 – Robert Jul 01 '21 at 12:52

1 Answers1

1

I think they're just trying to separate the fairness logic side from the scheduling logic. Threads may be concurrent, but that doesn't mean they try to access Locks simultaneously. Thread priority requests are only 'hints' to the OS, and are never guaranteed the way they may be expected.

So, just because you have threads A and B, which may request a lock, which may even have identical behavior, one thread may execute, acquire the lock, release, re-acquire, before the other locks even request it:

A: Request Lock -> Release Lock -> Request Lock Again (Succeeds) B: Request Lock (Denied)... ----------------------- Time --------------------------------->

Thread scheduling logic is decoupled from the Lock logic.

There are other scheduling issues too, the burden of which often falls on the software designer, see Starvation and Livelock

user176692
  • 780
  • 1
  • 6
  • 21