Deadlock in java

A deadlock in Java occurs when two or more threads are blocked forever, each waiting for the other to release a lock. In other words, a set of threads is in a circular waiting state, and no progress can be made. Deadlocks are one of the common concurrency issues that can occur when working with multiple threads. They can lead to the application becoming unresponsive and are generally undesirable.

Here’s a simple example to illustrate a deadlock scenario:

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

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            synchronized (lock1) {
                System.out.println("Thread 1: Holding lock 1");
                try {
                    Thread.sleep(1000); // Simulate some work
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 1: Waiting for lock 2");
                synchronized (lock2) {
                    System.out.println("Thread 1: Holding lock 1 and lock 2");
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (lock2) {
                System.out.println("Thread 2: Holding lock 2");
                try {
                    Thread.sleep(1000); // Simulate some work
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 2: Waiting for lock 1");
                synchronized (lock1) {
                    System.out.println("Thread 2: Holding lock 2 and lock 1");
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}

In this example, Thread 1 holds lock1 and is waiting for lock2, while Thread 2 holds lock2 and is waiting for lock1. This creates a circular waiting situation, resulting in a deadlock. To avoid deadlocks, it’s crucial to follow best practices for managing locks, such as acquiring locks in a consistent order and using techniques like timeout mechanisms or deadlock detection.

To prevent deadlocks, consider the following practices:

  1. Lock Ordering:
  • Acquire locks in a consistent order to avoid circular waiting.
  1. Lock Timeout:
  • Implement mechanisms to timeout and release locks if a thread cannot acquire all the required locks within a specified time.
  1. Lock Hierarchy:
  • Establish a hierarchy for acquiring locks to ensure that threads always acquire locks in a predefined order.
  1. Deadlock Detection:
  • Implement deadlock detection mechanisms to identify and recover from deadlock situations.
  1. Minimize Lock Contention:
  • Minimize the duration for which locks are held to reduce the likelihood of contention.

It’s important to carefully design and review the concurrent aspects of your application to prevent and mitigate deadlock situations. Using higher-level concurrency utilities from the java.util.concurrent package, such as ExecutorService and Lock, can also help in managing concurrency more effectively.

Deadlock in java a special type of error that we need to avoid that relates specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects. For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever because to access X, it would have to release its own lock on Y so that the first thread could complete. Deadlock is a difficult error to debug for two reasons:

  • In general, it occurs only rarely, when the two threads time-slice in just the right way
  • It may involve more than two threads and two synchronized objects.

An example of deadlock

class A {
synchronized void foo(B b) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered A.foo");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("A Interrupted");
}
System.out.println(name + " trying to call B.last()");
b.last();
}
synchronized void last() {
System.out.println("Inside A.last");
}
}
class B {
synchronized void bar(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("B Interrupted");
}
System.out.println(name + " trying to call A.last()");
a.last();
}
synchronized void last() {
System.out.println("Inside A.last");
}
}
class Deadlock implements Runnable {
A a = new A();
B b = new B();
Deadlock() {
Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b); // get lock on a in this thread.
System.out.println("Back in main thread");
}
public void run() {
b.bar(a); // get lock on b in other thread.
System.out.println("Back in other thread");
}
public static void main(String args[]) {
new Deadlock();
}
}

The output of this program

MainThread entered A.foo
RacingThread entered B.bar
MainThread trying to call B.last()
RacingThread trying to call A.last()

Leave a Comment