• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Deadlock

How to avoid deadlock in java ?

May 23, 2017 By j2eereference 1 Comment

Conditions to avoid deadlock :
1)Lock Ordering : Deadlock occurs when multiple threads need same locks but acquired in different order and hence get blocked. In order to avoid this ,make sure that threads acquire the needed locks in same order so that one thread is able to complete its task and releases the locks and after that other thread can resume its processing.
Below program doesnot follow lock ordering and results in deadlock condition .In program output you can check that neither Thread-A not thread-B complete their processing as statement is never printed

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class DeadLockDemo
{
  public static void main(String[] args)
  {
    Thread threadA = new Thread("Thread-A")
    {
      public void run()
      {
        System.out.println(Thread.currentThread().getName()+ " has started its processing");
        synchronized (Integer.class)
        {
          try {
                Thread.sleep(100);
              } catch (InterruptedException e)
              {
                e.printStackTrace();
              }
         System.out.println(Thread.currentThread().getName()
         + " has acquired lock on Integer class and waiting to acquire lock
         on Float class to complete its processing");
        synchronized (Float.class)
        {
           System.out.println(Thread.currentThread().getName()
           + " has acquired lock on Float class");
        }
       }
       System.out.println(Thread.currentThread().getName()+ " has completed its processing");
      }
    };
  Thread threadB = new Thread("Thread-B")
  {
    public void run()
    {
      System.out.println(Thread.currentThread().getName()+ " has started its processing");
      synchronized (Float.class)
      {
        System.out.println(Thread.currentThread().getName()
        + " has acquired lock on Float class and waiting to acquire lock on Integer class");
        try {
              Thread.sleep(100);
            } catch (InterruptedException e)
            {
              e.printStackTrace();
            }
      synchronized (Integer.class)
      {
        System.out.println(Thread.currentThread().getName()
        + " has acquired lock on Integer class");
      }
     }
   System.out.println(Thread.currentThread().getName()+ " has completed its processing");
  }
};
   threadA.start();
   threadB.start();
}
}

OutPut:
Thread-B has started its processing
Thread-A has started its processing
Thread-B has acquired lock on Float class and waiting to acquire lock on Integer class
Thread-A has acquired lock on Integer class and waiting to acquire lock on Float class to complete its processing

Now, change the order of locks in the above program by taking lock on Integer class first and then Float class. In Program Output , you can check that now both Thread-a and Thread-B are able to complete their task.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class DeadLockDemo
{
  public static void main(String[] args)
  {
    Thread threadA = new Thread("Thread-A")
    {
      public void run()
      {
        System.out.println(Thread.currentThread().getName()+ " has started its processing");
        synchronized (Integer.class)
        {
          try {
                Thread.sleep(100);
              } catch (InterruptedException e)
              {
                e.printStackTrace();
              }
              System.out.println(Thread.currentThread().getName()
              + " has acquired lock on Integer class and waiting to acquire lock on
              Float class to complete its processing");
 
       synchronized (Float.class)
       {
         System.out.println(Thread.currentThread().getName()
         + " has acquired lock on Float class");
       }
      }
        System.out.println(Thread.currentThread().getName()+ " has completed its processing");
     }
    };
 
    Thread threadB = new Thread("Thread-B")
    {
      public void run()
      {
        System.out.println(Thread.currentThread().getName()+ " has started its processing");
        synchronized (Integer.class)
        {
          System.out.println(Thread.currentThread().getName()+ " has acquired lock on Float class and waiting to acquire lock on Integer class...");
          try
          {
            Thread.sleep(100);
          } catch (InterruptedException e)
          {
            e.printStackTrace();
           }
 
         synchronized (Float.class)
         {
           System.out.println(Thread.currentThread().getName()
           + " has acquired lock on Integer class");
          }
         }
           System.out.println(Thread.currentThread().getName()+ " has completed its processing");
        }
       };
 
       threadA.start();
       threadB.start();
  }
}

OutPut :
Thread-A has started its processing
Thread-B has started its processing
Thread-B has acquired lock on Float class and waiting to acquire lock on Integer class…
Thread-B has acquired lock on Integer class
Thread-B has completed its processing
Thread-A has acquired lock on Integer class and waiting to acquire lock on Float class to complete its processing
Thread-A has acquired lock on Float class
Thread-A has completed its processing

2)Avoid nested synchronization blocks as it makes a thread to acquire another lock while it already holds one lock.This can result in deadlock in case if other thread wants to use the same lock which is held by this thread.

3)Lock the code where it is actually required and not the whole method ,so use synchronized blocks around the specific lines of code that you want to make thread safe in place of synchronized method.

4)Lock Timeout: another way to prevent deadlock is to specify time for a thread to acquire lock and If thread fails to acquire the lock in the specified time then it should give up trying for that lock and retry after some time.

5)Use Join() Method : Using join method threads can start and end sequentially as join method waits for a thread to complete its task on which it is called and then start the next thread processing.

 

Related Posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Difference between Stack and Heap memory
  • What is ThreadMXBean in java?
  • What is serialVersionUID
  • What is exchanger in concurrency?

Filed Under: Core Java Tagged With: Conditions to avoid deadlock, Deadlock, Lock ordering to prevent deadlock, lock timeout

What is deadlock in java?

May 22, 2017 By j2eereference 1 Comment

What is Deadlock : A deadlock  is the situation where two or more threads are holding lock on resources and  waiting for each other to release the lock  from the resources in order to complete their task.

Let’s assume, Thread 1 has acquired lock on Resource 1 and requesting for Resources 2 and Thread 2 has acquired lock on Resource2 and requesting for Resource1. So, Thread1 needs Resource 2 which is held by Thread2 to complete its task whereas Thread2 needs Resource1 which is held by thread1 to complete its task.

DeadLock Example :

In below Program, Thread-A is waiting for Thread-B to release lock on Float.class and Thread-B is waiting for Thread-A to release lock on Integer.class .Deadlock is formed here as both threads are blocked and waiting for each other to release the lock. Please note down one thing that in the output statement  ” has completed its processing ” is  never printed in and this is because of deadlock between Thread-A & Thread-B is never ended.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class DeadLockDemo {
  public static void main(String[] args)
  {
    Thread threadA = new Thread("Thread-A")
    {
      public void run()
      {
        System.out.println(Thread.currentThread().getName()+ " has started its processing");
        synchronized (Integer.class)
       {
        try {
              Thread.sleep(100);
            } catch (InterruptedException e)
            {
              e.printStackTrace();
            }
             System.out.println(Thread.currentThread().getName()
             + " has acquired lock on Integer class and waiting to acquire lock on Float
              class to complete its processing");
            synchronized (Float.class)
            {
              System.out.println(Thread.currentThread().getName()+ " has acquired lock on Float class");
            }
       }
             System.out.println(Thread.currentThread().getName()+ " has completed its processing");
      }
    };
 
    Thread threadB = new Thread("Thread-B")
    {
      public void run()
      {
        System.out.println(Thread.currentThread().getName()+ " has started its processing");
        synchronized (Float.class)
        {
           System.out.println(Thread.currentThread().getName()+ " has acquired lock on Float class and waiting to acquire lock on Integer class");
           try {
                 Thread.sleep(100);
               } catch (InterruptedException e)
               {
                  e.printStackTrace();
                }
            synchronized (Integer.class)
            {
               System.out.println(Thread.currentThread().getName()+ " has acquired lock on Integer class");
             }
          }
               System.out.println(Thread.currentThread().getName()+ " has completed its processing");
        }
     };
 
      threadA.start();
      threadB.start();
   }
}

OutPut:

Thread-B has started its processing
Thread-A has started its processing
Thread-B has acquired lock on Float class and waiting to acquire lock on Integer class
Thread-A has acquired lock on Integer class and waiting to acquire lock on Float class to complete its processing

Conditions for deadlock to occur:

1)Mutual Exclusion: In this condition, only one thread at a time can hold the shared resource exclusively and use it other requesting threads must wait for this thread to release the shared resource.

2)Hold and wait: In this condition, thread must hold the allocated resource while waiting for other resource which is currently being held by other thread.

3)Circular wait: In this, a circular waiting chain is formed where each thread in the list is waiting for the resource being held by next thread in the list.

4)No Preemption: Operating system must not remove the resource allocated to a thread until thread execution completed or released voluntarily by the thread holding it.

Related Posts

  • UncaughtExceptionHandler in java
  • How to generate and resolve OutOfMemoryError?
  • Difference between Spring’s Singleton scope & Singleton Design pattern
  • How to stop a thread?
  • Interrupting a thread in java
  • What is ThreadLocal in Java ?
  • ArrayList custom Implementation
  • Difference between volatile and synchronized keyword?
  • How to write thread safe code?
  • Difference between Serializable and Externalizable

Filed Under: Core Java Tagged With: Deadlock, Deadlock condition, Deadlock creation program, what is deadlock

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.