Java Thread Priority
Java thread priority is a number from 1 to 10 that tells the thread scheduler how important a thread is. A higher number suggests that the thread should get CPU time before threads with a lower number.
Priorities let you mark background work (cleanup, logging, reports) as less important than user-facing work (handling requests, payments). This lesson shows how to read and set priorities, how they are inherited and limited, and why you must never rely on them for correctness.
Java Thread Priority Constants
The Thread class defines three constants for the priority range. Every new thread starts with the priority of the thread that created it, which for code started from main is NORM_PRIORITY.
| Constant | Value | Meaning |
|---|---|---|
Thread.MIN_PRIORITY | 1 | Lowest priority |
Thread.NORM_PRIORITY | 5 | Default priority |
Thread.MAX_PRIORITY | 10 | Highest priority |
public class PriorityBasics {
public static void main(String[] args) {
System.out.println("MIN_PRIORITY = " + Thread.MIN_PRIORITY);
System.out.println("NORM_PRIORITY = " + Thread.NORM_PRIORITY);
System.out.println("MAX_PRIORITY = " + Thread.MAX_PRIORITY);
Thread mainThread = Thread.currentThread();
System.out.println("main priority = " + mainThread.getPriority());
Thread worker = new Thread(() -> { }, "worker");
System.out.println("worker priority (default) = " + worker.getPriority());
}
}
Output:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
main priority = 5
worker priority (default) = 5
How it works:
getPriority()returns a thread's current priority as anint.- The
mainthread runs at priority 5, andworkeris created bymain, so it also starts at 5.
How to Set Thread Priority in Java
Call setPriority(int) to change a thread's priority. You can call it before or after start(), but setting it before starting is the usual practice.
thread.setPriority(int newPriority) // 1 (MIN) to 10 (MAX)
int priority = thread.getPriority();
public class SetPriority {
public static void main(String[] args) throws InterruptedException {
Thread emailSender = new Thread(() ->
System.out.println(Thread.currentThread().getName()
+ " running with priority " + Thread.currentThread().getPriority()),
"email-sender");
Thread paymentHandler = new Thread(() ->
System.out.println(Thread.currentThread().getName()
+ " running with priority " + Thread.currentThread().getPriority()),
"payment-handler");
emailSender.setPriority(Thread.MIN_PRIORITY); // 1: background work
paymentHandler.setPriority(Thread.MAX_PRIORITY); // 10: important work
emailSender.start();
emailSender.join();
paymentHandler.start();
paymentHandler.join();
}
}
Output:
email-sender running with priority 1
payment-handler running with priority 10
How it works:
- The email sender is background work, so it gets
MIN_PRIORITY. - The payment handler is important, so it gets
MAX_PRIORITY. - Inside
run(),Thread.currentThread().getPriority()reads the priority of the running thread. Named threads like these are explained in Java Thread Class.
Invalid Priority Values
Any value outside 1 to 10 is rejected with an IllegalArgumentException.
public class InvalidPriority {
public static void main(String[] args) {
Thread worker = new Thread(() -> { }, "worker");
int[] attempts = {0, 7, 11};
for (int priority : attempts) {
try {
worker.setPriority(priority);
System.out.println("setPriority(" + priority + ") OK -> " + worker.getPriority());
} catch (IllegalArgumentException e) {
System.out.println("setPriority(" + priority + ") failed: " + e.getClass().getSimpleName());
}
}
}
}
Output:
setPriority(0) failed: IllegalArgumentException
setPriority(7) OK -> 7
setPriority(11) failed: IllegalArgumentException
How it works:
0and11are outside the allowed range, sosetPriority()throws and the priority stays unchanged.7is valid and is stored. Any value from 1 to 10 is allowed, not just the three constants.
Thread Priority Is Inherited
A new thread copies the priority of the thread that creates it. This matters when a high- or low-priority thread starts helper threads.
public class InheritPriority {
public static void main(String[] args) throws InterruptedException {
Thread parent = new Thread(() -> {
Thread self = Thread.currentThread();
System.out.println("parent priority: " + self.getPriority());
// A thread created inside "parent" copies parent's priority
Thread child = new Thread(() -> { }, "child");
System.out.println("child priority : " + child.getPriority());
child.setPriority(Thread.NORM_PRIORITY); // can still be changed
System.out.println("child after set: " + child.getPriority());
}, "parent");
parent.setPriority(8);
parent.start();
parent.join();
}
}
Output:
parent priority: 8
child priority : 8
child after set: 5
How it works:
parentruns at priority 8. Thechildthread is created insideparent'srun()method, so it starts at 8 too.- The child's priority can still be changed with
setPriority()before it starts.
Thread Group Maximum Priority
Every platform thread belongs to a ThreadGroup. A group can set a maximum priority; a thread in that group can never go above it, even if you ask for more.
public class GroupLimit {
public static void main(String[] args) {
ThreadGroup batchJobs = new ThreadGroup("batch-jobs");
batchJobs.setMaxPriority(4); // no thread in this group may go above 4
Thread importer = new Thread(batchJobs, () -> { }, "importer");
importer.setPriority(Thread.MAX_PRIORITY); // asks for 10...
System.out.println("group max priority : " + batchJobs.getMaxPriority());
System.out.println("importer priority : " + importer.getPriority()); // ...gets 4
}
}
Output:
group max priority : 4
importer priority : 4
How it works:
setMaxPriority(4)caps every thread inbatch-jobsat 4.importer.setPriority(10)does not throw; Java silently uses the smaller value, 4.
Note: Thread groups are a legacy feature and are rarely used in new code. They are shown here because the cap explains why
setPriority()sometimes seems to "not work".
Java Thread Priority Is Only a Hint
Priorities are passed to the operating system as a hint. How much they matter depends on the OS, the JVM settings and how many CPU cores are free. On Linux, the JVM ignores Java priorities by default; on Windows they are mapped to OS priorities but still give no guarantee.
import java.util.concurrent.atomic.AtomicBoolean;
public class PriorityRace {
public static void main(String[] args) throws InterruptedException {
AtomicBoolean running = new AtomicBoolean(true);
long[] counts = new long[2];
Thread low = new Thread(() -> {
while (running.get()) counts[0]++;
}, "low");
Thread high = new Thread(() -> {
while (running.get()) counts[1]++;
}, "high");
low.setPriority(Thread.MIN_PRIORITY);
high.setPriority(Thread.MAX_PRIORITY);
low.start();
high.start();
Thread.sleep(1000); // let both threads count for one second
running.set(false);
low.join();
high.join();
System.out.println("CPU cores available: " + Runtime.getRuntime().availableProcessors());
System.out.printf("low (priority 1) counted %,d%n", counts[0]);
System.out.printf("high (priority 10) counted %,d%n", counts[1]);
}
}
Output of two runs on the same 2-core Linux machine (your numbers will differ):
CPU cores available: 2
low (priority 1) counted 390,533,135
high (priority 10) counted 739,973,897
CPU cores available: 2
low (priority 1) counted 1,204,851,716
high (priority 10) counted 1,189,102,012
How it works:
- Both threads count as fast as they can for one second. If priorities were strict,
highwould always count far more thanlow. - In the first run
highhappened to count more; in the second runlowwon. The difference comes from scheduling noise, not from the priorities. - With at least as many cores as busy threads, each thread gets its own core anyway, so priorities make little difference.
Note: Never use priorities to make a program correct, for example to make sure one thread runs before another. Use Java Thread Join, locks, or other coordination tools for that. Priorities can only influence performance, and only on some systems.
| Statement | True? |
|---|---|
| A higher-priority thread runs first | Not guaranteed |
| A low-priority thread may never run (starvation) | Possible on some systems |
| Priorities behave the same on every OS | No |
| Priority affects which thread gets a lock | No |
setPriority() above the group maximum throws | No, the value is lowered silently |
Thread Priority with Virtual Threads and Thread Builders
Virtual threads (Java 21) always have priority NORM_PRIORITY, and setPriority() has no effect on them. Platform threads created with the Thread.ofPlatform() builder can set their priority directly.
public class VirtualPriority {
public static void main(String[] args) throws InterruptedException {
Thread virtual = Thread.ofVirtual().name("virtual-worker").unstarted(() -> { });
virtual.setPriority(Thread.MAX_PRIORITY); // ignored for virtual threads
Thread platform = Thread.ofPlatform().name("platform-worker")
.priority(Thread.MAX_PRIORITY) // builders can set priority too
.unstarted(() -> { });
System.out.println("virtual priority: " + virtual.getPriority());
System.out.println("platform priority: " + platform.getPriority());
}
}
Output:
virtual priority: 5
platform priority: 10
How it works:
Thread.ofVirtual()creates a virtual thread. CallingsetPriority(MAX_PRIORITY)is silently ignored, so it stays at 5.Thread.ofPlatform().priority(...)sets the priority while building the thread, before it is started. The builder methods are an alternative tonew Thread(...), as shown in Create a Thread in Java.
Real-World Example: Thread Pools with Different Priorities
In a shop backend, checkout requests should be favoured over maintenance jobs like rebuilding a search index. Thread pools create their own threads, so you give them a ThreadFactory that sets the priority on every new thread.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class PriorityThreadFactoryDemo {
// Creates named platform threads that all share one priority
static ThreadFactory factory(String poolName, int priority) {
AtomicInteger counter = new AtomicInteger(1);
return task -> {
Thread t = new Thread(task, poolName + "-" + counter.getAndIncrement());
t.setPriority(priority);
t.setDaemon(true); // background pools should not keep the JVM alive
return t;
};
}
static String describe(String job) {
Thread t = Thread.currentThread();
return String.format("%-20s on %-13s priority %d", job, t.getName(), t.getPriority());
}
public static void main(String[] args) throws Exception {
ExecutorService checkoutPool =
Executors.newFixedThreadPool(2, factory("checkout", Thread.MAX_PRIORITY - 2));
ExecutorService maintenancePool =
Executors.newFixedThreadPool(1, factory("maintenance", Thread.MIN_PRIORITY));
List<Future<String>> results = new ArrayList<>();
results.add(checkoutPool.submit(() -> describe("place order #501")));
results.add(checkoutPool.submit(() -> describe("place order #502")));
results.add(maintenancePool.submit(() -> describe("rebuild search index")));
results.add(maintenancePool.submit(() -> describe("compress old logs")));
for (Future<String> result : results) {
System.out.println(result.get());
}
checkoutPool.shutdown();
maintenancePool.shutdown();
}
}
Output:
place order #501 on checkout-1 priority 8
place order #502 on checkout-2 priority 8
rebuild search index on maintenance-1 priority 1
compress old logs on maintenance-1 priority 1
How it works:
- A reusable factory.
factory(poolName, priority)returns aThreadFactorylambda. For each new thread it sets a readable name (checkout-1,checkout-2, ...), the priority, and daemon mode. - Two pools.
checkoutPooluses priority 8 for customer-facing work;maintenancePoolusesMIN_PRIORITYfor background jobs. Both are created withExecutors.newFixedThreadPool(size, factory). - Submitting work. Each task returns a description of the thread it ran on.
Future.get()waits for each result in order. - What the output proves. Checkout tasks run on
checkout-*threads with priority 8; maintenance tasks share the singlemaintenance-1thread with priority 1. - Realistic expectations. On a busy Windows server, the OS may give the checkout threads more CPU time. On Linux, the priorities are ignored by default, so the real protection is the separate pools: maintenance work can never use more than one thread. Thread pools are covered in detail in the Executor Service and Thread Pools lessons.