In this tutorial, we'll discuss how the Java thread scheduler executes threads on a priority basis. Additionally, we'll cover the types of thread priorities in Java.
2. Types of Priority
In Java, a thread's priority is an integer in the range 1 to 10. The larger the integer, the higher the priority. The thread scheduler uses this integer from each thread to determine which one should be allowed to execute. The Thread class defines three types of priorities:
- Minimum priority
- Normal priority
- Maximum priority
The Thread class defines these priority types as constants MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY, with values 1, 5, and 10, respectively. NORM_PRIORITY is the default priority for a new Thread.
3. Overview of Thread Execution
The JVM supports a scheduling algorithm called fixed-priority pre-emptive scheduling. All Java threads have a priority, and the JVM serves the one with the highest priority first.
When we create a Thread, it inherits its default priority. When multiple threads are ready to execute, the JVM selects and executes the Runnable thread that has the highest priority. If this thread stops or becomes not runnable, the lower-priority threads will execute. In case two threads have the same priority, the JVM will execute them in FIFO order.
There are two scenarios that can cause a different thread to run:
- A thread with higher priority than the current thread becomes runnable
- The current thread exits the runnable state or yields (temporarily pause and allow other threads)
In general, at any time, the highest priority thread is running. But sometimes, the thread scheduler might choose low-priority threads for execution to avoid starvation.
4. Knowing and Changing a Thread’s Priority
Java's Thread class provides methods for checking the thread’s priority and for modifying it. The getPriority() instance method returns the integer that represents its priority. The setPriority() instance method takes an integer between 1 and 10 for changing the thread's priority. If we pass a value outside the 1-10 range, the method will throw an error.
In this short article, we looked at how multiple threads are executed in Java on a priority basis using the pre-emptive scheduling algorithm. We further examined the priority range and the default thread priority. Also, we analyzed Java methods for checking a thread's priority and manipulating it if necessary.
res – REST with Spring (eBook) (everywhere)