Yahoo Interview Question
Software Engineer / DevelopersProgram shows deadlock.
public class Deadlock {
static Object mutexOne = new Object();
static Object mutexTwo = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new DeadlockProneOne());
Thread t2 = new Thread(new DeadlockProneTwo());
t1.start();
t2.start();
}
}
class DeadlockProneOne implements Runnable {
public void run() {
// Flip locks
synchronized (Deadlock.mutexOne) {
// Do some work
for (int i = 0; i < 100; i++) {
}
synchronized (Deadlock.mutexTwo) {
// Do some work
for (int i = 0; i < 100; i++) {
}
}
}
}
}
class DeadlockProneTwo implements Runnable {
public void run() {
// Flip locks
synchronized (Deadlock.mutexTwo) {
// Do some work
for (int i = 0; i < 100; i++) {
}
synchronized (Deadlock.mutexOne) {
// Do some work
for (int i = 0; i < 100; i++) {
}
}
}
}
}
Fix:
Make sure code is properly synchronized.
To make deadline happen, it must satisfy four conditions:
- Silence February 28, 20101. Each resource is available or hold to exactly one process
2. Process currently hold resources can request new resource
3. Don't allow to force process release resource
4. A chain of processes waiting for resources currently hold by another resource.
So break one of these four conditions, there will be no deadlock.