I scanned all the java documentation on the synchronized
statements looking for an answer to this question with no luck.
Say I have thread1
, thread2
, thread3
trying to run the following code all at the same time.
synchronized(lockObj) {
doSomething();
}
Assume thread1
gets first to doSomething()
, thread2
then thread3
which will block and wait on the synchronized
statement.
Question
- When
thread1
releases the lock, which of the threads will be released first? - What is the general order rule that applies when releasing a lock?
1. Either thread2 or thread3. There is no guarantee:
Likewise, no assumptions should be made about the order in which threads are granted ownership of a monitor or the order in which threads wake in response to the notify or notifyAll method
http://docs.oracle.com/javase/1.5.0/docs/guide/vm/thread-priorities.html#general
2. Java monitors (synchronized/await/notify/notifyAll) are non-fair. The synchronization primitives from java 1.5 usually have parameters to enforce the fairness. Be advised that the fair version have a considerably performance penalty, usually the non-fair version should work be used: statistically, every thread will be given the chance to run, even if the order is not strictly enforced.
Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html#ReentrantLock%28boolean%29