Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Deadlock in Java

  • A deadlock occurs when two or more processes are unable to move forward without the assistance of the others. Programming with multiple threads frequently results in deadlock situations. A deadlock, for instance, can happen when one thread is waiting for another thread to acquire the lock on an object, and the second thread is waiting for the first thread to acquire the lock on another object. As a result, there is a deadlock because both threads are waiting for the other to release the lock.

Example of Deadlock


Think about two threads Th1 and Th2, each of which has locked or taken up a resource (Re1 or Re2, respectively). Currently, thread Th1 is asking for resource Re2, and thread Th2 is asking for resource Re1. Till the thread execution is complete, neither of the threads Th1 nor Th2 will release their respective resources Re1 and Re2.






DeadLock Situation

Therefore, the situation is impasse. It is a situation in which all processes are at a standstill and are actively preventing one another from continuing with execution. For an infinite amount of time, the processes in the deadlock wait for one another to release resources.

public class Main {  
    final static String re1 = "Ankita";  
  final static String re2 = "Alok";  
  public static void main(String[] args) {  
	  // creating thread T1
    Thread th1 = new Thread() {  
      public void run() {  
          synchronized (re1) {  
           System.out.println("Thread Th1 locked -->   Resource Re1");    
           try { 
        	   Thread.sleep(100);
            } catch (Exception e) {
            	e.printStackTrace();
            }    
           synchronized (re2) {  
            System.out.println("Thread Th1 locked -->   Resource Re2");  
           }  
         }  
      }  
    };  
	  
    // creating thread T2
    Thread th2 = new Thread() {  
      public void run() {  
        synchronized (re2) {  
          System.out.println("Thread Th2 locked -->   Resource Re2");  
          try { 
        	  Thread.sleep(100);
          }catch (Exception e) {
        	e.printStackTrace();  
          }  
          synchronized (re1) {  
            System.out.println("Thread Th2 locked -->   Resource Re1");  
          }  
        }  
      }  
    };  
      
    th1.start();  
    th2.start();  
  }  
}





Output:

Thread Th2 locked -->   Resource Re2
Thread Th1 locked -->   Resource Re1 

Example to avoid deadlock

public class Main {  	   
    public static void main(String ar[]) {  
        Main test = new Main();  
        final Resource1 re1 = test.new Resource1();  
        final Resource2 re2 = test.new Resource2();  
		Runnable runnable1 = new Runnable() {  
		    public void run() {  
		        synchronized (re2) {  
		            try {  
		                // here we use sleep method so that both threads can start trying to lock resources
		                Thread.sleep(100);  
		            } catch (InterruptedException e) {  
		                e.printStackTrace();  
		            }  
		            // Thread 1 has resource 1, but also requires resource 2.
		            synchronized (re1) {  
		                System.out.println("Inside synchronized block 1");  
		            }  
		        }  
		    }  
		};  		    
		Runnable runnable2 = new Runnable() {  
		    public void run() {  
		        synchronized (re2) {  
		            // Thread 2 has resource 2, but also requires resource 1.
		            synchronized (re1) {  
		                System.out.println("Inside synchronized block 2");  
		            }  
		        }  
		    }  
		};     
        new Thread(runnable1).start();  
        new Thread(runnable2).start();  
    }  
    private class Resource1 {  
        private int b = 25;  
   
        public int getB() {  
            return b;  
        }  
   
        public void setB(int b) {  
            this.b = b;  
        }  
    }  
    private class Resource2 {  
        private int a = 10;  
        public int getA() {  
            return a;  
        }  
   
        public void setA(int a) {  
            this.a = a;  
        }  
    }  
} 




Output:

Inside synchronized block 1
Inside synchronized block 2 

Conditions for Deadlock in Java

  • Deadlock can occur under certain conditions. Let's understand these conditions step by step:
    • Mutual Exclusion : Mutual exclusion is an important factor contributing to deadlock. It means that when a particular thread accessing a resource, that resource cannot be shared with other threads at same time. In simple terms, only one thread can use a resource at a time.
    • Hold and Wait : This condition arises when multiple threads acquire a resource and then request additional resources while still holding the initial ones. This situation can lead to deadlock. In other words, a thread can hold onto a non-shareable resource while waiting for another resource.
    • No Preemption : In a deadlock scenario, a thread cannot be forced to release its resources. Threads have the freedom to voluntarily release their resources at any time, without any predetermined schedule or preemption condition. However, this can lead to deadlock because once a process starts, it cannot be interrupted. Although deadlock can be avoided by taking away the resource from the process causing it, this approach is not recommended as it may result in the loss of the progress made by the process so far.




How to Avoid Deadlock in Java ?

  • While deadlock cannot be entirely avoided, it can be made less likely. Here are a few strategies to help us avoid deadlock situations.
    • Avoid Nested Locks : The main cause of a deadlock condition is when multiple threads are given locks; this must be avoided. Normally, it occurs when multiple threads are given locks.
    • Avoid Unnecessary Locks : Use locks on the team members who require them. Applying locks erroneously can also result in a deadlock.
    • Using Thread Joins : The ReentrantLock class implements the Lock interface and adds features such as the ability to interrupt a thread that is waiting for a lock.



Inter Thread Communication in Java Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java

Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.