Consider the following code and explanations:
------------------------------------
public void getLocks(Object a, Object b)
{
synchronized(a)
{
synchronized(b)
{
//do something
}
}
}
and the following instantiations:
Object obj1 = new Object();
Object obj2 = new Object();
obj1 and obj2 are accesible to two different threads and the threads are about to call the getLocks() method.
Assume the first
thread calls the method getLocks(obj1, obj2).
-------------------------------------------------
Question: Which of the following is true?
a) The second Thread should call getLocks(obj2,obj1)
b) The second Thread should call getLocks(obj1,obj2)
c) The second Thread should call getLocks() only after the first exits out of it.
d) The second Thread my call getLocks() at any time and with passing arguments in any order
e) none of the above
-------------------------------------------------
The correct answer is b).
Why is that? I expected d) to be the correct answer.
-Bernd