JDK 24 came out on 18 March 2025, and with it JEP 491: a virtual thread that blocks inside synchronized no longer pins its carrier thread. Last year I wrote about turning on virtual threads in Spring Boot 3.2, and pinning was the first pitfall there. With that fixed, I wanted to see where Java now stands next to the other models I use: goroutines in Go, coroutines in Kotlin, asyncio in Python and async/await in Rust.
This is a comparison of the models, not a benchmark. I give no numbers.
The same program five times
Each program starts 10,000 tasks. Each task sleeps one second and then increments a counter. The program waits for all tasks and prints the counter. Sleep stands in for a network call.
Java 21 or later:
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class Sleepers {
public static void main(String[] args) {
var done = new AtomicInteger();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
done.incrementAndGet();
return null;
});
}
} // close() waits for all tasks
System.out.println(done.get());
}
}
Go:
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
var wg sync.WaitGroup
var done atomic.Int64
for i := 0; i < 10000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(time.Second)
done.Add(1)
}()
}
wg.Wait()
fmt.Println(done.Load())
}
Kotlin with kotlinx.coroutines:
import kotlinx.coroutines.*
import java.util.concurrent.atomic.AtomicInteger
fun main() = runBlocking {
val done = AtomicInteger()
coroutineScope {
repeat(10_000) {
launch {
delay(1000)
done.incrementAndGet()
}
}
}
println(done.get())
}
Python 3.11 or later:
import asyncio
async def worker(counter):
await asyncio.sleep(1)
counter[0] += 1
async def main():
counter = [0]
async with asyncio.TaskGroup() as tg:
for _ in range(10_000):
tg.create_task(worker(counter))
print(counter[0])
asyncio.run(main())
Rust with Tokio:
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::task::JoinSet;
#[tokio::main]
async fn main() {
let done = Arc::new(AtomicUsize::new(0));
let mut set = JoinSet::new();
for _ in 0..10_000 {
let done = done.clone();
set.spawn(async move {
tokio::time::sleep(Duration::from_secs(1)).await;
done.fetch_add(1, Ordering::Relaxed);
});
}
while let Some(res) = set.join_next().await {
res.unwrap();
}
println!("{}", done.load(Ordering::Relaxed));
}
All five finish in about one second plus overhead. The code looks similar. The differences are underneath.
Stackful and stackless
Java virtual threads and goroutines are stackful. Each task has its own call stack. When a virtual thread blocks, the JVM copies its stack frames to the heap and later copies them back. Any function at any depth can block, and the task is suspended with its whole stack.
Kotlin coroutines, Python coroutines and Rust futures are stackless. The compiler turns each suspend or async function into a state machine. The state machine only holds the local variables that live across a suspension point. A task can only suspend at points the compiler knows about: a suspend call in Kotlin, an await in Python or Rust.
This one difference explains most of the rest.
Scheduling
All five run many tasks on fewer OS threads (M:N), with one exception.
- Java: virtual threads run on a
ForkJoinPoolof carrier threads, by default one per CPU core. - Go: the runtime scheduler runs goroutines on OS threads, with
GOMAXPROCS(default: number of cores) running Go code at the same time. - Kotlin: the dispatcher decides.
Dispatchers.Defaultuses a pool sized to the cores,Dispatchers.IOa larger pool for blocking work. - Rust: the runtime decides. Tokio’s default runtime is multi-threaded with work stealing. You can also choose a single-threaded runtime.
- Python: asyncio runs one event loop on one thread. Concurrency, but no parallelism for Python code.
Preemption
Go has asynchronous preemption since Go 1.14. A goroutine in a tight loop without function calls can be interrupted by the runtime, so one busy goroutine does not starve the others or block garbage collection.
The others are cooperative. A Kotlin coroutine, a Python task or a Rust future gives up the thread only at a suspension point. A long CPU loop blocks the thread for everyone on it. In Python this means the whole event loop stops. Tokio has some cooperative budgeting for its own resources, but it cannot interrupt your loop.
Java virtual threads are also not time-sliced. A virtual thread that runs CPU work keeps its carrier until it blocks or finishes. With one carrier per core, a few CPU-heavy virtual threads can delay all the others. Virtual threads are for tasks that mostly wait. CPU work belongs in a normal, bounded pool.
Function colouring
With async/await, an async function can only be awaited from another async function. If a function deep in the call graph becomes async, every caller up to the top must change too. This is called the function colouring problem. Kotlin has the same rule with suspend. Libraries split into two worlds: blocking clients and async clients.
Virtual threads and goroutines do not have this problem. There is one kind of function. Thread.sleep, a JDBC call or InputStream.read is a normal blocking call, and the runtime makes the blocking cheap. For Java this is the main point of virtual threads: existing blocking libraries keep working, and the code stays sequential and readable.
Blocking calls
What happens when a task calls something that really blocks the OS thread?
- Go: when a goroutine enters a blocking system call, the runtime gives its processor to another OS thread, so other goroutines continue. Network I/O uses the netpoller and does not block a thread.
- Java: most JDK blocking operations (sockets,
Thread.sleep, locks injava.util.concurrent) unmount the virtual thread. Some operations, such as many file I/O calls, cannot unmount. Then the scheduler temporarily adds a carrier thread to compensate. - Kotlin: a blocking call inside a coroutine blocks the dispatcher thread. You move it to
Dispatchers.IOwithwithContext(Dispatchers.IO) { ... }. - Python: a blocking call (
requests.get,time.sleep) stops the whole event loop. Useawait asyncio.to_thread(...)or an async library. - Rust: a blocking call stalls a Tokio worker thread. Use
tokio::task::spawn_blockingfor it.
In the stackless models you must know which calls block. Nothing warns you at compile time. In Java and Go the runtime handles most cases.
Pinning
Pinning is Java-specific. A pinned virtual thread cannot unmount, so when it blocks, its carrier blocks too.
In JDK 21 to 23, the main causes were synchronized blocks and Object.wait(). JDK 24 with JEP 491 removes these cases: the virtual thread can now unmount while it waits for a monitor, holds one, or is in Object.wait(). The JEP also removes the jdk.tracePinnedThreads system property. The JFR event jdk.VirtualThreadPinned still exists for the remaining cases.
What still pins in JDK 24: native frames. If a virtual thread calls native code through JNI or the FFM API, and that native code calls back into Java and blocks, it is pinned. Class initialisation is a similar case. These are rare in normal web code, but some drivers use native code.
The other models have their own version of the same problem. Holding a normal mutex across an await in Rust or a blocking lock in a Kotlin coroutine has a similar effect.
Cancellation and structured concurrency
Kotlin has structured concurrency built in. Every coroutine runs in a scope. coroutineScope waits for its children, and if one child fails, the others are cancelled. Cancellation is cooperative: it happens at suspension points, and CPU loops should check isActive or call ensureActive().
Python has asyncio.TaskGroup since 3.11, with similar rules: if a task fails, the others are cancelled and the errors are raised as an ExceptionGroup. Cancellation raises CancelledError at an await.
Rust cancels a future by dropping it. This is simple, but code after an .await may never run, so cleanup must happen in Drop. JoinSet aborts its tasks when it is dropped.
Go has no built-in task tree. You pass a context.Context and check ctx.Done(). errgroup from golang.org/x/sync gives a group that cancels the context on the first error.
Java interrupts threads with Thread.interrupt(), and blocking calls throw InterruptedException. Structured concurrency (StructuredTaskScope) is still a preview API in JDK 24, the fourth preview (JEP 499), so it needs --enable-preview. The API may still change, so I do not use it in production code yet. For now, an executor in try-with-resources at least makes sure all tasks are finished when the block ends, like in the Java example above.
Debugging and stack traces
This is where stackful models are nicer. A virtual thread has a real stack. Exceptions show the full call path, debuggers step through it, and profilers see normal Java frames. A thread dump can include virtual threads:
jcmd <pid> Thread.dump_to_file -format=json threads.json
Go shows all goroutines with their stacks in a panic or with SIGQUIT, and pprof has a goroutine profile.
In the stackless models, the stack trace shows the state machine being resumed by the scheduler, not the logical chain of callers. Kotlin has kotlinx-coroutines-debug and IDE support to rebuild the coroutine chain. Python can print a task’s stack with task.print_stack(), and asyncio debug mode warns about slow callbacks. Rust has tokio-console for task state, and backtraces are often full of runtime frames. All of this works, but it takes more effort.
Memory per task
I will not give numbers, because they depend on what the task holds. The general picture:
- A Rust future is a state machine with a size known at compile time. Very small, but deep async call chains can make big futures.
- Kotlin and Python coroutines are heap objects that keep only live locals. Python objects are large compared with the others, but still small next to an OS thread.
- Goroutines start with a small stack that grows and shrinks as needed.
- Virtual thread stacks live on the Java heap as chunks and grow with call depth. A deep Spring call stack costs more than a small task, and it is garbage-collected memory.
All of them are far cheaper than an OS thread. If you need a million tasks, measure your real task, not an empty one.
What I take from this for Java and Spring
- For blocking-style services (Spring MVC, JDBC,
RestClient), virtual threads are the simplest way to handle many waiting requests. You keep normal code and normal stack traces. Setspring.threads.virtual.enabled=trueand test under load. - Move to JDK 24 if you can run a non-LTS release. The
synchronizedpinning was the most common problem, and it is gone. Otherwise keep the advice from the earlier post for Java 21. - Virtual threads do not limit concurrency. Connection pools, rate limits and downstream services still do. Use a
Semaphoreor the pool size to limit calls to slow resources. - Do not use virtual threads for CPU-heavy work. They are not preempted.
- If you already use WebFlux or Kotlin coroutines and they work for you, I see no reason to rewrite. Reactive code still gives you backpressure and streaming operators that plain threads do not.
- Avoid large
ThreadLocalcaches. With one virtual thread per request, a per-thread cache is a per-request cache. - Wait for structured concurrency to become final before you build on it. Until then, an executor in try-with-resources and normal exception handling are enough for most fan-out code.