Junior — Middle
Can you provide a real example of a situation where mutual resource locking occurred in a system or life?
sobes.tech AI
Answer from AI
Deadlock is a situation where two or more processes (or threads) are waiting for resources held by each other, and none of them can continue.
A real-life example: two people walking towards each other in a narrow corridor, each yielding to the other, and neither wants to step back. As a result, they both stand still and cannot pass.
An example in Java programming:
Object resourceA = new Object();
Object resourceB = new Object();
Thread thread1 = new Thread(() -> {
synchronized (resourceA) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (resourceB) {
System.out.println("Thread 1 acquired both resources");
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (resourceB) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (resourceA) {
System.out.println("Thread 2 acquired both resources");
}
}
});
thread1.start();
thread2.start();
Here, thread1 acquires resourceA and waits for resourceB, while thread2 does the opposite — resourceB and waits for resourceA. As a result, a deadlock occurs.