If I use synchronised methods or locks and some threads enter wait queue, do they leave the wait queue in same order as they entered it? In other words, does the first thread to enter wait queue also leave it first?
Asked
Active
Viewed 77 times
0
-
http://stackoverflow.com/questions/1802830/ensure-java-synchonized-locks-are-taken-in-order – d'alar'cop Sep 08 '13 at 17:57
1 Answers
0
No, the JVM
chooses randomly a Thread
to wake from waiting state either one uses notify()
or notifyAll()
to wake them. In particular with notify()
only one Thread will randomly be chosen to enter the excecution state, while with notifyAll()
all the waiting Threads
together, but there is no guarantee in what order will they be excecuted.

arjacsoh
- 8,932
- 28
- 106
- 166
-
but is there a way to achieve the behaviour I mentioned with syncronized method? – Rohit Malish Sep 08 '13 at 18:05
-
@Rohit: you'd have to use a ReentrantLock. see the question that this is being voted a duplicate of. – Nathan Hughes Sep 08 '13 at 18:06
-
I checked that one, but I'd like to know is ReentrantLock the only way to ensure that kind of behaviour? – Rohit Malish Sep 08 '13 at 18:09
-
btw the wording on this answer is not good, Stephen C's comment on http://stackoverflow.com/a/1802862/217324 applies. – Nathan Hughes Sep 08 '13 at 18:34