Junior — Middle
Have you ever encountered deadlock situations in systems?
sobes.tech AI
Answer from AI
Yes, deadlock is a situation where two or more processes or threads are waiting indefinitely for resources held by each other.
In Java, this can happen due to improper synchronization, such as two threads trying to acquire two monitors in different orders.
Example:
Object lock1 = new Object();
Object lock2 = new Object();
Thread t1 = new Thread(() -> {
synchronized(lock1) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized(lock2) {
// work
}
}
});
Thread t2 = new Thread(() -> {
synchronized(lock2) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized(lock1) {
// work
}
}
});
t1.start();
t2.start();
To avoid deadlock, it is important to follow a consistent lock acquisition order and minimize the time resources are held.