In Java we can implements fairness by using Lock interface and ReentrantLock class as follows :
Lock lock=new ReentrantLock(true);
Once we implement fairness then in the case of multiple threads waiting to access the lock, the one which is waiting for most duration is given access to lock.
Can anybody provide details of how JVM keep the track of threads waiting for long time i.e how fairness is implemented by JVM.
The details are in the source code. And the source code can be found by Googling for:
The code is exceptionally well commented.
The short answer is that each lock has a queue of waiting threads that is implemented as a linked list.
In the "fair" case, a thread that tries to acquire the lock when the queue is non-empty is added to the end of the queue.
In the "unfair" case, a thread may barge in if the lock is currently free. This gives better performance because you don't need to do a thread context switch which entails a syscall.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With