Create or simulate deadlock in multi threading (concurrency/ java/ example)

What is deadlock in concurrency?

The deadlock is the situation, which occurs when one thread is waiting for the resource, which has been acquired by second thread and second thread is waiting for the resource which has been acquired by first thread. This cyclic dependency results in a deadlock situation.

Example of deadlock situation in java

  1. Suppose, we have two threads thread1 and thread2.
  2. thread1 acquired the lock1.
  3. thread2 acquired the lock2.
  4. thread1 is waiting for lock2 (which has been acquired for thread2).
  5. thread2 is waiting for lock1 (which has been acquired for thread1).
  6. The cyclic dependency of resources results in deadlock i.e. thread1 waiting for lock2 and thread2 waiting for lock1.
deadlock multiple thread example
Fig 1: Deadlock situation – multiple threads

Program – create deadlock in java using multiple threads (example)

package org.learn;

public class CreateDeadlock {

 static Object lock1 = new Object();
 static Object lock2 = new Object();
 
 public static void main(String[] args) {
  
  // 1. Create and start thread 1
  // 2. Acquire lock1
  // 3.  Acquire lock2
  new Thread("Thread 01") {
   public void run() {
    synchronized(lock1) {
     System.out.println("1.1 Thread 01 got lock 1");
     try { 
      Thread.sleep(500);
      }
              catch (InterruptedException e) {
               System.out.println("Thread 01 InterruptedException occured");
              }
     System.out.println("1.2 Thread 01 waiting for lock 2");
     synchronized(lock2) {
      System.out.println("Thread 01 got lock 2");      
     }
    }
   }
  }.start();
  
  // 1. Create and start thread 2
  // 2. Acquire lock2
  // 3.  Acquire lock1
  new Thread("Thread 02") {
   public void run() {
    synchronized(lock2) {
     System.out.println("2.1 Thread 02 got lock 2");
     try { 
      Thread.sleep(500); 
     }
     catch (InterruptedException e) {
               System.out.println("Thread 02 InterruptedException occured");
              }
     System.out.println("2.2 Thread 02 waiting for lock 1");
     synchronized(lock1) {
      System.out.println("Thread 02 got lock 1");      
     }
    }
   }
  }.start();
 }
}

Output – deadlock simulation in java using multiple threads

1.1 Thread 01 got lock 1
2.1 Thread 02 got lock 2
1.2 Thread 01 waiting for lock 2
2.2 Thread 02 waiting for lock 1
Scroll to Top