Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Multihreading Synchronization with Lock

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.

like image 382
Sarang Shinde Avatar asked Feb 01 '26 11:02

Sarang Shinde


1 Answers

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.

like image 183
Stephen C Avatar answered Feb 03 '26 08:02

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!