Java Virtual Threads, Interrupts and Daemon Threads: Thread Properties Explained
Everything about Java thread properties: virtual threads and carrier threads (Java 21), cooperative cancellation with interrupt, handling InterruptedException correctly, daemon threads, names and IDs, uncaught exception handlers, priorities, and thread builders and factories.
kvi5hnuCode Sprout team member12 min readOn this page
Beyond starting and joining, every thread has properties that control how it behaves. Is it a platform thread or a lightweight virtual thread? Has someone asked it to stop? Does it keep the JVM alive? What happens when it throws? This article covers each property, with special attention to the two that matter most in modern code: virtual threads, the headline feature of Java 21, and interruption, the only correct way to cancel a thread.
Virtual threads
By default, a Java thread is a platform thread, a thin wrapper around an operating-system thread. The OS schedules these well, but they are expensive. Starting one costs thousands of CPU instructions, each reserves a stack of around a megabyte, and a machine can sustain only a few thousand before memory and scheduling overhead hurt.
That's a problem for servers. A web application wants to handle a huge number of concurrent requests, and each request spends most of its time waiting: for a database query, a downstream HTTP call, a file read. With one platform thread per request, you run out of threads long before you run out of CPU.
The traditional fix was non-blocking, callback-based APIs:
service.request(parameters, response -> process(response)); // returns immediately
That scales, but it costs readability. Loops, branches, try/catch and stack traces all get scattered across callbacks or reactive operator chains.
Virtual threads (Java 21) offer the same scalability with plain blocking code. A virtual thread is a Thread that the JVM schedules onto a small pool of platform threads called carrier threads. When a virtual thread performs a blocking operation, the JVM unmounts it: its stack is saved on the heap, and the carrier is free to run another virtual thread. When the operation completes, the virtual thread is remounted on any free carrier and continues. The name is an analogy with virtual memory: lots of virtual threads mapped onto fewer real ones.

By default there is one carrier per CPU core. You can tune this with -Djdk.virtualThreadScheduler.parallelism=N, but you rarely need to. Virtual threads cost a few hundred bytes to start with and are cheap to create, so millions of them are practical. The demo starts 10,000 that each sleep for 50 ms, and they finish in roughly 50 ms of wall-clock time rather than 500 seconds.
Thread t = Thread.startVirtualThread(task);
Thread v = Thread.ofVirtual().name("handler-", 0).start(task);
t.isVirtual(); // true
In practice you'll mostly use an executor that creates one virtual thread per task, Executors.newVirtualThreadPerTaskExecutor() (article 95).
Virtual threads are always daemon threads, always have normal priority, and belong to a special thread group. setPriority on a virtual thread is silently ignored, and setDaemon(false) throws IllegalArgumentException.
Interrupting threads
A thread terminates when its run method returns, either by finishing or because of an uncaught exception. Java has no way to force another thread to stop. stop() was unsafe and now throws. Instead there is interruption, a polite request.
Calling t.interrupt() sets the target thread's interrupted status, a boolean flag that every thread has. What happens next depends on what the target is doing.
If it's running, nothing happens automatically. The thread must check the flag now and then:
while (!Thread.currentThread().isInterrupted() && moreWorkToDo) {
do more work
}
If it's blocked in an interruptible call such as sleep, wait, join, BlockingQueue.take, Lock.lockInterruptibly or Future.get, that call ends early by throwing InterruptedException, and the flag is cleared. If the flag is already set when such a method is called, it throws immediately without blocking. Some blocking I/O on platform threads isn't interruptible. Classic java.io socket reads are the main example, though virtual threads do make socket I/O interruptible.
Interruption means "please pay attention". The interrupted thread decides how to react. Some threads handle it and keep going, but most treat it as a request to finish up and exit. The idiomatic shape for a task is:
Runnable r = () -> {
try {
while (more work to do) {
do more work
Thread.sleep(delay); // throws if interrupted
}
} catch (InterruptedException e) {
// interrupted while sleeping or waiting: fall through and exit
} finally {
cleanup, if required
}
// returning from run terminates the thread
};
If the loop calls sleep (or another interruptible method) on every iteration, there's no need to check isInterrupted(), since the exception covers both cases.
interrupted() versus isInterrupted()
The two names are confusingly similar:
Thread.interrupted()is a static method. It tests the current thread and clears its flag.t.isInterrupted()is an instance method. It tests any thread and leaves the flag alone.
The demo shows isInterrupted returning true, then interrupted() returning true and resetting the flag, then interrupted() returning false.
Never swallow InterruptedException
A very common bug is catching InterruptedException deep in a helper and doing nothing:
void mySubTask() {
try { sleep(delay); }
catch (InterruptedException e) { } // BAD: the stop request vanishes
}
The exception has cleared the flag, so the interrupt is lost. Code higher up keeps running, and the thread can no longer be cancelled. There are two correct options:
-
Propagate it. Declare
throws InterruptedExceptionand let the caller, ultimatelyrun, deal with it. This is the best option when you can. -
Restore the flag if you can't change the signature, for example inside a
Runnableor an overridden method:javacatch (InterruptedException e) { Thread.currentThread().interrupt(); // re-assert so callers can see it }
The demo runs both helper styles in an interrupted thread. Only the restoring helper lets the caller see that a stop was requested.
Daemon threads
t.setDaemon(true); // must be called before start()
A daemon thread exists only to serve other threads. Examples are a timer thread sending ticks, or a cleaner removing stale cache entries. The rule is simple: when only daemon threads remain, the JVM exits. There's no point in keeping a program alive just for its helpers.
Daemon threads are killed abruptly at exit, so their finally blocks may never run. Never give a daemon thread work that must complete, such as writing a file or committing a transaction. All virtual threads are daemons, and calling setDaemon(false) on one throws IllegalArgumentException. A thread inherits daemon status from the thread that created it. Calling setDaemon after start throws IllegalThreadStateException.
Names and IDs
Threads get default names like Thread-2. Give them meaningful ones with setName, the constructor, or a builder. Good names make thread dumps and log lines (%t in many log formats) far easier to read:
var t = new Thread(runnable, "web-crawler");
long id = t.threadId(); // Java 19: unique positive id
Use threadId(). The older getId() is deprecated because it isn't final, so a subclass could override it and return something that isn't the real ID.
Uncaught exception handlers
run can't throw checked exceptions, but an unchecked exception can escape it and kill the thread. There is no caller to catch it, so the exception goes to an uncaught exception handler, an implementation of the functional interface Thread.UncaughtExceptionHandler:
void uncaughtException(Thread t, Throwable e)
You can install a handler on one thread with setUncaughtExceptionHandler, or on every thread at once with the static Thread.setDefaultUncaughtExceptionHandler. A typical handler logs the failure, reports it to monitoring, or both. If a thread has no handler of its own, the JVM tries, in order:
- the thread's thread group, which delegates to its parent group if there is one (rare in practice);
- the default handler, if one is installed;
- otherwise, it prints
Exception in thread "name"plus the stack trace toSystem.err. That is the familiar crash output you've seen many times.
Thread groups, the mechanism behind step 1, are a Java 1.0 feature for managing threads together. Executors and structured concurrency do that job better, so don't build on thread groups.
Priorities
Platform threads have a priority from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10), with NORM_PRIORITY (5) as the default, inherited from the creating thread. The OS scheduler may prefer higher-priority threads. Java priorities are mapped onto whatever levels the OS has: Windows has seven, so some Java values collapse together, and OpenJDK on Linux ignores priorities entirely by default.
Priorities made sense in early JVMs that scheduled threads themselves. Today, don't use them. Code that depends on priorities for correctness is broken, and code that uses them for performance usually gets nothing. Virtual threads ignore them altogether.
Thread factories and builders
When you need many threads with the same configuration, use a ThreadFactory, an interface with one method, Thread newThread(Runnable r). Executors accept factories, so you can control the names, daemon status and handlers of pool threads. Since Java 21, builders make factories trivial:
Thread.Builder builder = Thread.ofVirtual().name("request-", 1)
.uncaughtExceptionHandler(handler);
Thread t = builder.unstarted(task); // configured, not started
builder.start(task); // configured and started
ThreadFactory factory = builder.factory(); // for executors
ThreadFactory workers = Thread.ofPlatform().name("worker-", 1).daemon(true).factory();
name(prefix, start) numbers the threads automatically: worker-1, worker-2 and so on. Platform builders also offer stackSize, group and priority, which are rarely useful.
A complete example
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
public static void main(String[] args) throws Exception {
// 1. ten thousand virtual threads that each block for a moment
var done = new AtomicInteger();
var threads = new ArrayList<Thread>();
for (int i = 0; i < 10_000; i++)
threads.add(Thread.startVirtualThread(() -> {
try {
Thread.sleep(Duration.ofMillis(50)); // unmounts from its carrier while sleeping
done.incrementAndGet();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
for (Thread t : threads) t.join();
Thread v = threads.get(0);
System.out.println("virtual threads finished: " + done.get() + ", isVirtual " + v.isVirtual()
+ ", isDaemon " + v.isDaemon() + ", priority " + v.getPriority());
// 2. interrupting a busy loop: check the flag
Thread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) Thread.onSpinWait(); // "work"
System.out.println("busy worker saw the interrupt and stopped (flag still set: "
+ Thread.currentThread().isInterrupted() + ")");
}, "busy");
worker.start();
Thread.sleep(20);
worker.interrupt();
worker.join();
// 3. interrupting a sleeping thread: InterruptedException, flag cleared
Thread sleeper = new Thread(() -> {
try {
while (true) Thread.sleep(Duration.ofSeconds(10));
} catch (InterruptedException e) {
System.out.println("sleeper got InterruptedException; flag now " + Thread.currentThread().isInterrupted());
} finally {
System.out.println("sleeper cleans up in finally");
}
}, "sleeper");
sleeper.start();
while (sleeper.getState() != Thread.State.TIMED_WAITING) Thread.sleep(1);
sleeper.interrupt();
sleeper.join();
// 4. interrupted() clears the flag, isInterrupted() doesn't
Thread.currentThread().interrupt();
System.out.println("isInterrupted " + Thread.currentThread().isInterrupted()
+ ", interrupted " + Thread.interrupted() + ", then interrupted again " + Thread.interrupted());
// 5. already interrupted? sleep throws at once
Thread.currentThread().interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("sleep with the flag already set throws immediately");
}
// 6. swallowing versus restoring the interrupt in a helper method
System.out.println("swallowing helper: caller sees interrupt? " + runHelper(Solution::swallowingPause));
System.out.println("restoring helper: caller sees interrupt? " + runHelper(Solution::restoringPause));
// 7. daemon threads
Thread daemon = new Thread(() -> {
try { Thread.sleep(Duration.ofMinutes(1)); } catch (InterruptedException e) { /* done */ }
}, "housekeeper");
daemon.setDaemon(true);
System.out.println("housekeeper daemon? " + daemon.isDaemon() + ", main daemon? " + Thread.currentThread().isDaemon());
daemon.start();
try {
daemon.setDaemon(false);
} catch (IllegalThreadStateException e) {
System.out.println("setDaemon after start: IllegalThreadStateException");
}
daemon.interrupt();
daemon.join();
// 8. names, ids, priorities
var crawler = new Thread(() -> { });
String defaultName = crawler.getName();
crawler.setName("web-crawler");
System.out.println("default name starts with Thread-: " + defaultName.startsWith("Thread-")
+ ", renamed " + crawler.getName() + ", id positive " + (crawler.threadId() > 0)
+ ", priority " + crawler.getPriority() + " (range " + Thread.MIN_PRIORITY + ".." + Thread.MAX_PRIORITY + ")");
// 9. uncaught exception handlers: per thread, and a default for all threads
Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.out.println("default handler: " + t.getName() + " threw " + e));
Thread a = new Thread(() -> { throw new IllegalArgumentException("bad input"); }, "parser");
a.start(); a.join();
Thread b = new Thread(() -> { throw new ArithmeticException("divide by zero"); }, "calculator");
b.setUncaughtExceptionHandler((t, e) -> System.out.println("own handler: " + t.getName() + " -> " + e.getMessage()));
b.start(); b.join();
Thread.setDefaultUncaughtExceptionHandler(null);
// 10. builders and factories
ThreadFactory factory = Thread.ofPlatform().name("pool-worker-", 1).daemon(true).factory();
var names = new ArrayList<String>();
for (int i = 0; i < 3; i++) {
Thread t = factory.newThread(() -> { });
names.add(t.getName() + (t.isDaemon() ? " (daemon)" : ""));
}
System.out.println("factory threads " + names);
Thread.Builder vb = Thread.ofVirtual().name("request-", 100)
.uncaughtExceptionHandler((t, e) -> System.out.println("virtual " + t.getName() + " failed: " + e.getMessage()));
Thread r = vb.start(() -> { throw new IllegalStateException("timeout"); });
r.join();
}
static boolean runHelper(Runnable helper) throws InterruptedException {
var sawInterrupt = new boolean[1];
Thread t = new Thread(() -> {
Thread.currentThread().interrupt(); // pretend someone asked us to stop
helper.run();
sawInterrupt[0] = Thread.currentThread().isInterrupted();
});
t.start();
t.join();
return sawInterrupt[0];
}
static void swallowingPause() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// BAD: the interrupt request is lost
}
}
static void restoringPause() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // GOOD: let the caller know
}
}
}
virtual threads finished: 10000, isVirtual true, isDaemon true, priority 5
busy worker saw the interrupt and stopped (flag still set: true)
sleeper got InterruptedException; flag now false
sleeper cleans up in finally
isInterrupted true, interrupted true, then interrupted again false
sleep with the flag already set throws immediately
swallowing helper: caller sees interrupt? false
restoring helper: caller sees interrupt? true
housekeeper daemon? true, main daemon? false
setDaemon after start: IllegalThreadStateException
default name starts with Thread-: true, renamed web-crawler, id positive true, priority 5 (range 1..10)
default handler: parser threw java.lang.IllegalArgumentException: bad input
own handler: calculator -> divide by zero
factory threads [pool-worker-1 (daemon), pool-worker-2 (daemon), pool-worker-3 (daemon)]
virtual request-100 failed: timeout
Look at the third and fourth lines. When sleep throws InterruptedException, the flag has already been cleared. Further down, the "swallowing" helper loses the interrupt, and the "restoring" one preserves it.
Common questions
Should I replace my thread pools with virtual threads?
For tasks that spend most of their time waiting on I/O, such as request handling, database calls or HTTP calls, yes: use Executors.newVirtualThreadPerTaskExecutor(). For CPU-bound work, keep a fixed pool sized to the number of cores. Don't pool virtual threads.
Is synchronized still a problem with virtual threads?
On Java 21 to 23, blocking inside synchronized pins the virtual thread to its carrier. Since Java 24 (JEP 491), virtual threads unmount in synchronized too, so on Java 25 this is no longer a concern in most code. A few cases, such as blocking in native code, still pin.
What should I do in a catch (InterruptedException e) block?
Either let the exception propagate by declaring throws InterruptedException, or restore the flag with Thread.currentThread().interrupt() and finish the task. Never ignore it, because the interrupt request is then lost.
Why didn't my daemon thread's finally block run?
When only daemon threads remain, the JVM exits immediately and doesn't unwind their stacks. Work that must finish, such as writing files, belongs in non-daemon threads, or in an executor that you shut down and wait for.
How do I limit concurrency with virtual threads?
Use a Semaphore with the desired number of permits, and acquire a permit around the limited operation. That limits the resource, such as a database or remote service, rather than the number of threads.
API reference
java.lang.Thread
| Method | Description |
|---|---|
boolean isVirtual() (Java 21) | true for a virtual thread |
static Thread startVirtualThread(Runnable task) (Java 21) | creates and starts a virtual thread |
void interrupt() | sets the interrupted status; a blocked interruptible call throws InterruptedException |
static boolean interrupted() | tests the current thread's status and clears it |
boolean isInterrupted() | tests a thread's status without changing it |
static Thread currentThread() | the executing thread |
void setDaemon(boolean on), boolean isDaemon() | daemon status; set before start |
void setName(String), String getName() | the thread's name |
long threadId() (Java 19) | unique ID (prefer to the deprecated getId) |
void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h), getUncaughtExceptionHandler() | per-thread handler |
static void setDefaultUncaughtExceptionHandler(...), static getDefaultUncaughtExceptionHandler() | default handler for all threads |
void setPriority(int p); MIN_PRIORITY = 1, NORM_PRIORITY = 5, MAX_PRIORITY = 10 | scheduling hint (not recommended) |
static Thread.Builder.OfPlatform ofPlatform(), static Thread.Builder.OfVirtual ofVirtual() (Java 21) | thread builders |
java.lang.Thread.Builder (Java 21)
| Method | Description |
|---|---|
name(String name), name(String prefix, long start) | fixed name, or prefix plus counter |
uncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) | handler for built threads |
Thread unstarted(Runnable task), Thread start(Runnable task) | build one thread, unstarted or started |
ThreadFactory factory() | a factory using this configuration |
OfPlatform.daemon(), daemon(boolean), stackSize(long), group(ThreadGroup), priority(int) | platform-only options |
java.util.concurrent.ThreadFactory and Thread.UncaughtExceptionHandler
| Method | Description |
|---|---|
Thread newThread(Runnable r) | creates a thread that will run r |
void uncaughtException(Thread t, Throwable e) | called when t dies from e |
Summary
- Virtual threads are cheap, JVM-scheduled threads that unmount from their carrier while blocked. Use them, one per task, for large numbers of I/O-bound tasks, and don't pool them.
interrupt()requests cancellation. Running code checksisInterrupted(), and blocking calls throwInterruptedExceptionand clear the flag.- Never swallow
InterruptedException. Propagate it, or restore the flag withThread.currentThread().interrupt(). - Daemon threads don't keep the JVM alive. Set the flag before
start. Virtual threads are always daemons. - Name your threads. Use
threadId(), install uncaught exception handlers for logging, and skip priorities and thread groups. - Builders (
Thread.ofPlatform(),Thread.ofVirtual()) configure threads and produceThreadFactorys.
Practice Questions
Your service makes 5,000 concurrent blocking HTTP calls. Platform threads or virtual threads, and why?
Virtual threads. Each call spends most of its time blocked. A virtual thread releases its carrier while blocked, so thousands of calls need only a handful of OS threads, instead of 5,000 expensive platform threads.
A loop calls Thread.sleep(100) each iteration and also checks isInterrupted(). Is the check needed?
No. If an interrupt arrives during sleep, an InterruptedException is thrown. If it arrives between sleeps, the next sleep throws immediately. Catching the exception around the loop handles both.
What is wrong with catch (InterruptedException e) { } in a utility method, and what are the two fixes?
It discards the cancellation request, because the flag was cleared when the exception was thrown. Either declare throws InterruptedException, or call Thread.currentThread().interrupt() in the catch block to restore the flag.
What's the difference between Thread.interrupted() and Thread.currentThread().isInterrupted()?
Both test the current thread, but interrupted() also clears the flag, while isInterrupted() leaves it unchanged.
Your program's main method returns, but the JVM keeps running. What could be keeping it alive?
At least one non-daemon thread is still running, such as an executor's worker thread that was never shut down. Mark helper threads as daemons, or shut down executors and join the threads.
Previous: Java Thread States: New, Runnable, Blocked, Waiting and Terminated
Next: Java Callable, Future and ExecutorService: Thread Pools and Task Results
Related reading
- Java Thread States: New, Runnable, Blocked, Waiting and Terminated
- Java Threads: Creating and Running Threads with Runnable and Thread
- Java Object Construction: Overloading, Default Fields, this(), and Initialization Blocks
- Java Block Scope and if/else Statements
- The Java String API, Code Points, StringBuilder and Text Blocks

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.