0

For example, I run several endless threads with different priority. When thread swiching is taking place will thread with low priority ever be selected? Is priority absolute or it just affect on the thread selection probability.

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
Ed Akhmetshin
  • 173
  • 10
  • possible duplicate of [Java multithreading - thread priority](http://stackoverflow.com/questions/20333150/java-multithreading-thread-priority) – Chetan Kinger May 07 '15 at 15:47
  • 2
    It may or may not, depending on the implementation. It doesn’t have to have any effect at all. – Holger May 07 '15 at 15:48

1 Answers1

3

Most schedulers are based on multilevel feedback queues. These priorities are based mostly on the program's behavior. The kernel takes your assigned thread priority as more of a 'hint'.

For example, if a thread does a lot of IO, then it could be scheduled more often even if it has a lower priority than another thread because of how the MFQ operates. Threads that spend more of their schedule quantum will be moved to lower priorities in the MFQ. Threads that give up some of their quantum (i.e. for IO) will likely stay at their current priority.

If you assign thread 1 a higher priority than thread 2, and they are working on similar tasks, there is a higher probability that thread 1 will get scheduled. This doesn't mean that thread 1 must be scheduled more often than thread 2, it just hints to the kernel that you would like it to be scheduled more often than thread 2. In the end it is up to the kernel which thread gets scheduled when.

John
  • 3,769
  • 6
  • 30
  • 49
  • 1
    It should also be mentioned that the answer depends on the underlying operating system. On windows, thread priority used to be fairly strict, so a low priority thread would only run if there were no higher priority threads waiting. It may have changed in more recent versions. On linux, thread priority is much more of a hint, and only actually works if the java process has permission to change the 'nice' value (which generally means running as root). – Darren May 07 '15 at 16:15
  • 1
    @Darren: right, and even if you know the operating system, you also need to know how the actually used JVM maps Java priorities to native priorities, i.e. different Java thread priorities may map to the same OS thread priority and this might change from version to version (and there *were* changes across the different versions of Sun/Oracle’s JVM). – Holger May 08 '15 at 08:44