Infibeam Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
package threading;
class DeadLock1 {
public static synchronized void method() {
System.out.println("Thread executed Deadlock1" + Thread.currentThread());
DeadLock2.method();
}
}
class DeadLock2 {
public static synchronized void method() {
System.out.println("Thread executed Deadlock2" + Thread.currentThread());
DeadLock1.method();
}
}
public class DeadLock {
public static void main(String [] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
DeadLock1.method();
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
DeadLock2.method();
}
});
t2.start();
}
}
In the main class... I started 2 threads, t1 --> Invoking DeadLock1.method() [ thus it gains the lock on DeadLock1 class object] , t2 --> Inboking DeadLock2.method() [ thus it gains the lock on DeadLock2 class object]
Now... DeadLock1.method is trying to call DeadLock2.method , hence forcing the thread t1 to make hold the lock of DeadLock2 class object, which is already held by t2.
Similarly t2 is not able to access DeadLock1's lock. Both threads are waiting for each other to release the lock, hence DeadLock!!
public class OneMoreDeadlock
- raghava.javvaji September 19, 2012{
public static void main(String args[])
{
Thread t1 = new Thread(new Runnable()
{
public void run()
{
synchronized(String.class)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Waiting for integer");
synchronized(Integer.class)
{
System.out.println("Thread1");
}
}
}
});
Thread t2 = new Thread(new Runnable()
{
public void run()
{
synchronized(Integer.class)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Waiting for string");
synchronized(String.class)
{
System.out.println("Thread2");
}
}
}
});
t1.start();
t2.start();
}
}
Fix: change the order of resources.