In Java, deadlock is a situation that arises in the multithreading concept. This situation may appear in cases where one of your thread is waiting for an object lock, which is acquired by another thread and the second thread waiting for object lock acquired by the first one. Since both become dependent on each other's lock release, so it forms a situation which is termed as deadlock. In such scenarios, the threads get blocked for an infinite timestamp and keep on waiting for each other. When the synchronized keyword halts the thread execution for some time, multiple threads suffer that are associated with that particular object.



Java Example Program to Show How the Deadlock Situation Arises.

Example:

//Java example program to demonstrate thread deadlock.

public class DeadLockExample {
 public static void main(String argu[]) {

  //Define resources shared by multiple threads
  final String RA = "Lex";
  final String RB = "Luthor";

  Thread thread1 = new Thread() {
   public void run() {
    System.out.println("Starting RA");

    synchronized(RA) {
     System.out.println("1st thread - locked 1st string");
     try {
     //"Sleep" is used to create deadlock.
     //The delay ensures that the other thread acquires the lock on RB.
      Thread.sleep(100);
     } catch (Exception ex) {
     }
     synchronized(RB) {
      System.out.println("1st thread - locked 2nd string ");
     }
    }

    // If we reach here then there is no deadlock.
    System.out.println("no deadlock");
   }
  };

  Thread thread2 = new Thread() {
   public void run() {
    System.out.println("Starting RB");

    synchronized(RB) {
     System.out.println("2nd thread - locked 2nd string ");
     try {
      Thread.sleep(100);
     } catch (Exception ex) {
     }
     synchronized(RA) {
      System.out.println("2nd thread - locked 1st string ");
     }
    }
    
    // If we reach here then there is no deadlock.
    System.out.println("no deadlock");
   }
  };
  thread1.start();
  thread2.start();
 }
}

Output:

Starting RA
1st thread - locked 1st string
Starting RB
2nd thread - locked 2nd string


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram