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
thread1
releases the lock, which of the threads will be released first? Order synchronization is the exchange of essential product data with one or more external e-commerce systems. It syncs information, such as sold products and a product's stock, between your shop system and other marketplaces.
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
The wait function doesn't release "all locks", but it does release the lock associated with the object on which wait is invoked.
Only one thread is allowed to access only one method at any given point of time using a synchronized block. This is a very expensive operation. Locks avoid this by allowing the configuration of various locks for different purpose.
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
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