Question

Directly from this website:

But if we are specifying the fairness parameter as “true” while creating a new ReentrantLock object, it gives us the guaranty that the longest waiting thread will get the lock next. Sounds pretty nice right?

I thought that it is never guaranteed, it just influences the decision of the scheduler. Isn't it or the website above-linked is actually saying the truth?

Thanks in advance.

Was it helpful?

Solution

The API documentation for ReentrantLock says (my emphasis):

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. 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. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.

So it would seem the website you quote is oversimplifying a bit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top