Sobes.tech
Senior

What is a deadlock? How to avoid it?

sobes.tech AI

Answer from AI

Deadlock (mutual blocking) is a situation in a multithreaded application where two or more threads permanently block each other, waiting for resources held by the other thread. In Java, deadlock occurs if threads acquire multiple locks in different orders.

To avoid deadlocks:

  • Always acquire locks in the same order.
  • Use timeouts when attempting to acquire locks (for example, tryLock with a timeout in java.util.concurrent.locks.Lock).
  • Minimize the time locks are held.
  • Use higher-level synchronization constructs (such as Semaphore, ConcurrentHashMap) that reduce the risk of deadlocks.

Example of a potential deadlock:

synchronized(lock1) {
    Thread.sleep(100);
    synchronized(lock2) {
        // work
    }
}

// In another thread, the opposite:

synchronized(lock2) {
    Thread.sleep(100);
    synchronized(lock1) {
        // work
    }
}

To prevent deadlocks, always acquire lock1 and lock2 in the same order.