Loading Posts...

Deadlock in Java Example | Java Deadlock Tutorial

Deadlock in Java Example | Java Deadlock Tutorial

Deadlock in Java Example | Java Deadlock Tutorial is today’s topic. A deadlock consists of a set of blocked processes, in which each process is holding a resource and waiting to receive another resource which is already owned by another process. It may occur when two processes/threads want the same resource, and there comes confusion about which process should take the resource first and then deadlock occurs. We use the synchronized keyword before the class name and method name to avoid deadlock.

Deadlock in Java

Deadlock describes the situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when the multiple threads need the same locks but obtain them in a different order.

See the following figure.

 

Deadlock in Java

In the above diagram, thread1 requires the resource/object which is held by thread2 and thread2 requires the object which is owned by thread3 and so on. As thread2 does not release its resource and thread1 waiting for a long time, there comes deadlock.

Example

See the following code about the deadlock in java.

public class deadlock {
  static Object Lock1 = new Object();
  static Object Lock2 = new Object();

  private static class Thread1 extends Thread {
    public void run() {
      synchronized (Lock1) {
        System.out.println("Thread 1: Has Lock1");
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {

        }
        System.out.println("Thread 1: Waiting for Lock 2");
        synchronized (Lock2) {
          System.out.println("Thread 1: No DeadLock");
        }
      }
    }
  }

  private static class Thread2 extends Thread {
    public void run() {
      synchronized (Lock2) {
        System.out.println("Thread 2: Has Lock2");
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {

        }
        System.out.println("Thread 2: Waiting for Lock 1");
        synchronized (Lock1) {
          System.out.println("Thread 2: No DeadLock");
        }
      }
    }
  }

  public static void main(String args[]) {
    Thread1 thread1 = new Thread1();
    Thread2 thread2 = new Thread2();
    thread1.start();
    thread2.start();
  }
}

See the output.

 

Deadlock in Java Example

#How to avoid deadlock in Java

Whenever a resource is allocated to a thread, that resource cannot be assigned to another thread until it releases it. Just reverse the order of passing of object. 

See the following code example.

public class deadlock {
  static Object Lock1 = new Object();
  static Object Lock2 = new Object();

  private static class Thread1 extends Thread {
    public void run() {
      synchronized (Lock2) {
        System.out.println("Thread 1: Has Lock1");
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {

        }
        System.out.println("Thread 1: Waiting for Lock 2");
        synchronized (Lock1) {
          System.out.println("Thread 1: No DeadLock");
        }
      }
    }
  }

  private static class Thread2 extends Thread {
    public void run() {
      synchronized (Lock2) {
        System.out.println("Thread 2: Has Lock2");
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {

        }
        System.out.println("Thread 2: Waiting for Lock 1");
        synchronized (Lock1) {
          System.out.println("Thread 2: No DeadLock");
        }
      }
    }
  }

  public static void main(String args[]) {
    Thread1 thread1 = new Thread1();
    Thread2 thread2 = new Thread2();
    thread1.start();
    thread2.start();
  }
}

See the following output.

 

How to avoid deadlock in Java

So, Deadlock is the part of the multithreading. Deadlock can occur in the situation when a thread is waiting for an object lock, another thread and second thread acquire that is waiting for an object lock that is obtained by the first thread.

Since both the threads are waiting for each other to release a lock, the condition is called deadlock.

We can avoid deadlock condition by knowing its possibilities. It’s a very complicated process and not easy to catch. But still, if we try, we can prevent this.

There are some methods by which we can avoid the deadlock condition. We can’t altogether remove its possibility, but we can reduce.

  1. Avoid Nested Locks: It is the main reason for the deadlock. The DeadLock mainly happens when we give locks to multiple threads. Avoid giving a lock to multiple threads if we already have given to one.
  2. Avoid Unnecessary Locks: We should have lock only those members which are required. Having a lock on unnecessarily can lead to deadlock.
  3. Using thread join: Deadlock condition appears when one thread is waiting other to finish. If this condition occurs, we can use Thread.join with the maximum time you think the execution will take.

#Key Points

  1. If the threads are waiting for each other to finish, then the condition is known as Deadlock.
  2. Deadlock condition is the complex condition which occurs only in the case of multiple threads.
  3. A deadlock condition can break our code at run time and can destroy the whole business logic.

Finally, Deadlock in Java Example | Java Deadlock Tutorial is over.

The post Deadlock in Java Example | Java Deadlock Tutorial appeared first on AppDividend.

Get Free Email Updates!

Signup now and receive an email once I publish new content.

I agree to have my personal information transfered to MailChimp ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.

user

The author didnt add any Information to his profile yet

Show one comment

August 14, 2019
0

Good day! examsworld.co.in

We put up of the sale

Sending your message through the feedback form which can be found on the sites in the Communication partition. Contact form are filled in by our application and the captcha is solved. The superiority of this method is that messages sent through feedback forms are whitelisted. This method increases the odds that your message will be read.

Our database contains more than 25 million sites around the world to which we can send your message.

The cost of one million messages 49 USD

FREE TEST mailing of 50,000 messages to any country of your choice.

This message is automatically generated to use our contacts for communication.

Contact us.
Telegram – @FeedbackFormEU
Skype FeedbackForm2019
Email – [email protected]

Leave a Comment

Loading Posts...