Last Updated on September 6, 2024 by Abhishek Sharma
Java provides a multi-threading environment where multiple threads can execute concurrently. However, thread execution is controlled by the thread scheduler, which is typically a part of the operating system. Thread priority serves as a suggestion to the scheduler, but it does not guarantee execution in a specific order or give full control over the execution timing of threads. The actual behavior depends on the underlying platform and the JVM’s thread scheduling algorithm.
Understanding Thread Priority in Java
Each thread in Java is given a priority value ranging from 1 to 10, with 1 being the lowest and 10 being the highest. A new thread inherits the priority of its parent thread by default. The thread priorities are used as a hint by the Java Virtual Machine (JVM) to determine the order in which threads should be scheduled for execution. It is important to note, however, that thread priorities do not always have the same effect across different JVM implementations and operating systems.
Setting Thread Priority in Java
Java provides the setPriority()
method in the Thread
class to set the priority of a thread. Here’s an example:
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());
thread1.setPriority(Thread.MIN_PRIORITY); // Setting lowest priority
thread2.setPriority(Thread.MAX_PRIORITY); // Setting highest priority
In this example, we create two threads, thread1
and thread2
, and assign them different priorities using the setPriority()
method. Thread.MIN_PRIORITY
represents the lowest priority, while Thread.MAX_PRIORITY
represents the highest priority.
Setter and Getter Methods of Thread Priority
Let us go over the thread priority setter and getter methods.
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.
public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method changes or assigns the thread’s priority to newPriority. If the value newPriority is outside the range of 1 (minimum) to 10 (maximum), the method throws an IllegalArgumentException.
- public static int MIN_PRIORITY
- public static int NORM_PRIORITY
- public static int MAX_PRIORITY
A thread’s default priority is 5 (NORM_PRIORITY). The MIN_PRIORITY value is 1 and the MAX_PRIORITY value is 10.
Example of Priority of a Thread in
import java.lang.*;
public class ThreadPriorityExample extends Thread {
public void run() {
System.out.println("Inside the run() method");
}
public static void main(String argvs[]) {
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
}
}
Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
When it comes to thread execution, we know that a thread with a high priority will take precedence over a thread with a lower priority. However, there may be other situations in which two threads have the same priority. The Java thread scheduler handles all of the processing for thread management. Consider the following example to see what happens if two threads have the same priority.
import java.lang.*;
public class ThreadPriorityExample1 extends Thread {
public void run() {
System.out.println("Inside the run() method");
}
public static void main(String argvs[]) {
Thread.currentThread().setPriority(7);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
ThreadPriorityExample1 th1 = new ThreadPriorityExample1();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
}
}
Output:
Priority of the main thread is : 7
Priority of the thread th1 is : 7
Explanation: If two threads have the same priority, it is impossible to predict which thread will be executed first. The execution is then determined by the thread scheduler’s algorithm (First Come, First Serve, Round-Robin, and so on).
Implementation of IllegalArgumentException in Java
We know that if the value of the method getPriority()’s parameter newPriority is not in the range (1 to 10), we get the IllegalArgumentException. Let us examine this with the help of an example.
import java.lang.*;
public class IllegalArgumentException extends Thread {
public static void main(String argvs[]) {
Thread.currentThread().setPriority(17);
System.out.println(Thread.currentThread().getPriority());
}
}
Output
Exception in thread "main" java.lang.IllegalArgumentException
at java.base/java.lang.Thread.setPriority(Thread.java:1141)
at IllegalArgumentException.main(IllegalArgumentException.java:12)
Impact of Thread Priorities
Thread priorities influence how the JVM schedules and allocates resources to threads. A higher priority thread has a better chance of being executed before lower priority threads. However, it’s important to remember that priority alone does not determine the order of thread execution. The JVM’s thread scheduler takes other factors, such as the underlying operating system and thread states, into account.
Thread priority is useful when certain threads require more processing time or have critical tasks. By giving such threads a higher priority, developers can ensure that they receive enough CPU time to complete their tasks on time. It is not, however, recommended to rely solely on thread priorities to achieve specific execution behavior.
Best Practices and Considerations for Thread Priority in Java
When working with thread priorities in Java, it’s essential to keep the following considerations in mind:
-
Thread priorities are relative: Thread priorities are relative to each other and not absolute. The relationship between priorities is what matters, rather than the specific values assigned.
-
Platform dependency: Thread scheduling behavior can vary across different JVM implementations and operating systems. Therefore, it’s crucial to avoid making assumptions about the precise behavior of thread priorities.
-
Avoid excessive priority use: Overusing thread priorities or assigning extreme values to them may lead to unexpected and non-portable behavior. It is generally advisable to use priorities sparingly and focus on designing efficient algorithms and proper thread synchronization.
-
Design robust and responsive applications: Prioritizing threads alone does not guarantee responsive and well-performing applications. It is important to design applications carefully, taking into account proper thread synchronization, efficient resource utilization, and algorithm optimization.
Conclusion
Thread priority in Java is a useful feature for guiding the thread scheduler about the relative importance of threads. However, its effectiveness is platform-dependent, and the actual behavior of thread scheduling may vary. It’s a tool that should be used judiciously, as modern systems often handle thread scheduling efficiently without the need for manual intervention through priority settings.
Frequently Asked Questions (FAQs) related to Thread Priority In Java:
Here are some of the most frequently asked questions on thread priority in Java
Q1: What is thread priority in Java?
A1: Thread priority in Java is a value assigned to a thread to suggest its relative importance to the thread scheduler. It helps determine the order in which threads are executed when multiple threads are in a runnable state.
Q2: How is thread priority set in Java?
A2: Thread priority can be set using the setPriority(int priority) method of the Thread class. The priority value must be an integer between 1 (minimum priority) and 10 (maximum priority).
Q3: What are the minimum, normal, and maximum thread priorities?
A3: Java defines three priority levels:
Thread.MIN_PRIORITY (1) – the lowest priority.
Thread.NORM_PRIORITY (5) – the default priority.
Thread.MAX_PRIORITY (10) – the highest priority.
Q4: Does setting a higher priority guarantee that the thread will execute first?
A4: No, thread priority is only a suggestion to the thread scheduler. While higher priority threads are more likely to be executed sooner, it does not guarantee execution order, as the thread scheduling is platform-dependent.
Q5: What happens if two threads have the same priority?
A5: If two threads have the same priority, the thread scheduler uses its own algorithm (usually round-robin or time-slicing) to determine the execution order. The execution of these threads may alternate or depend on the operating system.