Ai Ayumi wrote:
From K&B Practice Exam 2, q16:
Answer: there is only one lock, so no deadlock can occur.
Ai Ayumi wrote:
Aren't synchronize(Stubborn.class) and static synchronized void push() locked seperately?
Ai Ayumi wrote:
If only one lock, Does that mean if t1 is using synchronize(Stubborn.class), t2 won't be able to access static synchronized void push()?
Ai Ayumi wrote:
Also, the output prints 5 4 3 2 1 (by t1), then 0 (by t2). Why is it not alternatingly by t1, t2?
Henry Wong wrote:
Ai Ayumi wrote:
Aren't synchronize(Stubborn.class) and static synchronized void push() locked seperately?
Synchronized static methods use the instance of Class class (that represents the class which the method is declared) as its lock. So, a thread that calls a synchronized static method of the Stubborn class, and a thread that locks on the Stubborn.class instance, are locking on the same object.
Henry
Amit Ramesh wrote:
At this point, two things can happen: 1) the second un-named thread in runnable state could get scheduled to run. Or 2) t1 could be potentially chosen to run if it finishes its timed sleep and wakes back up into runnable state.
But lets assume the nameless thread was chosen for now instead.
Amit Ramesh wrote:
The nameless thread starts it's run method. From within run(), it invokes push().
Push() is a static synchronized method, which means the nameless thread must obtain the Class lock for Stubborn to proceed, but t1 still has it. So the nameless thread gets stuck in Running state trying to obtain the class lock for Stubborn that t1 owns.
Amit Ramesh wrote:
Lets say, t1 has now woken up from its timed sleep of 2000 milliseconds. This is where I am unsure. I think t1 has woken up, is in runnable state, but cant transition back to Running, because the nameless thread is stuck in Running state waiting for the Stubborn.class lock to be released by t1. So wouldnt t1 be deadlocked now as well. Both threads are deadlocked. So shouldn't answers D and E be correct?
Get me the mayor's office! I need to tell her about this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
|