Java Deadlock


In java, a deadlock occurs in a situation when two or more threads are blocked and waiting for each other to release the lock.


A thread waiting for an object lock but it obtained by another thread and another thread is waiting for an object lock but is obtained by the first thread. Both threads are waiting forever for each other to release the lock.

Dead Lock

Example:

 public class Deadlock{
    public static Object obj1 = new Object();
    public static Object obj2 = new Object();
    private static class Thread1 extends Thread {
        public void run() {
            synchronized (obj1) {
                System.out.println("Thread 1: Holding lock 1");
                try { 
                    Thread.sleep(50); 
                }
                catch (InterruptedException e) {
                    System.out.println("Main thread Interrupted");
                }
                System.out.println("Thread 1: Waiting for lock 2");
                
                synchronized (obj2) {
                   System.out.println("Thread 1: Holding lock 2");
                }
            }
        }
    }
    private static class Thread2 extends Thread {
        public void run() {
            synchronized (obj2) {
                System.out.println("Thread 2: Holding lock 2");
                try { 
                    Thread.sleep(50); 
                }
                catch (InterruptedException e) {
                    System.out.println("Main thread Interrupted");
                }
                System.out.println("Thread 2: Waiting for lock 1");
                
                synchronized (obj1) {
                   System.out.println("Thread 2: Holding lock 1");
                }
            }
        }
   } 
   public static void main(String args[]) {
      Thread1 t1 = new Thread1();
      Thread2 t2 = new Thread2();
      t1.start();
      t2.start();
   }
}



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.