Home » Java » How can this cause a deadlock?

How can this cause a deadlock?

Posted by: admin December 28, 2021 Leave a comment

Questions:

I’m brushing up on my Java have been asked this question in an exercise. How could the following result in a deadlock?

private Object sync = new Object();

    public void methodA() throws InterruptedException {
        synchronized(this.sync) {
            Thread.sleep(1000);
        }
    }

    public void methodB() throws InterruptedException {
        synchronized(this.sync) {
            this.methodA();
        }
    }

My guess is that if methodB calls methodA while it has the Thread.sleep function going, the two method would start cascading and cause an indefinite sleep?

Thoughts?

Answers:

No, this will not cause a deadlock.

To create deadlock, you need two Threads a and b and two resources x and y. If a holds a lock on x and also needs a lock on y, but b holds a lock on y and also needs a lock on x, then a deadlock occurs.

You only have one thing to lock here, this.sync, so no deadlock occurs.

If methodB is entered while another thread has called methodA, then it will wait until methodA releases the lock before continuing. If methodA is entered while another thread has called methodB, then it will wait until methodB releases the lock before continuing. Note that the fact that methodB calls methodA doesn’t matter, because it’s the same lock on this.sync.

###

No deadlock, it is called Reentrant Synchronization, if the thread has already acquired the lock it doesn’t get blocked by itself,

imagine as you lock yourself in a room now you are free within that room and other rooms which are locked and you have the key or unlocked and has door from that room, other people (threads) wanting to use that room (method) are blocked, not you