Java Virtual Threads and Native Code: FFM Calls, File I/O and Other Limitations
What still holds a virtual thread's carrier on current JDKs: native calls through JNI or FFM, class initialization, file I/O and long CPU-bound work (there is no time slicing). A measured one-carrier demo, the reasons, and how to offload such work to a platform pool.
kvi5hnuCode Sprout team member9 min readOn this page
Since Java 24, synchronized no longer pins (article 13). That leaves a short list of situations in which a virtual thread keeps its carrier while it waits or works. None of them is a bug. Each follows from how virtual threads are built. But you need to recognize them, because a server that does them often and for a long time loses most of the benefit of virtual threads.

Native code pins
When Java code calls a native function, through JNI (native methods) or the Foreign Function & Memory API (Linker downcalls, final since Java 22), the call stack contains native frames: machine code compiled from C, Rust or similar. The JVM can copy Java frames to the heap because it knows exactly what's in them: which slots hold references, where the return addresses point. It knows nothing about native frames. The native code may also have saved pointers into its own stack, or used OS thread-local storage. Moving it to another thread would break it.
So a virtual thread inside a native call can't unmount. If the native code blocks (waiting for a device, sleeping or doing its own I/O), the carrier blocks with it. The same applies when native code calls back into Java (an upcall) and that Java code blocks: the native frames are still underneath.
Measuring it
This program uses a single carrier again. It compares a holder that sleeps in Java, one that sleeps in the C library's usleep through an FFM downcall, and one that computes for 300 ms without blocking at all:
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class Solution {
static final long START = System.nanoTime();
static long now() { return (System.nanoTime() - START) / 1_000_000; }
// A handle to the C library's usleep(): a native call that blocks the OS thread it runs on
@SuppressWarnings("restricted")
static final MethodHandle USLEEP = Linker.nativeLinker().downcallHandle(
Linker.nativeLinker().defaultLookup().find("usleep").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT));
static void nativeSleep(int ms) {
try {
int ignored = (int) USLEEP.invokeExact(ms * 1000);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
static void javaSleep(int ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
static volatile long sink;
static void busyFor(int ms) { // pure computation, never blocks
long end = System.nanoTime() + ms * 1_000_000L;
long x = 0;
while (System.nanoTime() < end) x += x * 31 + 7;
sink = x;
}
/** One carrier. The holder runs for 300 ms; a bystander starts 50 ms later. When does it run? */
static void test(String situation, Runnable holderWork) throws InterruptedException {
long t0 = now();
Thread holder = Thread.ofVirtual().start(holderWork);
Thread.sleep(50);
long[] ranAt = new long[1];
Thread bystander = Thread.ofVirtual().start(() -> ranAt[0] = now());
bystander.join();
holder.join();
System.out.printf("%-30s bystander ran after about %d ms%n",
situation, Math.round((ranAt[0] - t0) / 50.0) * 50);
}
public static void main(String[] args) throws InterruptedException {
System.setProperty("jdk.virtualThreadScheduler.parallelism", "1"); // before any virtual thread
System.setProperty("jdk.virtualThreadScheduler.maxPoolSize", "1");
test("Thread.sleep(300)", () -> javaSleep(300));
test("native usleep for 300 ms", () -> nativeSleep(300));
test("300 ms of CPU work", () -> busyFor(300));
}
}
Output (on macOS and Linux, where the C library has usleep):
Thread.sleep(300) bystander ran after about 50 ms
native usleep for 300 ms bystander ran after about 300 ms
300 ms of CPU work bystander ran after about 300 ms
Thread.sleep unmounts, so the bystander runs on time. The native sleep pins the carrier for the full 300 ms, exactly as if the thread were a platform thread. The CPU-bound loop does the same without blocking at all, for a different reason, explained below.
Downcalls are restricted methods: the JDK prints a warning unless native access is enabled, so run such programs with java --enable-native-access=ALL-UNNAMED Solution (or name your module). The @SuppressWarnings("restricted") only silences the compiler's version of that warning.
Class initialization pins
The first use of a class runs its static initializer, and the JVM makes every other thread that touches the class wait until it finishes. That logic lives inside the JVM's own C++ code, which keeps the initializing thread mounted. So a static { } block that does I/O, such as loading configuration over the network or opening a database pool, pins its virtual thread. Threads that are waiting for the initialization to finish are pinned as well.
Article 13's experiment showed this on both Java 21 and 25. In practice it's rarely a problem because initialization happens once, but avoid slow work in static initializers anyway. Lazy, explicit initialization is easier to test and doesn't pin.
File I/O holds the carrier
Operating systems don't offer a readiness-based API for regular files like they do for sockets, so the JDK can't park a virtual thread while it waits for the disk. A file read or write runs on the carrier and holds it for the duration.
How the scheduler reacts has changed:
- Java 21–22: file operations told the scheduler they were about to block, and the scheduler compensated by temporarily adding a carrier (up to
maxPoolSize, 256 by default). - Java 23 and later (JDK-8329593): compensation was dropped for ordinary buffered file I/O, because reads and writes on local files are usually fast and the extra threads cost more than they saved. Compensation remains for operations that are known to be slow: synchronous writes (
O_SYNC/O_DSYNC), direct I/O,FileDescriptor.sync(), reading and writing a child process's streams, and DNS lookups throughInetAddress.
For typical server work, such as reading a template or writing a log line, this doesn't matter: the carrier is held for microseconds. It does matter for heavy file work on a slow or network file system. A batch job that reads thousands of large files from NFS on virtual threads will be limited to roughly one file per core at a time.
CPU-bound work: no time slicing
The third result in the demo isn't pinning at all. The loop never blocks, so it never gives up its carrier. The virtual-thread scheduler is not preemptive: it doesn't interrupt a running virtual thread after a time slice to let others run. A virtual thread keeps its carrier until it blocks or finishes.
The OS still time-slices the carriers among all the process's threads, so the JVM as a whole stays responsive. But other virtual threads waiting for that carrier don't get it. With N cores and N virtual threads each doing a long computation, every other virtual thread waits.
That's why virtual threads are for tasks that mostly wait. CPU-heavy work belongs on a pool sized to the cores, such as a ForkJoinPool, a parallel stream or a fixed thread pool, as article 10 explained.
Offloading work that holds the carrier
When a request handler on a virtual thread must call a slow native library or run a heavy computation, hand that work to a separate, bounded platform-thread pool and wait for the result. Waiting on a Future unmounts the virtual thread, so the virtual-thread carriers stay free, and the platform pool's size caps how many such calls run at once:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class ImageService implements AutoCloseable {
// Platform threads, sized for the work: CPU-bound here, so one per core
private final ExecutorService cpuPool = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors(),
Thread.ofPlatform().name("thumbnail-", 0).factory());
/** Called from a virtual thread per request. */
byte[] thumbnail(byte[] original) throws InterruptedException {
Future<byte[]> result = cpuPool.submit(() -> resize(original)); // runs on a platform thread
try {
return result.get(); // the virtual thread unmounts while it waits
} catch (ExecutionException e) {
throw new IllegalStateException("resize failed", e.getCause());
}
}
private byte[] resize(byte[] image) {
// heavy computation or a call into a native imaging library
return image.length > 1024 ? new byte[1024] : image.clone();
}
@Override public void close() { cpuPool.close(); }
}
This keeps both kinds of work healthy: thousands of request threads spend their waiting time unmounted, and the expensive work runs on exactly as many threads as the machine can handle.
Other things to keep in mind
- Thread-local caches. Code that caches expensive objects in
ThreadLocals assumes a few long-lived threads. With one virtual thread per task, each cache is used once and thrown away. Article 15 covers this. - Don't pool virtual threads. They're cheap to create. A pool of them only adds a queue and reintroduces the limits virtual threads removed. Limit resources with semaphores instead (article 12).
- Priorities and daemon status are fixed. Every virtual thread is a daemon with normal priority (article 8). Code that relies on
setPriorityfor scheduling won't get it. - Debuggers and profilers. Modern IDEs, JFR and
jcmdunderstand virtual threads. Old agents and tools that list threads throughgetAllStackTracesdon't see them (article 17).
What's current
- Native calls and class initializers are the remaining pinning causes on Java 24 and later. JFR's
jdk.VirtualThreadPinnedevent reports them with the reason, such as a native frame on the stack (article 16). - Since Java 23, ordinary file I/O no longer triggers carrier compensation. Synchronous and direct writes,
FileDescriptor.sync, process streams and DNS lookups still do. - The FFM API is final since Java 22, and its restricted methods warn at run time unless
--enable-native-accesscovers the caller. Since Java 24 (JEP 472), loading JNI libraries warns the same way. A future release plans to turn these warnings into errors. - The virtual-thread scheduler is still non-preemptive. There's no time slicing between virtual threads on the same carrier.
Common questions
Is calling a native library from a virtual thread wrong? No. Short native calls, such as hashing, compression of a small buffer or a quick system call, hold the carrier for microseconds and cost nothing noticeable. Only native calls that block or run for a long time, frequently, are worth moving to a platform pool.
Why doesn't the JDK just add a carrier for every pinned thread?
That would bring back the cost of platform threads exactly where they're used. The scheduler compensates only for a few operations known to be slow, and only up to maxPoolSize. Raising jdk.virtualThreadScheduler.maxPoolSize helps only in those cases.
Does a virtual thread doing Files.readAllBytes on a large file block other virtual threads?
It holds one carrier while the OS reads the file. Other virtual threads keep running on the remaining carriers. It becomes a problem only when many virtual threads do slow file I/O at the same time, using up most carriers.
Should CPU-heavy tasks ever run on virtual threads? Short bursts of computation in a request handler, like parsing JSON or rendering a small page, are fine. Long computations should go to a pool sized to the cores, so they can't starve the request threads.
Summary
- On current JDKs, a virtual thread keeps its carrier during native calls (JNI or FFM), class initialization, file I/O and CPU-bound computation.
- Native frames and JVM-internal class initialization can't be moved to the heap, so those cases pin.
- File I/O holds the carrier. Since Java 23 only a few slow operations, such as synchronous writes, process streams and DNS lookups, get a compensating carrier.
- The scheduler doesn't time-slice: a computing virtual thread keeps its carrier until it blocks or finishes.
- Short holds are harmless. Move long, frequent ones to a bounded platform-thread pool and wait on a
Future, which unmounts.
Practice questions
A service on 8 cores runs each request on a virtual thread. Each request makes a 500 ms blocking call into a native PDF library through JNI. What's the maximum throughput, and how would you raise it?
Answer
Each call pins a carrier for 500 ms, so with 8 carriers at most 8 calls run at once: 8 / 0.5 = 16 requests per second, and all other virtual threads in the JVM wait whenever all 8 are busy. Move the PDF calls to a dedicated platform-thread pool sized for the library (for example 32 threads if it's mostly waiting), and have the virtual threads wait on the Future. The request threads then stay unmounted, and the PDF pool's size sets the PDF throughput.
Why can a virtual thread unmount in Thread.sleep but not in the C function usleep, even though both just wait?
Answer
Thread.sleep is JDK code that knows about virtual threads: it registers a timer, freezes the Java frames to the heap and frees the carrier. usleep is native code that blocks the OS thread directly. Its frames are native, so the JVM can't move them, and it doesn't know the call is waiting.
Two virtual threads on one carrier: one runs a loop that computes for 2 seconds, the other is ready to handle a request. When does the second one run?
Answer
After the loop finishes, about 2 seconds later. Virtual threads aren't preempted: a running virtual thread keeps its carrier until it blocks or ends. With more carriers, the second thread would run on another one.
Previous: Virtual Thread Pinning in Java: synchronized, ReentrantLock and the Java 24 Fix
Next: ThreadLocal With Java Virtual Threads: Memory Costs, Inheritance and Alternatives

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.