Reputation: 4159
When I have a synchronized method in java, and if multiple threads (lets say 10 threads) tries to access this method and lets assume some thread gets access to this method and finishes the execution of the method and releases the lock then which of the remaining 9 threads get access to this method? Is there any standard mechanism through which next thread will be selected from the pool or will it be selected in FIFO order or will it randomly be selected the thread?
Upvotes: 3
Views: 125
Reputation: 19905
Thread scheduling in Java
is platform-specific. There is no guarantee in the order of thread execution in a synchronization scenario.
Having said that, the procedure is roughly as follows:
The JVM runs the thread with the highest priority. Priorities can be programmatically set, too, via the setPriority()
method of the Thread
class.
Upvotes: 8
Reputation: 8938
The next thread will be selected essentially at random, and the algorithm for selecting the next thread may be different on different machines. This is necessary for Java to gain the efficiencies of using native threads.
If you need first in, first out behavior, you may want to use something from the java.util.concurrent package, such as the Semaphore class with fairness set to true.
Upvotes: 3