Reputation: 19665
Threads A, B, C in that order, reach synchronized method f() in a single object.
All have the same priority.
B and C are blocked.
A leaves f().
What thread now begins running in f()? Is it always B on the principle of FIFO? Or is the order undetermined?
If C has a higher priority than B, does that guarantee that C will run rather than B?
Upvotes: 5
Views: 844
Reputation: 67760
To the best of my knowledge, that's undefined.
Good thing, too. If you're writing coding that depends on priorities to determine order of execution, you're doing it wrong. You either control this stuff explicitly and intentionally, or be prepared for whatever happens. Best is to write code that will work regardless.
Priorities are a hint to the runtime scheduler, not a hard and fast directive. It's possible and legal for your priorities to be ignored altogether, or threads to be scheduled in an order having nothing to do with priorities. The best you can hope for is that, on average, your higher-priority threads get more CPU time than lesser-priority threads, other circumstances like IO waits permitting.
Upvotes: 5
Reputation: 54025
It's unspecified/platform dependent. However, Java semaphores can be fair - what guarantees FIFO.
Upvotes: 0
Reputation: 84179
For all application intents and purposes you can assume the order is totally random. Don't play with priorities - you can easily introduce subtle priority inversion bugs that are very very very hard to catch.
Upvotes: 10
Reputation: 14505
When all the runnable threads in the system have the same priority, the scheduler chooses the next thread to run in a simple, non-preemptive, round-robin scheduling order.
This also depends upon OS and number of CPU's. Multiple threads can be in execution if there are multiple CPU's and OS supports same.
Interesting old link :
http://journals.ecs.soton.ac.uk/java/tutorial/java/threads/priority.html
Upvotes: 0
Reputation: 4950
It depends on what algorithm the scheduler of your OS use. Look at this for more information about the scheduler behavior.
But you can allways do some tricks to simulate a desire order.
Upvotes: 0
Reputation: 98489
The order is undefined. Having a higher priority does not guarantee first resumption. The higher priority means a thread gets more CPU time while running, but an implementation is not required to give it the lock first.
Incidentally, there is no way to write deterministic code that guarantees the A-B-C lock-entry ordering you describe. It cannot be done with the Java methods. If you write code that you think produces that ordering reliably, you haven't tested it enough. Since you cannot know in what order the threads will enter the lock, you also cannot know the order in which they'll leave it - even if there were a FIFO policy.
Upvotes: 3