Consider the following code:
<code>
public class
Test extends
Thread {
static Object obj1 = new Object();
static Object obj2 = new Object();
public void m1()
{
synchronized(obj1)
{
System.out.print("1 ");
synchronized(obj2)
{
System.out.println("2");
}
}
}
public void m2()
{
synchronized(obj2)
{
System.out.print("2 ");
synchronized(obj1)
{
System.out.println("1");
}
}
}
public void run()
{
m1();
m2();
}
public static void main(
String[] args)
{
new Test().start();
new Test().start();
}
}
</code>
What of the following statements are correct?
a)It may result in deadlock and the program may get stuck
b)There is no potential for deadlock in the code
c)Deadlock may occur but the program will not get stuck as the JVM will resolve the deadlock
d)The program will always print 12,21,12 and 21
e)Nothing can be said for sure
I answered B and D but the answer is A and E. I do not believe that deadlock could occur beacause m1() is called then m2() is called so therefore the lock on obj1 must be released before the lock on obj2 can be acquired. Anyone have any answers?