Reputation: 690
Suppose There are 3 threads t1, t2, t3
I have this pieace of code(Condition con = lock.newCondition();
):
lock.lock();
if (Thread.currentThread().getName().equals("t1"))
con.await();
if (Thread.currentThread().getName().equals("t2"))
con.signal();
lock.unlock();
t1 runs this code first then t2 and t3 are suspended in the lock.lock();
.
After t1 executes con.await();
t2 enters and executes con.signal();
.
My question is who will enter the critical section after the signal?
Will it be t1 that is suspended because of the await() or t3 that is suspended in the lock.lock();
?
Oracles documentation states:
If any threads are waiting on this condition then one is selected for waking up. That thread must then re-acquire the lock before returning from await.
From the last sentence does it mean that after t1 is awake it competes with t3 on the lock?
If so is it guaranteed who among t1, t3 will enter?
Suppose I haven`t passed true (means fair lock) in lock's constructor.
Upvotes: 1
Views: 105
Reputation: 120978
Yes, you are correct - if the is no fairness there will be absolutely no guarantee which Thread will be chosen - t1
of t3
; and they will indeed compete for the resources.
And btw that is the case not only here, it is generally the case for thread scheduling - be it synchronized block, CAS, spin-locks etc. Fairness is really expensive and rarely used (at least I had no case for it so far).
Upvotes: 1