问题
What will happen to the request for synchronized block from different threads, if current threads holds the monitor? example: say below is the synchronized block:
ABC.java:
public class ABC {
...
public void setValue(){
Example object = Example.getinstance();
// Example is a singleton class which maintains the arraylist of objects of class ABC
synchronized (object) {
object.storeObject(this);
}
}
...
}
suppose there are three threads T1,T2,T3 which is creating objects for ABC class e.g: obj1,obj2,obj3. and all three objects are calling setValue method of ABC class:
example:
Thread T1: obj1.setValue()
Thread T2: obj2.setValue()
Thread T3: obj3.setValue()
What will happen to the requests(T2 & T3) if first request(Thread T1) is under processing? Will it be rejected, or other threads will be suspended or Queued up? If rejected or suspended , how to process all the request?
回答1:
One thread acquires the lock at a time. If the lock is already taken, any other requesting threads block - that is, pause execution - until the lock is free. You can think of it as "queueing up", keeping in mind that that is not exactly what happens: the intrinsic locks used with the synchronized keyword are not fair, it's up to the OS scheduler to decide which thread goes first. It doesn't have to choose according to who asked first, it can pick any of the threads that are waiting on that lock.
In your example the threads will all get a chance to acquire the lock (none of them get turned away or timed out), but there's no telling what order they will do it in.
回答2:
The first thread to hit the synchronized block will enter it. The rest will block until the first one exists the block. Then another thread will take the lock, leaving the rest to wait, and so on.
回答3:
The only thread that can request AND then attain the lock on the object is the thread which has already the lock,Any other thread has to wait untill the lock is freed.You may like to know more about re-entrant locks as well.
The below code wont cause a deadlock.
synchronize(lock){
callTheLogic();
}
void callTheLogic(){
synchronize(lock){
}
来源:https://stackoverflow.com/questions/32010904/what-will-happen-to-the-request-for-synchronized-block-in-java-if-monitor-is-alr