Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deadlock situation

Tags:

java

I have some trouble understanding the concept of deadlock situation in this program. I am getting the output as : Entered amethod Entered bmethod and then the deadlock situation occurs. Now since my amethod is a synchronized method, shouldn't it execute first completely i.e. by calling bsum method and then start the new thread. ? Please explain...

public class Deadlock 
{
    public static void main(String[] args) 
    {

        A a= new A();
        B b= new B();
        new MainClass1(a,b);
        new MainClass2(a,b);
    }

}
class MainClass1 extends Thread
{
    A a;
    B b;
    MainClass1(A a,B b)
    {
        super();
        this.a=a;
        this.b=b;
        start();
    }
    public void run()
    {
        a.amethod(b);
    }
}
class MainClass2 extends Thread
{
    A a;
    B b;
    MainClass2(A a,B b)
    {
        super();
        this.a=a;
        this.b=b;
        start();
    }
    public void run()
    {
        b.bmethod(a);
    }

}
class A
{
    public synchronized void amethod(B b)
    {
        System.out.println("Entered amethod");
        try{
            Thread.sleep(500);
        }catch(Exception e){}
        b.bsum(2,3);
    }
    public synchronized void asum(int a,int b)
    {
        System.out.println("Sum in A is");
        System.out.println(a+b);
    }
}
class B
{
    public synchronized void bmethod(A a)
    {
        System.out.println("Entered bmethod");
        try{
            Thread.sleep(500);
        }catch(Exception e){}
        a.asum(3, 5);
    }
    public synchronized void bsum(int a, int b)
    {
        System.out.println("Sum in B is");
        System.out.println(a+b);
    }
}
like image 283
KD Singh Avatar asked Apr 19 '26 17:04

KD Singh


1 Answers

It seems that you are using the objects a and b in the other object's method. When the method that is called is synchronized no one can use the resources it uses, thus both methods want something that is locked => deadlock. You should synchronize with a common object for both methods, preferable one outside of both.

like image 162
Kokozaurus Avatar answered Apr 22 '26 05:04

Kokozaurus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!