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.
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.
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