What Is Deadlock In java

A condition that occurs when two processes are each waiting for the other to complete before proceeding. The result is that both processes hang. Deadlocks occur most commonly in multitasking and client/server environments. Ideally, the programs that are deadlocked, or the operating system, should resolve the deadlock, but this doesn't always happen.

The Following examples depicts how we can have deadlock in java.






public class MyDeadlockTest
{
  public static void main(String[] args)
  {
    final Object object1 = "object1";
    final Object object2 = "object2";
    // t1 tries to lock object1 then object2
    Thread t1 = new Thread()
    {
      public void run()
      {
        // Lock resource 1
        synchronized (object1)
        {
          System.out.println("Thread 1: locked object 1");
          try
          {
            Thread.sleep(50);
          }
          catch (InterruptedException e)
          {
          }
          synchronized (object2)
          {
            System.out.println("Thread 1: locked object 2");
          }
        }
      }
    };
    // t2 tries to lock object2 then object1
    Thread t2 = new Thread()
    {
      public void run()
      {
        synchronized (object2)
        {
          System.out.println("Thread 2: locked object 2");
          Thread.yield();
          object2.notifyAll();
          try
          {
            // Thread.sleep(50);
          }
          catch (Exception e)
          {
          }
          synchronized (object1)
          {
            System.out.println("Thread 2: locked object 1");
          }
        }
      }
    };
    // If all goes well, deadlock will occur,
    // and the program will never exit.
    t1.start();
    t2.start();
  }
}

Comments

  1. Good one man.keep posted
    to read more about java thread and dead lock deadlock in java
    FIX protocol tutorial

    ReplyDelete

Post a Comment

Popular posts from this blog

Difference between volatile and synchronized

Converting Java Map to String

Masking Credit Card number in Java