user1614862
user1614862

Reputation: 4159

Mutli Threading in Java

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

Answers (2)

PNS
PNS

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:

  1. A preemptive scheduling algorithm is employed
  2. Each thread gets a priority number by the JVM
  3. The thread with he highest priority is selected
  4. FIFO ordering is followed among threads with identical priorities

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

Warren Dew
Warren Dew

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

Related Questions