Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Ensure that a thread never gets context switched

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)?

like image 525
PHcoDer Avatar asked Jan 05 '23 22:01

PHcoDer


2 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.

http://man7.org/linux/man-pages/man7/sched.7.html

like image 70
ck1 Avatar answered Jan 12 '23 02:01

ck1


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.

like image 29
sparsh610 Avatar answered Jan 12 '23 02:01

sparsh610