Wednesday, 25 November 2015

Create Deadlock between two threads in Java

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.

Deadlock occurs because:

Mutual exclusion - Two processes cannot simultaneously control the same resource or be in their critical section.

Hold and Wait - processes currently holding resources can request new resources.

No preemption - Once a process holds a resource, it cannot be taken away by another process or the kernel.

Circular wait - Each process is waiting to obtain a resource which is held by another process.

Deadlocks in Java:
Deadlocks can occur in Java when the synchronized keyword causes the executing thread to block while waiting to get the lock, associated with the specified object. Since the thread might already hold locks associated with other objects, two threads could each be waiting for the other to release a lock. In such case, they will end up waiting forever.


class Thread1 implements Runnable {
      public Object obj1;
      public Object obj2;
      public Thread1(Object obj1, Object obj2) {
            this.obj1 = obj1;
            this.obj2 = obj2;
      }

      public void run() {
            synchronized (obj1) {
                  System.out.println("Thread1 : obj1");
                  synchronized (obj2) {
                        System.out.println("Thread1 : obj2");
                  }
            }
      }
}

class Thread2 implements Runnable {
      public Object obj1;
      public Object obj2;
      public Thread2(Object obj1, Object obj2) {
            this.obj1 = obj1;
            this.obj2 = obj2;
      }
      public void run() {
            synchronized (obj2) {
                  System.out.println("Thread2 : obj2");
                  synchronized (obj1) {
                        System.out.println("Thread2 : obj1");
                  }
            }
      }
}

public class Deadlock {
      public static void main(String args[]) throws InterruptedException {
            Object obj1 = new Object();
            Object obj2 = new Object();

            Thread2 runn2 = new Thread2(obj1, obj2);
            Thread1 runn1 = new Thread1(obj1, obj2);

            Thread thrd2 = new Thread(runn2);
            Thread thrd1 = new Thread(runn1);

            thrd1.start();
            thrd2.start();

            while(!thrd2.isAlive() || !thrd1.isAlive()) {
                  System.out.println("No deadlock found");
            }

      }
}

Output:
Thread1 : obj1
Thread2 : obj2

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...