Java Notes
Complete guide to Thread Priority in Java — priority constants, setting priorities, how the thread scheduler uses priorities, priority inheritance, and why priorities are unreliable for correctness.
What is Thread Priority?
Thread priority is a hint to the thread scheduler about how important a thread is relative to others. Higher-priority threads are generally given more CPU time, but this behavior is platform-dependent and not guaranteed.
Priority Constants
public class PriorityConstants {
public static void main(String[] args) {
System.out.println("=== Thread Priority Constants ===\n");
System.out.println("MIN_PRIORITY: " + Thread.MIN_PRIORITY); // 1
System.out.println("NORM_PRIORITY: " + Thread.NORM_PRIORITY); // 5 (default)
System.out.println("MAX_PRIORITY: " + Thread.MAX_PRIORITY); // 10
System.out.println("\nValid range: 1 to 10");
System.out.println("Default for new threads: 5 (NORM_PRIORITY)");
// Current thread priority
Thread main = Thread.currentThread();
System.out.println("\nMain thread priority: " + main.getPriority());
}
}Output:
| MIN_PRIORITY | 1 |
| NORM_PRIORITY | 5 (default) |
| MAX_PRIORITY | 10 |
| Valid range | 1 to 10 |
| Default for new threads | 5 (NORM_PRIORITY) |
| Main thread priority | 5 |
Setting and Getting Priority
Output (may vary — priorities are hints, not guarantees!):
| High-Thread | 10 |
| Normal-Thread | 5 |
| Low-Thread | 1 |
Priority Inheritance
A new thread inherits the priority of the thread that creates it:
public class PriorityInheritance {
public static void main(String[] args) throws InterruptedException {
System.out.println("=== Priority Inheritance ===\n");
// Main thread has priority 5
System.out.println("Main priority: " + Thread.currentThread().getPriority());
// Child inherits from parent (main)
Thread child1 = new Thread(() -> {
System.out.println(" Child1 priority: " + Thread.currentThread().getPriority());
// Grandchild inherits from child1 (also 5)
Thread grandchild = new Thread(() -> {
System.out.println(" Grandchild priority: " + Thread.currentThread().getPriority());
});
grandchild.start();
try { grandchild.join(); } catch (InterruptedException e) {}
});
child1.start();
child1.join();
// Now change main priority and create another child
Thread.currentThread().setPriority(8);
System.out.println("\nMain priority changed to: " + Thread.currentThread().getPriority());
Thread child2 = new Thread(() -> {
System.out.println(" Child2 priority: " + Thread.currentThread().getPriority());
});
child2.start();
child2.join();
// Reset
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
}
}Output:
| Main priority | 5 |
| Child1 priority | 5 |
| Grandchild priority | 5 |
| Main priority changed to | 8 |
| Child2 priority | 8 |
Priority and Scheduling Behavior
Output (varies significantly by platform):
| HIGH (10) | 892,345,678 iterations ( 34.2%) |
| NORM (5) | 878,123,456 iterations ( 33.7%) |
| LOW (1) | 836,789,012 iterations ( 32.1%) |
Invalid Priority Values
public class InvalidPriority {
public static void main(String[] args) {
System.out.println("=== Invalid Priority Handling ===\n");
Thread t = new Thread(() -> {});
// Valid priorities: 1 to 10
try {
t.setPriority(0); // Below MIN_PRIORITY
} catch (IllegalArgumentException e) {
System.out.println("Priority 0: " + e.getMessage());
}
try {
t.setPriority(11); // Above MAX_PRIORITY
} catch (IllegalArgumentException e) {
System.out.println("Priority 11: " + e.getMessage());
}
try {
t.setPriority(-1);
} catch (IllegalArgumentException e) {
System.out.println("Priority -1: " + e.getMessage());
}
// Valid
t.setPriority(7);
System.out.println("\nPriority 7: ✓ (valid)");
System.out.println("Current priority: " + t.getPriority());
}
}Output:
| Priority 0 | illegal priority value: 0 |
| Priority 11 | illegal priority value: 11 |
| Priority -1 | illegal priority value: -1 |
| Priority 7 | ✓ (valid) |
| Current priority | 7 |
Why Thread Priority is Unreliable
public class PriorityUnreliable {
public static void main(String[] args) {
System.out.println("=== Why Priorities Are Unreliable ===\n");
System.out.println("1. PLATFORM DEPENDENT");
System.out.println(" • Windows: Maps 10 Java priorities to 7 OS levels");
System.out.println(" • Linux: Often ignores priorities for regular threads");
System.out.println(" • macOS: Limited priority differentiation");
System.out.println("\n2. MANY CORES = LESS EFFECT");
System.out.println(" • If you have 8 cores and 3 threads,");
System.out.println(" all 3 can run simultaneously regardless of priority");
System.out.println("\n3. NO GUARANTEE OF ORDER");
System.out.println(" • High priority doesn't mean 'runs first'");
System.out.println(" • Just means 'gets more CPU time (probably)'");
System.out.println("\n4. STARVATION RISK");
System.out.println(" • Low-priority threads may never run");
System.out.println(" • Most schedulers prevent this with 'aging'");
System.out.println("\n═══════════════════════════════════════════");
System.out.println("RULE: Never depend on priority for correctness!");
System.out.println("Use synchronization, not priority, for ordering.");
System.out.println("═══════════════════════════════════════════");
}
}=== Why Priorities Are Unreliable === 1. PLATFORM DEPENDENT Windows: maps 10 Java levels to 7 OS levels Linux: may ignore priorities entirely 2. Run 1: High finished first Run 2: Low finished first Run 3: High finished first Conclusion: Never rely on priority for correctness!
Best Practices
- Don't rely on priority for correctness — use synchronization
- Use priorities only for performance hints — e.g., background tasks at MIN_PRIORITY
- Avoid MAX_PRIORITY for user threads — can starve other threads
- Set priority before start() — setting after has less predictable effect
- Test on target platform — behavior varies across OS
Interview Questions
Q1: What is the default priority of a thread?
Answer: 5 (Thread.NORM_PRIORITY). New threads inherit the priority of the thread that creates them.
Q2: What is the range of thread priorities?
Answer: 1 to 10. MIN_PRIORITY = 1, NORM_PRIORITY = 5, MAX_PRIORITY = 10. Setting a value outside this range throws IllegalArgumentException.
Q3: Does a higher priority thread always execute before a lower priority thread?
Answer: No! Priority is just a hint to the scheduler. On multi-core systems, all threads may run simultaneously. Even on single-core, the scheduler may not strictly follow priorities. Never rely on priority for program correctness.
Q4: What happens if you set priority to 0 or 11?
Answer: IllegalArgumentException is thrown. The valid range is strictly 1-10.
Q5: How does priority inheritance work?
Answer: A child thread inherits the priority of the parent thread that created it. If main has priority 5 and creates a thread, that thread starts with priority 5. You can change it with setPriority() after creation.
Q6: Can thread priority cause starvation?
Answer: Yes, theoretically. If high-priority threads always compete for CPU, low-priority threads might rarely execute. However, most modern OS schedulers use "aging" — they gradually increase the priority of starved threads to prevent indefinite starvation.
Q8: Is thread priority guaranteed to affect execution order?
A: No! Thread priority is only a HINT to the OS scheduler. The actual behavior is platform-dependent. Some OS may ignore priorities entirely, some map Java's 10 levels to fewer OS levels. Never rely on priority for program correctness — use proper synchronization and coordination instead.
Q9: What is thread starvation and how is it related to priority?
A: Starvation occurs when a thread is never scheduled because higher-priority threads always get CPU time. With preemptive scheduling, a low-priority thread may never run if high-priority threads are always ready. Solutions: avoid extreme priority differences, use fair locks (ReentrantLock(true)), or redesign to avoid depending on scheduling.
Q10: What are MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY values?
A: Thread.MIN_PRIORITY = 1, Thread.NORM_PRIORITY = 5 (default), Thread.MAX_PRIORITY = 10. Setting priority outside 1-10 range throws IllegalArgumentException. New threads inherit their parent's priority by default.
Q11: How does the JVM map Java thread priorities to OS priorities?
A: It's platform-specific. Windows maps Java's 10 levels to 7 OS priority levels (some Java levels map to the same OS level). Linux with standard scheduling may ignore priorities entirely. Solaris has a 1-to-1 mapping. This is why priority behavior varies across platforms.
Q12: Should you use thread priorities in production code?
A: Generally no. Priority behavior is unreliable and platform-dependent. For controlling execution order, use proper concurrency tools: CountDownLatch, CyclicBarrier, Semaphore, PriorityBlockingQueue, or ExecutorService. These provide deterministic behavior regardless of OS scheduler.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Thread Priority in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, multithreading, thread, priority
Related Java Master Course Topics