Home » 
        Java programming language
    
    What is Deadlock, how to analyze and avoid it in java?
    
    
    
            
        In this article, we are going to learn about Deadlock in java - What is deadlock and how to analyze and avoid deadlock situation?
        Submitted by Preeti Jain, on  February 15, 2018
    
    Deadlock in java
    
        - When two threads are waiting for each other forever means (i.e. it does not get a chance to enter in a ready queue) such type of infinite waiting is called deadlock.
- A deadlock occurs when the waiting process is still holding onto another resource that the first needs before it can finish.
- By using synchronized keyword we may move towards deadlock situation. Synchronize keyword is not recommended to apply unnecessarily.
- We cannot resolve deadlock but we can avoid deadlock situation based on several techniques.
How can we analyze deadlock situation?
    
        - If all threads have only one object then we can use a graph called wait-for-graph.
- If there are multiple objects for a single thread as 	a cycle then wait-for-graph won't work then we 	should go for such a solution like banker's 	algorithm in operating system to detect a 	deadlock.
In the given example, below we will see the situation of deadlock:
Example:
class HelloClass{
	public synchronized void first(HiClass hi)
	{
		try{
			Thread.sleep(1000);
		}
		catch(InterruptedException ie){}
		System.out.println(" HelloClass is calling 	HiClass second() method");
		hi.second();
	}
	public synchronized void second(){
		System.out.println("I am inside second method of HelloClass");
	}
}
class HiClass{
	public synchronized void first(HelloClass he)
	{
		try{
			Thread.sleep(1000);
		}
		catch(InterruptedException ie){}
		System.out.println(" HiClass is calling HelloClass second() method");
		he.second();
	}
	public synchronized void second(){
		System.out.println("I am inside second method of HiClass");
	}
}
class DeadlockClass extends Thread{
	HelloClass he = new HelloClass();
	HiClass hi = new HiClass();
	public void demo(){
		this.start();
		he.first(hi);
	} 
	public void run(){
		hi.first(he);
	}
	public static void main(String[] args){
		DeadlockClass dc = new DeadlockClass();
		dc.demo();
	}
}
Output
D:\Java Articles>java DeadlockClass
HelloClass is calling HiClass second() method
HiClass is calling HelloClass second() method
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement