Sobes.tech
Middle

What is a deadlock?

sobes.tech AI

Answer from AI

Deadlock is a situation in multi-threaded or multi-process systems where two or more processes (or threads) are waiting for resources held by each other, and none of them can continue.

Example:

  • Thread A has acquired resource 1 and is waiting for resource 2.
  • Thread B has acquired resource 2 and is waiting for resource 1.

Both threads are blocked forever because each is waiting for the resource held by the other.

In Java, deadlock often occurs due to improper order of acquiring multiple synchronized blocks (synchronized).

Example code with deadlock:

public class DeadlockDemo {
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

    public void method1() {
        synchronized(lock1) {
            // ...
            synchronized(lock2) {
                // ...
            }
        }
    }

    public void method2() {
        synchronized(lock2) {
            // ...
            synchronized(lock1) {
                // ...
            }
        }
    }
}

Here, if two threads call method1 and method2 simultaneously, deadlock may occur.

To prevent deadlock, it is important to follow a resource acquisition order and use timeouts or other synchronization mechanisms.