Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What determines which of two competing threads acquires a lock?

When two threads try to acquire the lock of the same object what are the things that are considered to decide upon to which thread the lock should be handed over.

like image 630
itsraja Avatar asked Oct 09 '22 17:10

itsraja


1 Answers

According to the Java documentation for notify():

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

So if you use synchronized(obj){} you basically have no control on which thread will obtain the lock on obj, and you cannot make any assumption. It depends on the scheduler.

If you want fairness (that is, the next thread obtaining the lock is the first in the queue), have a look at ReentrantLock: it has a boolean flag to specify you want to enforce fairness.

like image 89
Savino Sguera Avatar answered Oct 12 '22 11:10

Savino Sguera