
Senior Java Performance & Concurrency Engineer ·
35+ Intl. Talks ·
Team WorkshopsUpdated on 2026-10-21
The “Free Threads” Hype
With all the hype surrounding virtual threads, you have probably heard of them by now and are maybe already using them. Many people treat them as the final chapter in Java concurrency: just replace your thread pool with Executors.newVirtualThreadPerTaskExecutor() and stop worrying. Virtual threads are so cheap they are basically free!
Sadly, there is no such thing as a free lunch. With virtual threads, that price can show up as extra Garbage Collection (GC) pressure, unexpected OutOfMemoryError crashes, and worse CPU cache locality.
When not to use virtual threads
Throughout blogs, talks, and things like that, you will see the same warning:
Virtual threads are designed for tasks that spend most of their time waiting on I/O, not for CPU-bound tasks or parallel compute.
In software development, warning labels are often repeated as dogma without explaining what actually breaks under the hood. Why shouldn't you use virtual threads for recursive tasks? Where does the memory go if thousands of virtual threads block with deep call stacks? What happens to your CPU caches when virtual threads constantly pause and resume?
I wanted to put this to the test by using virtual threads in completely the wrong way. To be completely clear: if you are building normal web services, making HTTP requests, and waiting on SQL queries, virtual threads are fantastic. In 99.9% of everyday applications, your call stacks are shallow, your threads spend most of their life waiting on a network call, and you will never hit the edge cases we are about to explore. Yet let’s see how they work, and how it can be broken.
The Scheduler: LIFO vs. FIFO
Virtual threads do not run directly on the CPU. Instead, the JVM schedules them onto a pool of real OS threads called carrier threads. That scheduler is actually a ForkJoinPool, the same pool used by parallel streams except with one difference in how it pulls tasks from its queue.
A standard ForkJoinPool is built for divide-and-conquer compute tasks and uses LIFO (Last-In, First-Out) queues for its worker threads. When a task splits into two subtasks using invokeAll(left, right):
- The worker pushes
right onto the top of its local stack. - It runs
left immediately on the same thread without queuing it. - Once
left finishes, it pops the newest task (right) off the top of its local stack.
Because each worker always finishes the newest subtask first, it naturally walks a recursive tree depth-first.
Virtual threads use a ForkJoinPool configured in FIFO (First-In, First-Out) mode (asyncMode = true). For a web server, FIFO makes total sense: you want requests handled in the order they arrive so no request starves.
However, if you spawn child virtual threads recursively and call join(), something very different happens:
- Both child virtual threads are placed at the back of the FIFO queue.
- When the parent calls
join(), it does not run the child task inline. Instead, the parent virtual thread parks (unmounts) and waits in memory for the children to finish. - Because tasks are pulled in FIFO order, the scheduler walks the tree breadth-first (level by level), leaving every parent thread parked in memory along the way.
Let's see this in action with in the following example. Both tests traverse a binary tree on a single worker thread and count how many tasks are active at the same time:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| public class SchedulerComparison {
static int maxDepth = 3;
static final AtomicInteger activeFjp = new AtomicInteger(0);
static final AtomicInteger peakFjp = new AtomicInteger(0);
static final AtomicInteger activeVt = new AtomicInteger(0);
static final AtomicInteger peakVt = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
if (args.length > 0) {
maxDepth = Integer.parseInt(args[0]);
}
// Pin to 1 carrier thread so the queue order is deterministic
System.setProperty("jdk.virtualThreadScheduler.parallelism", "1");
System.setProperty("jdk.virtualThreadScheduler.maxPoolSize", "1");
System.out.println("=== 1. ForkJoinPool (LIFO / Depth-First, depth = " + maxDepth + ") ===");
try (ExecutorService fjp = new ForkJoinPool(1)) {
fjp.submit(() -> runTask(fjp, 0, "Root", activeFjp, peakFjp)).get();
}
System.out.println("Peak active ForkJoin tasks: " + peakFjp.get());
System.out.println("\n=== 2. Virtual Threads (FIFO / Breadth-First, depth = " + maxDepth + ") ===");
try (ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor()) {
vt.submit(() -> runTask(vt, 0, "Root", activeVt, peakVt)).get();
}
System.out.println("Peak active Virtual Threads: " + peakVt.get());
}
static void runTask(ExecutorService executor, int depth, String path,
AtomicInteger activeCounter, AtomicInteger peakCounter) {
int active = activeCounter.incrementAndGet();
peakCounter.updateAndGet(peak -> Math.max(peak, active));
try {
if (maxDepth <= 3) {
System.out.printf("[%s] Depth %d (Active: %d)%n", path, depth, active);
}
if (depth >= maxDepth) return;
executor.invokeAll(List.of(
Executors.callable(() -> runTask(executor, depth + 1, path + "->L", activeCounter, peakCounter)),
Executors.callable(() -> runTask(executor, depth + 1, path + "->R", activeCounter, peakCounter))
));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
activeCounter.decrementAndGet();
}
}
}
|
Running this at depth 3 shows the exact order in which the tasks run:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| === 1. ForkJoinPool (LIFO / Depth-First, depth = 3) ===
[Root] Depth 0 (Active: 1)
[Root->L] Depth 1 (Active: 2)
[Root->L->L] Depth 2 (Active: 3)
[Root->L->L->L] Depth 3 (Active: 4)
[Root->L->L->R] Depth 3 (Active: 4)
[Root->L->R] Depth 2 (Active: 3)
[Root->L->R->L] Depth 3 (Active: 4)
[Root->L->R->R] Depth 3 (Active: 4)
[Root->R] Depth 1 (Active: 2)
...
Peak active ForkJoin tasks: 4
=== 2. Virtual Threads (FIFO / Breadth-First, depth = 3) ===
[Root] Depth 0 (Active: 1)
[Root->L] Depth 1 (Active: 2)
[Root->R] Depth 1 (Active: 3)
[Root->L->L] Depth 2 (Active: 4)
[Root->L->R] Depth 2 (Active: 5)
[Root->R->L] Depth 2 (Active: 6)
[Root->R->R] Depth 2 (Active: 7)
[Root->L->L->L] Depth 3 (Active: 8)
...
Peak active Virtual Threads: 8
|
Notice how ForkJoinPool dives straight down the left branch (Root -> L -> L -> L) and never has more than 4 active tasks in memory. Virtual threads, on the other hand, run all of Depth 1, then all of Depth 2, and then Depth 3 and parking every parent thread along the way.
If we bump the depth to 12 (8,191 total tasks in the tree):
1
2
3
4
5
| === 1. ForkJoinPool (LIFO / Depth-First, depth = 12) ===
Peak active ForkJoin tasks: 13
=== 2. Virtual Threads (FIFO / Breadth-First, depth = 12) ===
Peak active Virtual Threads: 4096
|
ForkJoinPool still only needs 13 active tasks (depth + 1). Virtual threads end up with 4,096 threads alive at the exact same time (all 4,095 parent threads across levels 0 to 11 parked on join(), plus the running leaf thread).
So where do these threads actually sleep? Or more precisely, where do the stacks of parked virtual threads go? And what if the stacks are deep?
When stacks go to sleep
To understand why deep stacks matter for virtual threads, we have to look at where thread stacks live in memory.
A Platform Thread is a 1:1 operating system thread. The OS gives it a dedicated call stack in native memory outside the Java heap (usually 1 MB). When a platform thread blocks (for example, on Thread.sleep()), the OS pauses the thread and its stack stays right where it is in native memory. The heap is not really affected by this ordeal.
A Virtual Thread only borrows a carrier platform thread while it is actively running. While running, its stack frames sit on the carrier thread's allocated native memory. When the virtual thread blocks, it has to unmount so the carrier thread is free to run other virtual threads.
To unmount a virtual thread, the stack gets frozen: the JVM copies the stack frames off the carrier thread into an internal object on the Java Heap as a StackChunk. When the virtual thread wakes up, the JVM thaws (copies) those frames back onto a carrier thread.
When your call stack is only a few methods deep, each StackChunk is tiny. But what happens when 10,000 virtual threads block at a recursion depth of 500 frames, holding 10 long variables (80 bytes) in each frame?
Let's see what happens with the following example!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
| public class DeepStackMemory {
static final int THREAD_COUNT = 10_000;
static final int DEPTH = 500;
static volatile long sink;
public static void main(String[] args) throws Exception {
System.out.println("=== Platform Threads ===");
measureParkedStacks(Executors.newCachedThreadPool(), false);
System.out.println("\n=== Virtual Threads ===");
measureParkedStacks(Executors.newVirtualThreadPerTaskExecutor(), true);
}
static void measureParkedStacks(ExecutorService executor, boolean printHistogram) throws Exception {
System.gc();
Thread.sleep(200);
long heapBefore = usedHeapMb();
CountDownLatch allParked = new CountDownLatch(THREAD_COUNT);
CountDownLatch release = new CountDownLatch(1);
try (executor) {
for (int i = 0; i < THREAD_COUNT; i++) {
executor.submit(() -> {
try {
sink = dive(0, allParked, release,
System.nanoTime(), 2, 3, 4, 5, 6, 7, 8, 9, 10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
// Wait until all 10,000 threads are parked at depth 500
allParked.await();
Thread.sleep(200);
System.gc();
Thread.sleep(200);
long heapWhileParked = usedHeapMb();
System.out.printf("Heap before : %d MB%n", heapBefore);
System.out.printf("Heap while parked : %d MB (+%d MB)%n",
heapWhileParked, heapWhileParked - heapBefore);
if (printHistogram) {
printTopHeapObjects();
}
release.countDown();
}
}
static long dive(int depth, CountDownLatch allParked, CountDownLatch release,
long p1, long p2, long p3, long p4, long p5,
long p6, long p7, long p8, long p9, long p10) throws InterruptedException {
long childResult;
if (depth < DEPTH) {
childResult = dive(depth + 1, allParked, release,
p1 + 1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
} else {
allParked.countDown();
release.await(); // Thread parks here with a lot of frames on its stack
childResult = 42;
}
return childResult + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10;
}
static long usedHeapMb() {
Runtime rt = Runtime.getRuntime();
return (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024);
}
static void printTopHeapObjects() throws Exception {
String histogram = (String) ManagementFactory.getPlatformMBeanServer().invoke(
new ObjectName("com.sun.management:type=DiagnosticCommand"),
"gcClassHistogram",
new Object[]{null},
new String[]{"[Ljava.lang.String;"}
);
System.out.println("\nTop objects on the heap (GC.class_histogram):");
histogram.lines().limit(7).forEach(System.out::println);
}
}
|
Running this show the following result:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| === Platform Threads ===
Heap before : 3 MB
Heap while parked : 6 MB (+3 MB)
=== Virtual Threads ===
Heap before : 5 MB
Heap while parked : 505 MB (+500 MB)
Top objects on the heap (GC.class_histogram):
num #instances #bytes class name (module)
-------------------------------------------------------
1: 10000 509029008 jdk.internal.vm.StackChunk (java.base@27)
2: 2729 13421608 [Ljdk.internal.vm.FillerElement; (java.base@27)
3: 10000 1600000 java.lang.VirtualThread (java.base@27)
4: 20024 1100872 [B (java.base@27)
5: 3833 489520 java.lang.Class (java.base@27)
|
With 10,000 parked platform threads, the Java heap only grew by 3 MB (just for the Thread and other things). With 10,000 parked virtual threads, the Java heap jumped by 500 MB.
The heap histogram shows that we gained a lot of StackChunks.
- The 10,000
java.lang.VirtualThread objects themselves only use 1.6 MB (160 bytes each). - Their frozen stacks (
jdk.internal.vm.StackChunk) consume 509 MB on the Java heap—about 51 KB per thread.
Platform threads look so good in comparison, only because they don't place their stack on the heap.
Crashing the Heap with an OutOfMemoryError
Because parked virtual thread stacks live on the Java heap, what happens when your heap is smaller than the combined stack size of your parked threads?
Let's run the exact same 10,000-thread, 500-depth workload with a constrained 250 MB heap (-Xmx250m) and the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
| public class HeapOomDemo {
static final int THREAD_COUNT = 10_000;
static final int DEPTH = 500;
static volatile long sink;
public static void main(String[] args) throws Exception {
boolean usePlatform = args.length > 0 && args[0].equalsIgnoreCase("platform");
System.out.printf("Starting %,d %s threads (Depth: %d, Max Heap: %d MB)...%n",
THREAD_COUNT,
usePlatform ? "Platform" : "Virtual",
DEPTH,
Runtime.getRuntime().maxMemory() / (1024 * 1024));
CountDownLatch allParked = new CountDownLatch(THREAD_COUNT);
CountDownLatch release = new CountDownLatch(1);
try (var executor = usePlatform
? Executors.newCachedThreadPool()
: Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 1; i <= THREAD_COUNT; i++) {
int threadId = i;
executor.submit(() -> {
try {
sink = dive(0, allParked, release,
System.nanoTime(), 2, 3, 4, 5, 6, 7, 8, 9, 10);
} catch (OutOfMemoryError oom) {
System.err.printf("!! CRASH at thread %,d !! %s%n", threadId, oom);
System.exit(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
if (i % 1000 == 0) {
Thread.sleep(100);
long usedMb = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024);
System.out.printf("Submitted %,5d threads | Heap used: %,4d MB%n", i, usedMb);
}
}
allParked.await();
long usedMb = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024);
System.out.printf("SUCCESS! All %,d threads parked. Peak heap used: %d MB%n", THREAD_COUNT, usedMb);
release.countDown();
}
}
static long dive(int depth, CountDownLatch allParked, CountDownLatch release,
long p1, long p2, long p3, long p4, long p5,
long p6, long p7, long p8, long p9, long p10) throws InterruptedException {
long childResult;
if (depth < DEPTH) {
childResult = dive(depth + 1, allParked, release,
p1 + 1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
} else {
allParked.countDown();
release.await();
childResult = 42;
}
return childResult + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10;
}
}
|
First, let's run it with Platform Threads on a 250 MB heap (java -Xmx250m HeapOomDemo.java platform):
1
2
3
4
5
6
7
8
9
10
11
12
| Starting 10,000 Platform threads (Depth: 500, Max Heap: 250 MB)...
Submitted 1,000 threads | Heap used: 9 MB
Submitted 2,000 threads | Heap used: 11 MB
Submitted 3,000 threads | Heap used: 13 MB
Submitted 4,000 threads | Heap used: 16 MB
Submitted 5,000 threads | Heap used: 10 MB
Submitted 6,000 threads | Heap used: 12 MB
Submitted 7,000 threads | Heap used: 15 MB
Submitted 8,000 threads | Heap used: 17 MB
Submitted 9,000 threads | Heap used: 20 MB
Submitted 10,000 threads | Heap used: 22 MB
SUCCESS! All 10,000 threads parked. Peak heap used: 22 MB
|
All 10,000 platform threads parked cleanly using only 22 MB of Java heap. (To be fair, their stacks aren't free they are sitting in native OS memory outside -Xmx250m, consuming a bunch of RAM).
Now let's run the exact same code with Virtual Threads (java -Xmx250m HeapOomDemo.java virtual):
1
2
3
4
5
6
7
8
| Starting 10,000 Virtual threads (Depth: 500, Max Heap: 250 MB)...
Submitted 1,000 threads | Heap used: 67 MB
Submitted 2,000 threads | Heap used: 117 MB
Submitted 3,000 threads | Heap used: 167 MB
Submitted 4,000 threads | Heap used: 217 MB
Submitted 5,000 threads | Heap used: 246 MB
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main"
|
Every 1,000 virtual threads adds roughly 50 MB of StackChunk objects to the heap. Because all of those threads are still parked and waiting to wake up, their StackChunk objects are still referenced and cannot be cleaned up by the Garbage Collector. Around 4,800 threads, the 250 MB Java heap is completely full and the JVM crashes with an OutOfMemoryError.
Virtual threads shift stack memory pressure away from native memory and directly into the Java heap.
Garbage Collection Churn
What if your heap is big enough that you don't run out of memory, but your application handles a steady stream of tasks with deep stacks?
If the same virtual thread blocks and wakes up repeatedly at the same stack depth, the JVM can often reuse its existing StackChunk in-place. However, the standard way to use virtual threads is thread-per-task (Pooling is frowned upon), where every incoming task starts on a brand-new virtual thread.
That means the first time each task blocks, the JVM must allocate a fresh StackChunk on the heap and copy the stack frames into it. Once the task finishes, that StackChunk is thrown away for the Garbage Collector to clean up.
Let's measure how much garbage this creates using JMH and its GC profiler (-prof gc). In each operation, 500 tasks recurse to either a shallow depth (10) or a deep depth (150), park once, and finish:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
| @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2, time = 2, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 3, time = 2, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class StackChurnBenchmark {
@Param({"500"})
private int tasks;
@Param({"10", "150"})
private int depth;
private ExecutorService platformPool;
private ExecutorService virtualExecutor;
@Setup(Level.Trial)
public void setup() {
platformPool = Executors.newFixedThreadPool(tasks);
virtualExecutor = Executors.newVirtualThreadPerTaskExecutor();
}
@TearDown(Level.Trial)
public void tearDown() {
platformPool.shutdownNow();
virtualExecutor.shutdownNow();
}
@Benchmark
public void platformThreads(Blackhole bh) throws Exception {
runBatch(platformPool, bh);
}
@Benchmark
public void virtualThreads(Blackhole bh) throws Exception {
runBatch(virtualExecutor, bh);
}
private void runBatch(ExecutorService executor, Blackhole bh) throws Exception {
CountDownLatch allParked = new CountDownLatch(tasks);
CountDownLatch release = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(tasks);
for (int i = 0; i < tasks; i++) {
executor.submit(() -> {
try {
long res = dive(0, depth, allParked, release,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
bh.consume(res);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
});
}
allParked.await();
release.countDown();
done.await();
}
private static long dive(int current, int maxDepth,
CountDownLatch allParked, CountDownLatch release,
long p1, long p2, long p3, long p4, long p5,
long p6, long p7, long p8, long p9, long p10) throws InterruptedException {
long childResult;
if (current < maxDepth) {
childResult = dive(current + 1, maxDepth, allParked, release,
p1 + 1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
} else {
allParked.countDown();
release.await();
childResult = 42;
}
return childResult + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10;
}
}
|
Running this with java -jar benchmarks.jar com.davidvlijmincx.article.StackChurnBenchmark -prof gc gives us the heap allocation rate (gc.alloc.rate) and bytes allocated per benchmark operation (gc.alloc.rate.norm):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| Benchmark (depth) (tasks) Mode Cnt Score Units
StackChurnBenchmark.platformThreads 10 500 avgt 3 5.658 ms/op
StackChurnBenchmark.platformThreads:gc.alloc.rate 10 500 avgt 3 12.976 MB/sec
StackChurnBenchmark.platformThreads:gc.alloc.rate.norm 10 500 avgt 3 76572.011 B/op
StackChurnBenchmark.platformThreads 150 500 avgt 3 6.370 ms/op
StackChurnBenchmark.platformThreads:gc.alloc.rate 150 500 avgt 3 11.458 MB/sec
StackChurnBenchmark.platformThreads:gc.alloc.rate.norm 150 500 avgt 3 76719.616 B/op
StackChurnBenchmark.virtualThreads 10 500 avgt 3 0.777 ms/op
StackChurnBenchmark.virtualThreads:gc.alloc.rate 10 500 avgt 3 1240.099 MB/sec
StackChurnBenchmark.virtualThreads:gc.alloc.rate.norm 10 500 avgt 3 1004230.564 B/op
StackChurnBenchmark.virtualThreads 150 500 avgt 3 1.316 ms/op
StackChurnBenchmark.virtualThreads:gc.alloc.rate 150 500 avgt 3 5724.376 MB/sec
StackChurnBenchmark.virtualThreads:gc.alloc.rate.norm 150 500 avgt 3 7903987.815 B/op
|
Look at the difference in gc.alloc.rate.norm (bytes allocated on the heap per operation):
- Pooled Platform Threads: At depth 10, an operation allocates 76.5 KB (just for the
FutureTask wrappers submitted to the pool). At depth 150, it allocates 76.7 KB. Scaling the stack to a depth of 150 added zero bytes to the heap because platform threads reuse memory. - Virtual Threads: At depth 10, an operation allocates 1.0 MB (~1.2 GB/sec). At depth 150, heap allocation jumps to 7.9 MB per operation, hammering the garbage collector at 5,724 MB/sec (5.7 GB/sec) purely from allocating and discarding
StackChunk objects.
Carrier Hopping and CPU Cache Locality
Heap memory and GC pressure are only half the story. What happens at the CPU hardware level when virtual threads pause and resume?
When a platform thread runs a compute loop, the OS scheduler usually keeps it on the same physical CPU core, keeping its working data warm in that core's ultra-fast L1 and L2 caches.
When a virtual thread pauses, it unmounts from its carrier thread. While it is unmounted, other virtual threads run on that carrier thread and overwrite the core's L1/L2 caches with their own data. Even worse, when our virtual thread wakes up, it can be picked up by a completely different carrier thread running on a different CPU core!
We can see this carrier hopping directly using Thread.currentThread().toString(), which prints the name of the current carrier worker after the @ sign (CarrierHoppingDemo.java):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| public class CarrierHoppingDemo {
public static void main(String[] args) throws Exception {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
// Launch a few background virtual threads that wake up and pause
for (int i = 0; i < 16; i++) {
executor.submit(() -> {
for (int step = 0; step < 50; step++) {
try { Thread.sleep(1); } catch (InterruptedException ignored) {}
}
});
}
// Track which carrier thread our virtual thread wakes up on
executor.submit(() -> {
String lastCarrier = "";
for (int step = 1; step <= 8; step++) {
String carrier = Thread.currentThread().toString().replaceFirst(".*@", "");
String note = (!lastCarrier.isEmpty() && !lastCarrier.equals(carrier))
? "<-- Hopped carrier!" : "";
System.out.printf("Run %d: %-26s %s%n", step, carrier, note);
lastCarrier = carrier;
try { Thread.sleep(2); } catch (InterruptedException ignored) {}
}
}).get();
}
}
}
|
Running this prints:
1
2
3
4
5
6
7
8
| Run 1: ForkJoinPool-1-worker-7
Run 2: ForkJoinPool-1-worker-5 <-- Hopped carrier!
Run 3: ForkJoinPool-1-worker-4 <-- Hopped carrier!
Run 4: ForkJoinPool-1-worker-5 <-- Hopped carrier!
Run 5: ForkJoinPool-1-worker-5
Run 6: ForkJoinPool-1-worker-19 <-- Hopped carrier!
Run 7: ForkJoinPool-1-worker-19
Run 8: ForkJoinPool-1-worker-12 <-- Hopped carrier!
|
If your virtual thread was waiting 30 milliseconds for a database query, hopping to another CPU core doesn't matter at all. Your data was evicted from the CPU cache a long time ago anyway.
However, if you use virtual threads for CPU-heavy work that frequently yields or passes messages, unmounting and swapping tasks across carrier threads hurts CPU cache locality.
Let's measure the hardware impact with JMH's Linux perf profiler (-prof perfnorm). We run 64 tasks on a 32-thread CPU. Each task loops 2,000,000 times over its own 8 KB int[] array. Small enough to fit entirely inside a single core's cache, and calls Thread.yield() every 1,000 steps:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
| @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2, time = 2, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 3, time = 2, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class CacheLocalityBenchmark {
private static final int ARRAY_LEN = 2 * 1024;
private static final int ITERATIONS_PER_TASK = 2_000_000;
private int taskCount;
private int[][] taskArrays;
private ExecutorService platformPool;
private ExecutorService virtualExecutor;
@Setup(Level.Trial)
public void setup() {
int cores = Runtime.getRuntime().availableProcessors();
taskCount = cores * 2; // 64 tasks competing for 32 logical cores
taskArrays = new int[taskCount][ARRAY_LEN];
for (int t = 0; t < taskCount; t++) {
for (int i = 0; i < ARRAY_LEN; i++) {
taskArrays[t][i] = i + 1;
}
}
platformPool = Executors.newFixedThreadPool(cores);
virtualExecutor = Executors.newVirtualThreadPerTaskExecutor();
}
@TearDown(Level.Trial)
public void tearDown() {
platformPool.shutdownNow();
virtualExecutor.shutdownNow();
}
@Benchmark
public void platformThreads(Blackhole bh) throws Exception {
runTasks(platformPool, bh);
}
@Benchmark
public void virtualThreads(Blackhole bh) throws Exception {
runTasks(virtualExecutor, bh);
}
private void runTasks(ExecutorService executor, Blackhole bh) throws Exception {
CountDownLatch done = new CountDownLatch(taskCount);
for (int t = 0; t < taskCount; t++) {
final int[] array = taskArrays[t];
executor.submit(() -> {
try {
bh.consume(traverseArray(array));
} finally {
done.countDown();
}
});
}
done.await();
}
private static long traverseArray(int[] data) {
long sum = 0;
int index = 0;
int mask = ARRAY_LEN - 1;
for (int i = 0; i < ITERATIONS_PER_TASK; i++) {
sum += data[index];
index = (index + 17) & mask;
if (i % 1000 == 0) {
Thread.yield();
}
}
return sum;
}
}
|
Both platformThreads and virtualThreads execute the exact same 64 tasks, the exact same array lookups, and the exact same number of Thread.yield() calls. Here is what the CPU hardware counters report:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| Benchmark Cnt Score Units
CacheLocalityBenchmark.platformThreads 3 18.565 ms/op
CacheLocalityBenchmark.platformThreads:IPC 2.682 insns/clk
CacheLocalityBenchmark.platformThreads:L1-dcache-load-misses 2475090.907 #/op
CacheLocalityBenchmark.platformThreads:LLC-load-misses 43369.941 #/op
CacheLocalityBenchmark.platformThreads:cycles 832929395.592 #/op
CacheLocalityBenchmark.platformThreads:instructions 2234300648.191 #/op
CacheLocalityBenchmark.virtualThreads 3 19.800 ms/op
CacheLocalityBenchmark.virtualThreads:IPC 1.622 insns/clk
CacheLocalityBenchmark.virtualThreads:L1-dcache-load-misses 14539579.715 #/op
CacheLocalityBenchmark.virtualThreads:LLC-load-misses 2201012.278 #/op
CacheLocalityBenchmark.virtualThreads:cycles 1641707746.337 #/op
CacheLocalityBenchmark.virtualThreads:instructions 2663465120.640 #/op
|
With Platform Threads, only 32 tasks run at a time (one per logical core) while the remaining 32 wait in the pool queue. Each worker thread finishes a task from start to end before picking up the next one, so once the 8 KB array is loaded into the core's L1 cache, it stays hot.
With Virtual Threads, all 64 tasks start immediately. Every Thread.yield() unmounts the virtual thread, copies its stack frame to the heap, and swaps a waiting virtual thread (with a different 8 KB array) onto the carrier thread:
- Instruction overhead: Virtual threads execute 2.66 billion instructions vs. 2.23 billion on platform threads. That's 429 million extra instructions per operation just for unmounting, mounting, and queue management.
- L1 cache misses (working-set eviction): L1 data cache misses jump 5.9x (2.48M to 14.54M) as tasks constantly evict each other's 8 KB arrays when swapping onto carrier threads.
- L3 cache misses: Last-Level cache misses jump 50x (43.4K to 2.20M).
- Total CPU work: Total CPU cycles nearly double (833M to 1,642M cycles, 2.0x), and CPU efficiency (IPC, “Instructions Per Cycle”) drops from 2.68 down to 1.62.
TL;DR
Virtual threads are not “free” threads. They trade dedicated OS stack memory for Java heap allocations and user-space scheduling. When used for blocking I/O, that trade-off is a massive win. When used for deep recursion or cache-sensitive CPU loops, you pay the price in heap memory, GC churn, and cache misses.
| Characteristic | Platform Threads | Virtual Threads | What It Means for You |
|---|
| Stack Location (Parked) | Native OS memory (off-heap) | Java Heap (StackChunk) | Parked virtual thread stacks are stored on the heap |
| Heap Cost When Blocking | 0 bytes for the stack | Scales with stack depth (~51 KB at depth 500) | Deep stacks + thread-per-task creates heavy GC churn. |
| Out-Of-Memory Risk | OS thread limit / native RAM | As long as you dont run out of heap | Thousands of parked deep stacks can fill up a small heap. |
| Scheduler Order | LIFO (Depth-First in ForkJoinPool) | FIFO (Breadth-First) | Recursive start() + join() parks thousands of parents at once. |
| CPU Cache Locality | Stays on the same OS thread / core | Unmounts and hops across carrier threads | Frequent yielding in compute loops causes L1/L3 cache misses. |
| Best Used For | CPU-bound work, parallel streams, recursion | Blocking I/O (HTTP, SQL, network calls) | Match the thread type to the workload. |
Conclusion
Everything we did in this article was a stress test designed to push virtual threads in the exact opposite direction of what they were built for. In everyday backend services, your stacks are small, your threads spend most of their time waiting on the network, and virtual threads do their job brilliantly.
The takeaway is simply understanding why and when you should use each kind of thread:
- Virtual thread stacks are stored on the Java heap whenever a thread parks.
- If your threads have deep call stacks and block frequently in thread-per-task mode, your Garbage Collector will be doing cardio (which it can easily do).
- If your workload is CPU-bound, keep it on platform threads or
ForkJoinPool where LIFO scheduling and hot CPU caches work in your favor.
Use virtual threads when you are waiting on I/O, keep your CPU-heavy work on platform threads, and you get the best of both worlds.
Further Reading on Virtual Threads & JVM Concurrency
🚀 In-House Team Workshop · 1 Day (Live In-Person On-Site)Adopt Virtual Threads & Structured Concurrency Without Production Surprises
Virtual threads look simple on paper—until carrier thread pinning, unmounted stack heap pressure, or legacy ThreadLocals hit production. Bring me in for a tailored 1-day Java Virtual Threads, Structured Concurrency & Scoped Values Workshop built around your team's actual architecture and frameworks.
Stay Connected · Code, Benchmarks & TalksWant More Deep-Dive JVM Benchmarks & Project Panama Research?
Follow my weekly engineering posts on LinkedIn, explore the full JMH benchmark suites and pure-Java Linux io_uring / FUSE projects on GitHub, or download my conference talk slides: