Deadlock Of Threads

Deadlock in Java is a condition where two or more threads are blocked forever, waiting for each other. This usually happens when multiple threads need the same locks but obtain them in different orders.

Deadlock in Multithreading

Multithreaded Programming in Java suffers from the deadlock situation because of the synchronized keyword. It causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.

Example

class Example {
    public static void main(String[] args) {
        final String r1 = "edureka";
        final String r2 = "java";

        Thread t1 = new Thread() {
            public void run() {
                synchronized (r1) {
                    System.out.println("Thread 1: Locked r1");
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        // printStackTrace method
                        // prints line numbers + call stack
                        e.printStackTrace();

                        // Prints what exception has been thrown
                        System.out.println(e.toString());
                    }
                    synchronized (r2) {
                        System.out.println("Thread 1: Locked r2");
                    }
                }
            }
        };
        Thread t2 = new Thread() {
            public void run() {
                synchronized (r1) {
                    System.out.println("Thread 2: Locked r1");
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        // printStackTrace method
                        // prints line numbers + call stack
                        e.printStackTrace();

                        // Prints what exception has been thrown
                        System.out.println(e.toString());
                    }
                    synchronized (r2) {
                        System.out.println("Thread 2: Locked r2");
                    }
                }
            }
        };

        t1.start();
        t2.start();
    }
}

Output:

Thread 1: Locked r1
Thread 2: Locked r2

How To Avoid Deadlock in Java?

Although it is not completely possible to avoid deadlock condition, but we can follow certain measures or pointers to avoid them:

  • Avoid Nested Locks – You must avoid giving locks to multiple threads, this is the main reason for a deadlock condition. It normally happens when you give locks to multiple threads.

  • Avoid Unnecessary Locks – The locks should be given to the important threads. Giving locks to the unnecessary threads that cause the deadlock condition.

  • Using Thread Join – A deadlock usually happens when one thread is waiting for the other to finish. In this case, we can use Thread.join with a maximum time that a thread will take.

core java programming multithreading concurrency

Subscribe For More Content