Learn Java Basics Concepts

Java Beginners Guide: What is DeadLock with example | DeadLock Vs Starvation in Multithreading

what is Dead Lock

 If two threads are waiting for each other forever such type of infinite waiting is called deadlock.

Synchronized keyword is only reason for dead lock situation hence while using synchronized keyword we have take special care.

 There are no resolution techniques for deadlock but several prevention techniques are available.

DeadLock Sample Program 

package Multithreading;

 class A {
    public synchronized void d1(B b){
try{System.out.println("thread 1 starts execution of d1() method");
Thread.sleep(6000);
}catch(InterruptedException e){}    
        System.out.println("thread 1 trying to call B's last() method");
        b.last();
    } 
    public synchronized void last(){
    
        System.out.println("inside A, this last() method");
    
    }
    
 }
class B
{
public synchronized void m2(A a)
{

System.out.println("thread 2 starts execution of d2() method");

try{

Thread.sleep(60000 );
}catch(InterruptedException e){}
 System.out.println("thread 2 trying to call A's last() method");
a.last();
}
public synchronized void last()
{
        System.out.println("inside B, this last() method");
}
}

class DeadLock1 extends Thread{
A a=new A();
B b=new B();

public void m1()
{
this.start();
a.d1(b);//this is executed by main thread
}
public void run(){

b.d2(a);//this is executed by child thread

}
    public static void main(String[] args) {
        
        DeadLock1 d=new DeadLock1();
        d.m1();
    }

}

output:
 thread 1 starts execution of d1() method
thread 1 starts execution of d2() method
tthread 2 trying to call A's last() method

thread 1 trying to call B's last() method

after just blinking for ever

to close the command prompt by Ctl+C

In this program, if we remove at least one synchronized keyword then the program will not enter into dead lock hence Synchronized keyword is only reason for dead lock situation due to this while using synchronized keyword we have to take special care.


DeadLock Vs Starvation


Long waiting of a thread where waiting never ends is called DeadLock.
Where as long waiting of thread where waiting hence at certain point is called Starvation.
For Example,
Low priority thread has to wait until completing all high priority threads it may be long waiting but hence at certain point, which is nothing but Starvation.




Tag : Core Java
0 Komentar untuk "Java Beginners Guide: What is DeadLock with example | DeadLock Vs Starvation in Multithreading"

Featured Content

Back To Top