Junior — Middle
Can the cause of system hangs be explained and how does it affect the application's performance?
sobes.tech AI
Answer from AI
A deadlock occurs when two or more threads or processes block each other, waiting for resources held by the other. For example, thread A holds resource 1 and waits for resource 2, while thread B holds resource 2 and waits for resource 1. As a result, neither thread can continue.
This leads to the application becoming unresponsive or malfunctioning, as the threads are in a state of infinite waiting. In multithreaded Java applications, deadlocks can cause the user interface to freeze, reduce performance, and even crash the system.
To prevent deadlocks, it is important to:
- Avoid nested locks or use them in a strictly defined order.
- Use timeouts when acquiring locks.
- Apply high-level synchronization constructs such as
java.util.concurrent.
An example of a simple deadlock in Java:
public class DeadlockDemo {
private final Object resource1 = new Object();
private final Object resource2 = new Object();
public void method1() {
synchronized(resource1) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized(resource2) {
System.out.println("Method1 acquired both resources");
}
}
}
public void method2() {
synchronized(resource2) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized(resource1) {
System.out.println("Method2 acquired both resources");
}
}
}
}
If two threads call method1 and method2 simultaneously, a deadlock may occur.