Question

public class SimpleDeadlock implements Runnable{

static SimpleDeadlock sc1=null;
static SimpleDeadlock sc2=null;

    void access(SimpleDeadlock sc){

        if(Thread.currentThread().getName().equals("Thread1"))
            threadMethod1(sc);
        if(Thread.currentThread().getName().equals("Thread2"))
            threadMethod2(sc);
    }

    public synchronized void threadMethod1(SimpleDeadlock sc) {

        System.out.println(Thread.currentThread().getName()+": threadMethod1");
        try{
            Thread.sleep(1000);
        }
        catch(InterruptedException ie){}
        sc.deadlock();
    }

    public synchronized void threadMethod2(SimpleDeadlock sc) {

        System.out.println(Thread.currentThread().getName()+": threadMethod2");
        try{
            Thread.sleep(1000);
        }
        catch(InterruptedException ie){}
        sc.deadlock();
    }

    synchronized void deadlock() {
        System.out.println("In deadlock...");
    }

    public void run(){
        if(Thread.currentThread().getName().equals("Thread1"))
            access(sc1);
        if(Thread.currentThread().getName().equals("Thread2"))
            access(sc2);
    }

    public static void main(String[] args) throws InterruptedException{

        sc1=new SimpleDeadlock();
        sc2=new SimpleDeadlock();
        Thread thread1=new Thread(sc1);
        Thread thread2=new Thread(sc2);
        thread1.setName("Thread1");
        thread2.setName("Thread2");
        thread1.start();
        thread2.start();
        Thread.sleep(10000);
        System.out.println(thread1.getName()+":"+thread1.getState());
        System.out.println(thread2.getName()+":"+thread2.getState());
    }
}

When I am interchanging the object in access method which is in run method this example occurs in deadlock as Thread1 waits for Thread2 to finish and vice versa. But when it is in given state it doesn't go in deadlock. WHY? When thread1 calls synchronized method threadMethod1(), the object sc1 is locked. Then how in that method the locked object sc1 calls another synchronized method.

Was it helpful?

Solution

Locks in Java are reentrant. If a thread has already acquired a lock and tries to acquire it again, there won't be any problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top