Let’s say I have 2 threads, t1 and t2, and a lock object, m. Thread t1 is in an infinite loop, where at each iteration, it grabs a lock on m, does some work, unlocks m and starts over immediately. During one iteration, t2 requests a lock on m but gets blocked by t1 and has to wait. Now, when t1 unlocks m, is it guaranteed that t2 will obtain the next lock on m? or can t1 sneak ahead of it at the next iteration?
Generally, is there a queue set up for waiting threads? If t1 has the lock, and all remaining threads also wanting that lock get blocked in the following order: t2, t3, …, will the remaining threads continue execution in the order that they were blocked (e.g. t2 runs, then t3, etc.)?
(I briefly perused the java spec and couldn’t find the answer. If it’s in there, please let me know, and I will go back to read more carefully.)
Thanks! (First SO post, woohoo!)
Yes, there is a queue and it can be fair or not. Fair queues are more expensive and non-fair are faster (who wins the CAS wins the lock).
check java.util.concurrent.locks.AbstractQueuedSynchronizer for further info.
The main issue is that they are executed concurrently/simultaneously, you can’t truly define order for 2 events that are executed in the same time. But w/ fair (unrecommended due to extra costs) locks any thread that manages to enlist itself for the lock will get eventually get to own it.