How can this cause a dead end?

I am combing in my Java, this question was asked in the exercise. How can the following result lead to a dead end?

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 assumption is that if method B calls method A when it executes the Thread.sleep function, will the two methods cascade and cause an undefined dream?

Thoughts?

+6
source share
2 answers

No, this will not lead to a deadlock.

To create a dead end, you need two Thread a and b and two resources x and y . If a contains a lock on x , but also requires a lock on y , but b contains a lock on y , and also requires a lock on x , then a deadlock occurs.

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

If methodB is entered when another thread calls methodA , it will wait until methodA releases the lock before continuing. If methodA is entered and another thread calls methodB , then it will wait until methodB releases the lock before continuing. Note that the fact that methodB calls methodA does not matter, since it has the same lock on this.sync .

+9
source

Without a dead end, it is called Reentrant Synchronization , if the thread has already acquired a lock, it does not perform a lock on itself,

Imagine how you lock yourself in a room, now you are free in this room and in other rooms that are locked, and you have a key or unlocked, and it has a door from this room, other people (flows) wanting to use this the room (method) is locked, not you

+6
source

Source: https://habr.com/ru/post/977447/


All Articles