Thread Priority and the Thread Scheduler in Java
Thread priority in Java is an integer from 1 to 10 that defines how a thread should be treated relative to other threads: the higher the number, the more willing the scheduler should be to give it the CPU. The bounds have constants — Thread.MIN_PRIORITY (1), Thread.NORM_PRIORITY (5) and Thread.MAX_PRIORITY (10). You set a priority with setPriority() and read it with getPriority(). It is only a hint to the operating system’s scheduler, so program logic must never depend on it.
A thread dump shows just how much of a hint it is. Call setPriority(Thread.MAX_PRIORITY), run the program on Linux and take a dump with jstack: the thread’s line reads prio=10 os_prio=0. The JVM remembered priority 10, but the operating system got a plain 0 — by default, HotSpot on Linux doesn’t pass Java thread priorities to the OS at all (details in The Thread Scheduler).
MIN_PRIORITY, NORM_PRIORITY, MAX_PRIORITY Constants
The java.lang.Thread class declares three priority constants: MIN_PRIORITY = 1, NORM_PRIORITY = 5 and MAX_PRIORITY = 10. Any value in between is allowed too, but in code it’s better to use the constants or expressions built from them — that way it’s obvious the number is a priority.
| Constant | Value | When it’s used |
|---|---|---|
Thread.MIN_PRIORITY | 1 | Background work that shouldn’t get in the way of everything else: cache cleanup, collecting statistics |
Thread.NORM_PRIORITY | 5 | Priority of the main thread, and therefore of almost every thread in an application; the only priority virtual threads ever have |
Thread.MAX_PRIORITY | 10 | Threads that need a fast response; rare in application code |
Strictly speaking, a Java thread has no “default priority”: a new thread gets the priority of the thread that created it. Since main runs at 5, almost every thread starts at 5 as well — hence the common statement “the default thread priority is 5”.
setPriority() and getPriority(): Setting and Reading a Priority
A priority is set with public final void setPriority(int newPriority) and read with public final int getPriority(). A value outside the 1–10 range throws IllegalArgumentException, while a value above the thread group’s maximum is silently cut down to ThreadGroup.getMaxPriority().
You can change the priority both before start() and on a thread that is already running. The simplest option is to set it before starting, so the thread runs with the right value from its very first instruction. The example also shows inheritance: the child thread is created after main has raised its own priority to 8.
public class PriorityInheritance {
public static void main(String[] args) {
Thread main = Thread.currentThread();
System.out.println(main.getName() + ": " + main.getPriority());
main.setPriority(8);
Thread child = new Thread(() -> { });
System.out.println("child: " + child.getPriority());
Thread background = new Thread(() -> { });
background.setPriority(Thread.MIN_PRIORITY);
System.out.println("background: " + background.getPriority());
}
} main: 5
child: 8
background: 1 Thread Group Limit: ThreadGroup.getMaxPriority()
Every platform thread belongs to a ThreadGroup, and the group has a priority ceiling. Ask for more, and setPriority() won’t throw — it quietly sets the group’s maximum instead:
ThreadGroup limited = new ThreadGroup("limited");
limited.setMaxPriority(4);
Thread t = new Thread(limited, () -> { });
t.setPriority(Thread.MAX_PRIORITY);
System.out.println(t.getPriority()); // Output: 4 Here t already got 4 when it was created: the inherited priority is capped by the group ceiling too. Thread groups are rarely used in modern code (most of their API has been deprecated since Java 19), but interviewers like to ask about setPriority() in exactly this form: “why did getPriority() return less after setPriority(10)?”
IllegalArgumentException Outside 1–10
Zero, negative numbers and anything above 10 are rejected immediately:
Thread t = new Thread(() -> { });
t.setPriority(11); Exception in thread "main" java.lang.IllegalArgumentException
at java.base/java.lang.Thread.setPriority(Thread.java:...)
at Main.main(Main.java:3) The exception has no message. In real code, a typical cause is arithmetic like getPriority() + 1 on a thread that is already at MAX_PRIORITY. The safe version is Math.min(t.getPriority() + 1, Thread.MAX_PRIORITY).
Since Java 21 you can also set the priority through the platform thread builder: Thread.ofPlatform().priority(Thread.MIN_PRIORITY).start(task). Same rules apply — anything outside 1–10 throws IllegalArgumentException.
The Thread Scheduler: Who Actually Picks the Thread
The thread scheduler decides which thread should run at any given moment and which one should be paused. For regular (platform) threads in HotSpot, that’s the operating system’s scheduler, not the JVM: every Java thread is an OS thread, and the JVM merely passes its priority on to the OS — and not always.
It wasn’t always this way. Early JVMs (Java 1.1 on Solaris) used “green threads”: the virtual machine switched them itself, and Java priorities really did control the choice. That’s where the old textbook line “the scheduler is part of the JVM” comes from. Once Java moved to native threads, the decision went to the OS, and what happens to a priority depends on the platform:
| Platform | What HotSpot does with the priority | What it means in practice |
|---|---|---|
| Linux | By default (-XX:ThreadPriorityPolicy=0) doesn’t pass it to the OS: all threads get the normal priority | setPriority() changes only the number returned by getPriority(). ThreadPriorityPolicy=1 requires root; without it, the JVM warns that priority changes will be ignored |
| Windows | Maps the 10 Java levels onto 5 Windows thread priority levels (from THREAD_PRIORITY_LOWEST to THREAD_PRIORITY_HIGHEST) | Priorities work, but neighboring values (say, 5 and 6) are the same to the OS |
| Virtual threads (Java 21+) | Scheduled by the JVM itself (ForkJoinPool), priority is ignored | Always NORM_PRIORITY — see the last section |
To check whether a priority reached the OS, take a thread dump (jstack <pid> or jcmd <pid> Thread.print). Each thread line has two numbers: prio is the Java priority, os_prio is what the operating system received:
"worker" #22 prio=10 os_prio=0 cpu=... tid=... nid=... runnable // Linux, default settings
"worker" #22 prio=10 os_prio=2 cpu=... tid=... nid=... runnable // Windows: THREAD_PRIORITY_HIGHEST How to read the remaining fields of a dump and the thread states in it is covered in Thread States in Java.
Don’t rely on priorities
Do NOT rely on thread priorities when designing multithreaded applications. The scheduler will most likely use priorities when choosing the next thread to run, but that is NOT guaranteed — and on Linux with default HotSpot settings it doesn’t even see them. If your code works correctly only with a particular ratio of priorities, it will break on another OS.
Context Switching in Java: What Happens and When
A context switch is the moment a CPU core stops running one thread and starts running another: the state of the first thread (registers, program counter, stack pointer) is saved, and the state of the second is loaded. This is exactly where a thread’s priority is used — to decide which thread to switch to next.
Steps of a Context Switch (Simplified Model)
Textbooks usually describe a switch like this:
- Saving the context of the thread that has finished running.
- Placing that thread at the end of the queue for its priority.
- Loading the context of a thread from the highest-priority ready queue.
- Removing the loaded thread from the queue and starting it.
It’s a handy model, but it doesn’t describe any particular OS, let alone a Java guarantee. Steps 1 and 4 happen everywhere; “a queue per priority” does not. Linux, for example, keeps no separate per-priority queues for regular threads: it hands out CPU time in proportion to a thread’s weight (its nice value), so a low-weight thread still gets time regularly, just less of it. And there are usually several cores, each with its own run queue.
When a Switch Happens
- The time slice allocated by the scheduler has run out.
- The thread gave up the CPU voluntarily: it explicitly yielded (
Thread.yield()), paused (sleep(),wait(),join()) or blocked waiting for I/O or a monitor. - The thread was preempted by another, higher-priority thread — if the OS honors priorities.
- The thread finished.
Switching isn’t free. Besides saving registers, the new thread starts with a “cold” CPU cache. That’s why hundreds of threads constantly waking each other up can be slower than a handful of threads doing the same work — and one reason tasks are handed to fixed-size thread pools.
Example: Two Threads with Different Priorities
Two threads increment their own counters for one second: one with MIN_PRIORITY, the other with MAX_PRIORITY. It’s tempting to expect the second counter to be much larger. On most machines the numbers come out close, and that’s the correct behavior, not a bug in the example.
public class PriorityDemo {
static volatile boolean running = true;
static class Counter implements Runnable {
long count;
@Override
public void run() {
while (running) {
count++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Counter low = new Counter();
Counter high = new Counter();
Thread lowThread = new Thread(low, "low");
Thread highThread = new Thread(high, "high");
lowThread.setPriority(Thread.MIN_PRIORITY);
highThread.setPriority(Thread.MAX_PRIORITY);
lowThread.start();
highThread.start();
Thread.sleep(1000);
running = false;
lowThread.join();
highThread.join();
System.out.println("low (1): " + low.count);
System.out.println("high (10): " + high.count);
}
} The program prints two lines with numbers in the hundreds of millions; the exact values depend on the CPU and change from run to run. What matters is how they compare:
| Where you run it | What you’ll see | Why |
|---|---|---|
| Linux, default JVM settings | Counters roughly equal | Priorities aren’t passed to the OS (os_prio=0 for both) |
| Any OS, more than two free cores | Counters roughly equal | The threads don’t compete: each runs on its own core, so the scheduler has nothing to choose |
| Windows, cores busy (more counting threads than cores) | Threads with MAX_PRIORITY pull clearly ahead of threads with MIN_PRIORITY | There is competition for the CPU, and the OS honors the priority |
This is the key takeaway about priorities: they matter only when there are more ready threads than cores, and only if the OS honors them. A priority can’t speed up a thread that nobody is getting in the way of. The count field is read in main after join(), so the values are visible correctly; the running flag is declared volatile, otherwise the loop might never see it change (volatile guarantees that a write made by one thread becomes visible to other threads).
What Java Guarantees and What It Doesn’t
The Java specification promises almost nothing about the order and speed of thread execution: neither priority nor the order of start() calls determines which thread runs first. Only the order of actions within a single thread is guaranteed, plus whatever synchronization tools give you.
- When it comes to threads, very little is guaranteed.
- Java does NOT guarantee that threads will run in the order they were started.
- There is no guarantee that once a thread starts, it will finish its work without interruption.
- The result may differ every time you run the program.
- There is no guarantee that a started thread will get the CPU quickly and run to completion: under starvation it can wait a long time for its turn, and daemon threads are cut off when the last non-daemon thread ends or
System.exit()is called. - Within one thread, actions run in a predictable order — from that thread’s own point of view. Without synchronization, another thread may see the results of those actions in a different order, or not see them at all.
If order matters, you set it explicitly: join(), synchronized, wait()/notify() or classes from java.util.concurrent. Priorities are not on that list.
Methods That Affect the Scheduler
From Java code you can influence the scheduler through a few methods of Thread and Object: some take the current thread off the CPU, some give a hint, and some wake up waiting threads. Each is covered in its own lesson — this is just an overview.
| Method | Class | What it does from the scheduler’s point of view | More details |
|---|---|---|---|
static void sleep(long millis) | Thread | Takes the current thread out of scheduling for the given time | Thread.sleep() |
static void yield() | Thread | Hints that the current thread is willing to give up the CPU; the hint may be ignored | Thread.yield() |
final void join() | Thread | The current thread waits for another one to finish and doesn’t compete for the CPU until then | Thread.join() |
final void setPriority(int newPriority) | Thread | Hints at the relative importance of the thread | This lesson, section above |
final void wait() | Object | Releases the monitor and takes the thread out of scheduling until notify() | Inter-thread communication through a shared monitor |
final void notify(), notifyAll() | Object | Makes one or all threads waiting on this object eligible to run again | Inter-thread communication through a shared monitor |
Priorities, Starvation and Priority Inversion
If the OS strictly honors priorities and the CPU is busy, a low-priority thread may go without CPU time for a long while — that’s starvation. This is why high priorities for “important” threads sometimes break a program instead of speeding it up: a background thread that is supposed to free resources can no longer keep up.
Operating systems fight this. Linux, under the normal scheduling policy, gives time to every thread in proportion to its weight, and Windows periodically gives a temporary priority boost to threads that haven’t had the CPU for a while. But these are OS mechanisms, not Java ones. How starvation differs from deadlock and livelock, and how to fix it, is in the table in Deadlock vs Livelock vs Starvation.
There’s also the opposite effect — priority inversion. A thread with MIN_PRIORITY holds a synchronized monitor, and a thread with MAX_PRIORITY wants to enter the same block. The high-priority thread sits in the BLOCKED state, waiting for the low-priority one — which gets the CPU least often of all — to leave the block. The monitor doesn’t pass priority along, so here a high priority works against you.
When Priorities Are Actually Worth Setting
Application code rarely uses priorities. The one sensible case is lowering the priority of a background thread (MIN_PRIORITY) so that on a loaded machine it yields to the main work. Raising a priority for speed is pointless: if cores are free there’s no effect, and if they’re busy you raise the risk of starving everything else.
Keep thread pools in mind. Executors.defaultThreadFactory(), which Executors.newFixedThreadPool() and similar methods use by default, creates threads with NORM_PRIORITY and clears the daemon flag, no matter what priority the thread that created the pool has. If you need a different priority, pass your own factory:
ThreadFactory lowPriority = runnable -> {
Thread t = new Thread(runnable, "background-worker");
t.setPriority(Thread.MIN_PRIORITY);
t.setDaemon(true);
return t;
};
ExecutorService background = Executors.newFixedThreadPool(2, lowPriority); A task submitted to this pool runs in a thread with priority 1. Don’t set the priority inside the task itself via Thread.currentThread().setPriority(): pool threads are reused, and the changed priority will carry over to the next tasks.
Virtual Thread Priority (Java 21)
Virtual threads (Java 21+) always have NORM_PRIORITY: getPriority() returns 5, and setPriority() ignores the new value. Virtual threads aren’t scheduled by the OS but by the JVM itself — a built-in scheduler based on ForkJoinPool — and it doesn’t take priorities into account.
Thread vt = Thread.ofVirtual().unstarted(() -> { });
vt.setPriority(Thread.MAX_PRIORITY);
System.out.println(vt.isVirtual() + " " + vt.getPriority()); // Output: true 5
vt.setPriority(11); // IllegalArgumentException - the range is checked here too Look at the last line: the value is ignored, but the 1–10 range check runs first, so setPriority(11) still throws IllegalArgumentException. The Thread.ofVirtual() builder has no priority() method at all — only Thread.ofPlatform() does.
Virtual threads run on a small number of platform carrier threads. You can’t raise the carriers’ priority either: the JVM manages them. If some tasks need a guaranteed share of the CPU, give them a separate, bounded pool of platform threads rather than relying on priorities.
Frequently Asked Questions
Can you change the priority of a thread that is already running?
Yes. setPriority() can be called at any time, including from the thread itself via Thread.currentThread().setPriority(). The JVM passes the new value to the OS right away (if it passes priorities on that platform at all), and it takes effect at the scheduler’s next decision. Calling it on a terminated thread doesn’t throw, but has no effect.
Will a MAX_PRIORITY thread run first if its start() is called after a MIN_PRIORITY thread?
Not necessarily. On a multi-core CPU both threads will most likely start almost simultaneously on different cores, and the order of their first actions is undefined. Priority doesn’t set the start order and doesn’t replace join() or other synchronization — see What Java Guarantees.
How do you set the priority of ExecutorService threads?
With your own ThreadFactory passed to Executors.newFixedThreadPool(n, factory) or to the ThreadPoolExecutor constructor. The default factory always sets NORM_PRIORITY, so the priority of the thread that created the pool is not inherited. A factory example is in When Priorities Are Actually Worth Setting.
What priority do the main thread and JVM service threads have?
main has 5 (NORM_PRIORITY). HotSpot service threads visible in a jstack dump get their own values: “Reference Handler” — 10, “Signal Dispatcher” — 9, “Finalizer” — 8. That’s how the JVM hints to the OS that these threads matter more than application threads, but on Linux with default settings they too are just numbers in the prio field.
Comments