Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java thread execution order after unlock

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!)

like image 513
heycosmo Avatar asked Jun 11 '11 18:06

heycosmo


People also ask

What is the order of thread program execution in Java?

string = "No" then, print from run method prints last. Threads run independently of each other. There is no defined order and it may very well happen what you expected.

Can we decide order of execution of threads?

You cannot tell the thread scheduler which order to execute threads in. If you need to ensure that a certain piece of code which is running on thread A must run before another piece of code running on thread B, you must enforce that order using locks or wait() / notify() .

Which thread will run first?

All Java threads have a priority, and the JVM serves the one with the highest priority first. When we create a Thread, it inherits its default priority. When multiple threads are ready to execute, the JVM selects and executes the Runnable thread that has the highest priority.


1 Answers

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.

will the remaining threads continue execution in the order that they were blocked (e.g. t2 runs, then t3, etc.)?

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.

like image 138
3 revs Avatar answered Oct 14 '22 01:10

3 revs