ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 2 · JVM, Concurrency & Performance
  4. Volume V
  5. Virtual vs Platform Threads
Book 2 · Volume V — Modern Concurrency, Virtual Threads & Performance Engineering · Topic 1.4

Virtual vs Platform Threads

Memory, scalability, blocking, CPU-bound and I/O-bound work

10 min readStage 1 · Foundations10 interview questions
Prerequisites
1.1 · 1.2 · 1.3
Covers
Memory · Scalability · Blocking · CPU-bound · I/O-bound
Related
Chapter 10 (threading model selection) · 4.4 Reactive vs Virtual Threads
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers

1Concept / Definition

Virtual and platform threads share one API but differ in cost and behaviour. Memory: virtual threads use small, growable heap stacks; platform threads reserve native stacks. Scalability: millions versus thousands. Blocking: virtual threads release their carrier; platform threads hold an OS thread. The decisive question is the workload: I/O-bound work gains dramatically from virtual threads; CPU-bound work gains nothing and is best run on pools sized to cores.

Virtual vs platform threads
Figure 1 — Virtual vs platform threads

2Why It Exists

Choosing the wrong model wastes either threads (blocking platform threads) or effort (virtual threads for computation). The comparison provides a decision basis for new services and migrations.

The question matters because the two kinds of thread fail in opposite ways. A service built on a fixed pool of platform threads that spends most of its time waiting on databases and remote calls runs out of threads long before it runs out of CPU: requests queue, latency climbs and the usual fix of adding instances or growing the pool costs memory and money. A service that moves computation onto virtual threads gains nothing in throughput and can harm latency, because long computations occupy carriers that I/O-bound tasks need. Since Java 21 both models sit behind the same Thread and ExecutorService APIs, so the choice can be made per workload, and even per task within one request, rather than per framework or rewrite.

3Core Concepts

Memory

Memory for 10,000 concurrent blocking tasks
Figure 2 — Memory for 10,000 concurrent blocking tasks
  • Platform: native stack reserved per thread, committed as used, plus JVM/kernel structures — outside the heap (counts against container memory, not -Xmx).
  • Virtual: stack chunks on the heap sized to the actual frames; plus a small thread object. Counts against heap and is visible to GC.
  • Heap sizing moves: fewer native bytes, more heap objects under high concurrency.

Scalability

Throughput vs concurrent I/O-bound requests
Figure 3 — Throughput vs concurrent I/O-bound requests
  • Platform-thread servers plateau when the pool is exhausted, although CPU may be idle.
  • Virtual-thread servers continue to scale until a real resource saturates (CPU, database, downstream).
  • Little's law: concurrency = throughput × latency; with 200 ms latency, 10,000 requests/s needs ~2,000 concurrent threads — easy with virtual threads, expensive with platform threads.

Blocking

  • Blocking a platform thread holds its OS thread idle; blocking a virtual thread releases the carrier (except when pinned).
  • Consequently, blocking APIs (JDBC, blocking HTTP clients) become acceptable at high concurrency with virtual threads.
  • Blocking that pins (native calls, class init) behaves like platform blocking — but on a scarce carrier (2.3).

CPU-bound

  • Throughput limited by cores; virtual threads add scheduling overhead without benefit.
  • Long computations on virtual threads monopolise carriers (no time slicing) and delay I/O-bound virtual threads.
  • Use a bounded platform pool (≈ cores), ForkJoinPool or parallel streams for computation; call it from virtual threads if needed.

I/O-bound

CPU-bound vs I/O-bound
Figure 4 — CPU-bound vs I/O-bound
  • The sweet spot: request handling, service-to-service calls, database access, messaging.
  • Simple thread-per-task code with blocking calls scales like asynchronous code.
  • Concurrency must be bounded where resources are limited: connection pools, semaphores, rate limiters.

4How It Works Internally

The difference comes from where waiting happens: a platform thread waits inside the kernel on its own OS thread; a virtual thread waits as a parked continuation on the heap, while the carrier returns to the scheduler. Running code is identical — both execute on OS threads with JIT-compiled code; only switching and waiting differ.

In practice the switch works like this. A platform thread that calls a blocking socket read enters the kernel and the OS deschedules it; its 1 MB stack reservation and kernel structures stay allocated while it waits. A virtual thread calling the same read goes through a JDK path that registers the socket with a poller and parks: its frames are copied into StackChunk objects on the heap, and the ForkJoinPool carrier, one per core by default, picks up the next runnable virtual thread. When data arrives, the poller unparks the virtual thread and a carrier copies the frames back lazily. If unmounting is impossible because the thread is pinned, for example inside a native frame or class initialisation, the carrier blocks instead; since JDK 24 (JEP 491) synchronized no longer pins.

5APIs / Features / Syntax

JAVACombining both models
// Mixed workload: I/O on virtual threads, CPU work on a bounded platform pool
ExecutorService cpu = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
        Thread.ofPlatform().name("cpu-", 0).factory());

try (ExecutorService io = Executors.newVirtualThreadPerTaskExecutor()) {
    for (Request r : requests) {
        io.submit(() -> {
            Data d = repository.load(r.id());  // blocking I/O: fine here
            // heavy CPU: bounded platform pool
            Report rep = cpu.submit(() -> analyse(d)).get();
            client.send(rep);  // blocking I/O again
            return null;
        });
    }
}

6Practical Examples

WorkloadChoiceReason
HTTP API calling databases/servicesvirtual threadsI/O-bound, high concurrency
video transcoding workersplatform pool ≈ coresCPU-bound
batch: fetch 1 M URLsvirtual threads + semaphoreI/O-bound, bounded downstream
low-latency trading enginededicated platform threads (pinned cores)predictable scheduling
message consumer with DB writesvirtual threads per message/batchI/O-bound

7Common Problems & Mistakes

  • Switching CPU-bound services to virtual threads and expecting speed-ups.
  • Removing all limits after switching (overloading databases).
  • Ignoring heap growth from parked virtual threads.
  • Judging by micro-benchmarks that don't block.

8Performance & Production Considerations

  • Benchmark with realistic latency of dependencies; gains appear only when waiting dominates.
  • Monitor carrier utilisation, pinning events, heap usage and downstream pool saturation.
  • Keep CPU pools separate to protect latency-sensitive I/O work.

9Architecture & Design Considerations

The threading model is an architectural choice (Chapter 10): virtual threads for I/O-bound services favour simple synchronous code; platform pools remain for computation; reactive for streaming and backpressure. The decision should follow measured workload characteristics, not fashion.

Two design consequences follow. First, capacity control moves from the thread pool to the resources themselves: with virtual threads the pool no longer limits concurrency, so every database, downstream API and memory-heavy operation needs its own explicit bound, such as a connection pool, a semaphore, a bulkhead or a rate limiter, and those limits become part of the service design. Second, mixed services should keep computation and waiting apart: request handling on virtual threads, heavy computation on a bounded platform pool, so a burst of CPU work cannot starve I/O-bound requests of carriers. Recording the classification and limits in an ADR makes the model explicit for future maintainers and reviewers.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is the main difference between virtual and platform threads?

A platform thread is a thin wrapper around an operating-system thread: one Java thread, one kernel thread, scheduled by the OS for its whole life. A virtual thread is a lightweight thread scheduled by the JVM, mounted on a small pool of carrier platform threads only while it runs. When a virtual thread blocks on I/O, a lock or a sleep, the JVM unmounts it, saves its stack on the heap and lets the carrier run another virtual thread. That makes virtual threads cheap enough to create one per task, while platform threads cost about a megabyte of reserved stack each and kernel resources, which limits them to thousands.

Q2L1 · BasicInternals

Where is a virtual thread's stack stored when it is parked?

On the Java heap, in StackChunk objects. When a virtual thread unmounts, the JVM copies its active frames from the carrier's native stack into a stack chunk sized to the frames actually in use, so a shallow request handler typically needs a few kilobytes rather than a platform thread's megabyte. The chunk is an ordinary heap object: the garbage collector scans and moves it, and its size counts against -Xmx rather than native memory. When the thread is resumed, frames are copied back to a carrier lazily, only as deep as execution needs. One consequence is that a million parked virtual threads show up as heap usage, which you must size for.

Q3L2 · IntermediateConcept

Which workloads benefit from virtual threads?

Workloads where tasks spend most of their time waiting and you need many of them in flight. Typical examples are HTTP APIs that call databases or other services, gateways and aggregators fanning out to several backends, message consumers that write to a database, and batch jobs fetching many remote resources. By Little's law, a service doing 5,000 requests per second with 200 ms of waiting needs about 1,000 concurrent tasks, which is trivial with virtual threads and costly with platform threads. The benefit is that you get the scalability of asynchronous code while keeping simple, blocking, thread-per-request code and readable stack traces. Concurrency should still be bounded by the real resources behind those calls.

Q4L2 · IntermediateTricky

Do virtual threads help CPU-bound work?

No. Virtual threads make waiting cheap, not computation faster. CPU-bound throughput is limited by the number of cores, and a fixed platform pool sized to the cores already keeps them all busy; adding virtual threads only adds scheduling overhead. They can make things worse: the virtual-thread scheduler does not time-slice, so a long computation keeps its carrier until it finishes or blocks. If a service runs heavy computation on virtual threads, I/O-bound tasks can be starved of carriers and their latency rises. The right pattern is to keep computation on a bounded platform pool, ForkJoinPool or parallel streams, and call into it from virtual threads when a request needs it.

Q5L3 · Senior EngineerTrade-off

How does memory usage differ?

A platform thread reserves a native stack outside the heap, 1 MB by default on 64-bit Linux, set with -Xss. Only the pages actually touched are committed, but each thread also brings kernel and JVM structures, and all of it counts against the container's memory limit rather than -Xmx. A virtual thread has a small Thread object and, when parked, stack chunks on the heap proportional to its real call depth, often a few kilobytes. So moving to virtual threads trades native memory for heap: thousands of platform threads free a lot of native memory, while a million parked virtual threads can add gigabytes of heap and GC work, so size the heap accordingly.

Q6L3 · Senior EngineerConcept

What limits scalability once virtual threads are used?

Once threads are cheap, the limits move to the real resources behind them. CPU becomes the ceiling for the work done between waits. Database connection pools are usually the first wall: a pool of 50 connections means only 50 queries in flight no matter how many virtual threads exist, and the rest queue on the pool. Downstream services have their own capacity and rate limits, and memory grows with every parked thread and the data each one holds. Pinning can also exhaust carriers if many threads block in native code. That is why bounding concurrency explicitly with pools, semaphores, bulkheads and rate limiters remains essential after the switch.

Q7L3 · Senior EngineerDesign

How would you handle a request that is mostly I/O but includes a heavy computation step?

Run the request itself on a virtual thread, because most of its life is spent waiting on I/O, and offload the computation to a separate bounded platform pool sized to the number of cores. The virtual thread submits the task and blocks on the Future, which is cheap because it simply unmounts, then continues with the remaining I/O. Wait with a timeout, so a saturated pool or slow computation fails fast instead of piling up requests. This isolates the two workloads: CPU bursts cannot occupy carriers that I/O-bound requests need, and the pool's size and queue give back-pressure. Monitor pool queue length and computation time separately from request latency.

Q8L3 · Senior EngineerTricky

Why can micro-benchmarks mislead when comparing the models?

Because the benefit of virtual threads comes from overlapping waits, and most micro-benchmarks contain no waiting. A loop that runs short CPU tasks on both models measures thread creation and scheduling, where virtual threads show no advantage, or slight overhead from mounting and continuation handling. Other benchmarks use Thread.sleep or fake latency that does not resemble real I/O, or ignore that the real limit is a 20-connection database pool. The meaningful test is a load test with production-like dependency latencies, realistic concurrency levels and the real connection pools, measuring throughput, tail latency, CPU and memory. Use JMH only for narrow questions, such as the cost of a specific code path.

Q9L4 · Technical ArchitectScenario

How would you validate a migration from a platform pool to virtual threads?

Treat it as a performance change with a baseline. First load-test the existing platform-pool version with production-like dependency latencies and traffic shape, recording throughput, p99 latency, CPU, heap and native memory. Then switch, for example with spring.threads.virtual.enabled in Spring Boot, and repeat the same tests at increasing concurrency. Record JFR with jdk.VirtualThreadPinned events to find pinning in native code or old libraries, and check that connection pools, downstream services and rate limits now saturate gracefully rather than collapsing. Watch heap and GC for parked stack chunks and ThreadLocal growth. Roll out with a canary and clear rollback, comparing error rates and latency against the old version.

Q10L5 · Solution ArchitectTrade-off

How does the threading model affect architecture choices?

It shapes code style, capacity design and framework choice. With virtual threads, synchronous thread-per-request code scales for I/O-bound services, so teams can keep imperative frameworks like Spring MVC, blocking JDBC and simple debugging, and reserve reactive stacks for streaming, back-pressure or event-driven pipelines where they add real value. Capacity controls move from thread pools to explicit limits on databases, downstream calls and memory. Observability changes too: thread dumps can contain millions of threads, so structured concurrency and JFR become more important. At organisation level, I would define one default model per workload class, with CPU-bound work on bounded pools, and document it so teams don't mix paradigms without reason.

Test your knowledge on this topic →Flashcards from this topic's 10 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.