5

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
itsraja
  • 1,640
  • 4
  • 32
  • 48

2 Answers2

4

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.

Savino Sguera
  • 3,522
  • 21
  • 20
  • Thanks. Also, it seems synchronized(obj) block invokes wait() also, Could you outline the chain of actions that are performed before, during and after the synchronized block or methods – itsraja Feb 11 '12 at 17:31
  • What do you mean? The algorithm used to ensure mutual exclusion on a piece of code? Or the scheduling algorithm? For the former, just conceptually, you may want to have a look at Peterson's algorithm: https://en.wikipedia.org/wiki/Peterson's_algorithm . For the latter, it's discussed here: http://stackoverflow.com/questions/2816011/what-is-the-jvm-scheduling-algorithm – Savino Sguera Feb 11 '12 at 18:44
  • Thanks. I meant mutual exclusion in terms of Java's methods. like wait(), notify()... I will be glad to see a sequence of these function calls simulated for 2 threads trying for 1 object. Hey this is analogous to 2(or more) boys proposing 1 girl. They call it wedlock ;) – itsraja Feb 12 '12 at 03:23
0

According to Java Oracle Docs:

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order.

If you are allowing fairness then FIFO (First-in-First-out) is used, otherwise it seems random (from my observations).

Kevin Jalbert
  • 3,115
  • 3
  • 26
  • 39
  • you are assuming he uses ReentrantLock... he only said "threads competing for a lock on the same object", that could be any Object IMHO – Savino Sguera Feb 11 '12 at 15:17