3

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.

3
  • 1
    A fair lock is one where the threads acquire the lock in the same order they asked for it - wouldn't the ReentrantLock just use a queue? I looked at the source and ReentrantLock has 2 static classes that extend AbstractQueuedSynchronizer, on class for fair the other for not fair. Commented Apr 24, 2016 at 7:02
  • 1
    @JonnyHenly As you say, it uses a queue as the source indicates. No magic going on. +1 Commented Apr 24, 2016 at 7:08
  • 1
    @PeterLawrey Woohoo! I love being not wrong. Commented Apr 24, 2016 at 7:12

1 Answer 1

1

The details are in the source code. And the source code can be found by Googling for:

  • "java.util.concurrent.locks.ReentrantLock source"
  • "java.util.concurrent.locks.AbstractQueuedSynchronizer source"

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.