All for Joomla All for Webmasters

Deadlock in java

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
deadlock

Example of Deadlock in java

  1. public class TestDeadlockExample1 {
  2.   public static void main(String[] args) {
  3.     final String resource1 = “ratan jaiswal”;
  4.     final String resource2 = “vimal jaiswal”;
  5.     // t1 tries to lock resource1 then resource2
  6.     Thread t1 = new Thread() {
  7.       public void run() {
  8.           synchronized (resource1) {
  9.            System.out.println(“Thread 1: locked resource 1”);
  10.            try { Thread.sleep(100);} catch (Exception e) {}
  11.            synchronized (resource2) {
  12.             System.out.println(“Thread 1: locked resource 2”);
  13.            }
  14.          }
  15.       }
  16.     };
  17.     // t2 tries to lock resource2 then resource1
  18.     Thread t2 = new Thread() {
  19.       public void run() {
  20.         synchronized (resource2) {
  21.           System.out.println(“Thread 2: locked resource 2”);
  22.           try { Thread.sleep(100);} catch (Exception e) {}
  23.           synchronized (resource1) {
  24.             System.out.println(“Thread 2: locked resource 1”);
  25.           }
  26.         }
  27.       }
  28.     };
  29.     t1.start();
  30.     t2.start();
  31.   }
  32. }
Output: Thread 1: locked resource 1
        Thread 2: locked resource 2deadlock
PinIt
submit to reddit

Leave a Reply

Top