Among around 150 threads on say 20 core machine. I want that a particular thread never gets context switched. I am not sure that setting Thread priority to MAX_PRIORITY will do this or not? Also if we set priority to max is it necessary that OS will follow the instruction(assuming I run in sudo mode)?
-
The operating system does not play a key role when it comes to threading basics in Java – mjn Jun 11 '16 at 16:17
4 Answers
You can't disable thread context switching altogether, but by setting the thread priority to MAX_PRIORITY
you're telling the OS thread scheduler (if it supports a priority scheduling policy) to preempt a lower priority thread, if a higher priority one is ready to run.
References
java.lang.Thread Javadoc
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority.
https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html
Linux kernel thread scheduler APIs man page
On priority:
Conceptually, the scheduler maintains a list of runnable threads for each possible sched_priority value. In order to determine which thread runs next, the scheduler looks for the nonempty list with the highest static priority and selects the thread at the head of this list.
On preemption:
All scheduling is preemptive: if a thread with a higher static priority becomes ready to run, the currently running thread will be preempted and returned to the wait list for its static priority level.

- 5,243
- 1
- 21
- 25
-
The OS threading specification is not relevant - the Java virtual machine specification is. – mjn Jun 11 '16 at 16:10
Thread priority to MAX_PRIORITY will do this or not ?
it depends upon your operating system. Although you set it but there is no guaranty that scheduler will work like that.

- 1,552
- 3
- 27
- 66
It is not possible to enforce this in general.
For example, the virtual machine could choose every other of the 150 threads and run them before your favorite thread.
My favorite Kathy Sierra quote:
In JAVA, when it comes to threads, very little is guaranteed
http://albertomorales.eu/in-java-when-it-comes-to-threads-very-little-is-guaranteed/

- 36,362
- 28
- 176
- 378
You should set the thread priority to MAX_PRIORITY. This will make sure that your desired thread gets to run whenever you want it to run. This is essentially like it is never context switched. This should resolve your issue.

- 546
- 3
- 10