Quiz: Virtual Threads in Java: What They Are and How to Use Them

Total: 8 questions

1. 

What is a virtual thread in Java and how does it differ from a platform thread?

A virtual thread is a lightweight thread managed by the JVM rather than by the operating system. It came out of Project Loom and became a final feature in Java 21 (JEP 444). Thousands or millions of virtual threads run on a small pool of carrier threads; when a virtual thread waits (sleep, network, a lock), the JVM unmounts it from its carrier, and the carrier runs another thread.

A platform thread is a wrapper around an OS thread (1:1). The differences:

  • scheduling: a platform thread is scheduled by the OS, a virtual thread by the JVM on ForkJoinPool carriers (M:N);
  • stack: a platform thread has a fixed stack reserved at creation; a virtual thread keeps its stack on the heap and grows it as needed;
  • how many you can create: thousands of platform threads, hundreds of thousands or millions of virtual ones, limited by the heap;
  • a virtual thread is always a daemon, its priority is always NORM_PRIORITY, and its default name is an empty string;
  • platform threads are pooled; virtual threads are created per task.

In code both are the same java.lang.Thread class, told apart by isVirtual(). A virtual thread is not faster than a platform thread, it is cheaper: the gain is in how many waiting tasks you can have at once, not in the speed of a single task.

2. 

How do you create a virtual thread in Java 21?

There are four ways:

  • Thread.ofVirtual().start(task): a builder that lets you set a name and an exception handler; unstarted(task) creates the thread without starting it;
  • Thread.startVirtualThread(task): a quick way to start one unnamed thread;
  • Thread.ofVirtual().name("w-", 0).factory(): a ThreadFactory for APIs that accept a factory; threads are named w-0, w-1, and so on;
  • Executors.newVirtualThreadPerTaskExecutor(): the main option, with submit(), Future, invokeAll() and closing via try-with-resources.
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
    executor.submit(() -> callRemoteService());
}   // close() waits for all tasks

new Thread(...) always creates a platform thread. newVirtualThreadPerTaskExecutor() is not a pool: it has no task queue and no fixed set of threads, and every submit() creates a new virtual thread. If you want readable thread names in logs, pass the factory to Executors.newThreadPerTaskExecutor(factory).

3. 

How do virtual threads work: what are mounting, unmounting and carrier threads?

A virtual thread is a task plus its stack, stored on the heap as a continuation: an object that can suspend and later resume where it left off. To run, the thread is mounted on a carrier thread, an ordinary platform thread. When the virtual thread waits, the JVM copies its stack frames to the heap and unmounts it, and the carrier picks up another virtual thread. After waking up, the thread may continue on a different carrier.

Carriers belong to a dedicated ForkJoinPool in FIFO mode (not commonPool()). By default there are as many as available processors; you change the number with -Djdk.virtualThreadScheduler.parallelism=N, while jdk.virtualThreadScheduler.maxPoolSize caps temporary growth of the pool.

Operations that unmount: sleep(), join(), BlockingQueue.take(), Lock.lock(), await() on synchronizers, Future.get(), network I/O. Most file operations, and on Java 21–23 Object.wait(), cannot release the carrier; then the scheduler temporarily adds another carrier.

Code cannot see its carrier: Thread.currentThread() returns the virtual thread itself, and the carrier shows up only in toString(), for example VirtualThread[#21,w-0]/runnable@ForkJoinPool-1-worker-1.

4. 

What is virtual thread pinning and what changed in Java 24?

Pinning is the situation where a virtual thread blocks but the JVM cannot unmount it, so the carrier sits idle along with it. Unlike file I/O, pinning gets no compensation: the scheduler does not add an extra carrier.

  • Java 21–23: a thread is pinned when it blocks inside a synchronized block or method, or inside a native method.
  • Java 24 and later (JEP 491): synchronized no longer pins the thread; native methods and calls through the Foreign Function API still do.

Pinning is not a bug: the program still produces correct results, but if every carrier is held by a pinned thread, the other virtual threads wait while the CPU is idle. That is why on Java 21–23 synchronized around long waits (network, sleep(), wait()) is replaced with ReentrantLock. Short critical sections with no waiting are not hurt by pinning, and on Java 24+ there is no need to rewrite synchronized for virtual threads.

5. 

How do you detect virtual thread pinning and take a thread dump that shows virtual threads?

Pinning:

  • on Java 21–23, the system property -Djdk.tracePinnedThreads=full (or =short): when a pinned virtual thread blocks, the JVM prints its stack with the reason (reason:MONITOR) and marks the frame holding the monitor (<== monitors:1). Java 24 removed the property;
  • on any version from 21 onward, the JDK Flight Recorder event jdk.VirtualThreadPinned, recorded by default for pinning longer than 20 ms. It suits production better: no debug flag is needed, and you get the duration and the stack.
java -XX:StartFlightRecording=filename=rec.jfr App
jfr print --events jdk.VirtualThreadPinned rec.jfr

Thread dump: jstack and Thread.getAllStackTraces() show only platform threads, that is, the carriers. A dump with every virtual thread is taken with jcmd:

jcmd <pid> Thread.dump_to_file -format=text threads.txt
jcmd <pid> Thread.dump_to_file -format=json threads.json

A classic dump with monitors for a million threads would take gigabytes, so virtual threads got a separate format; the JSON version is easy to process programmatically.

6. 

When do virtual threads not make a program faster?

Virtual threads increase throughput, meaning how many tasks can be in flight at once, and only when the tasks mostly wait. They do not help when:

  • tasks are compute-heavy (CPU-bound): the code runs the same instructions on the same cores, and as many threads run at once as there are cores. 2,000 tasks of 100 ms CPU time take at least 25 seconds on 8 cores on any kind of thread;
  • computation is mixed with I/O tasks: the scheduler does not preempt a virtual thread on a time slice, so long-computing threads hold the carriers while tasks that already got their network response wait. Hand computation to a separate pool of platform threads sized around the core count;
  • there are only a few concurrent tasks: a service with 50 concurrent requests is fine with an ordinary pool; virtual threads pay off with thousands of waiting tasks;
  • the bottleneck is not threads: the CPU, the database, the connection pool. The database response time does not depend on the kind of thread.
7. 

What should you not do with virtual threads?

Habits that made sense for expensive platform threads work against you with virtual ones, because a virtual thread lives for exactly one task:

  • Do not pool them. newFixedThreadPool(100, Thread.ofVirtual().factory()) works, but runs no more than 100 tasks at once. Use newVirtualThreadPerTaskExecutor(), one thread per task.
  • Do not rely on pool size to limit the load on a resource. After switching to virtual threads the implicit pool limit is gone, and 10,000 tasks hit the database at once. Bring the limit back explicitly: a Semaphore sized to the allowed number of calls, acquire() before the call, release() in finally. A thread waiting for a permit is unmounted and does not occupy a carrier.
  • Do not cache heavy objects in a ThreadLocal. The cache is rebuilt for every task, and a million threads means a million copies. Use a shared thread-safe object (DateTimeFormatter) or an explicit object pool. -Djdk.traceVirtualThreadLocals shows where virtual threads write to a ThreadLocal.
  • On Java 21–23, do not keep synchronized around network calls (pinning); do not run computation on virtual threads; do not look for them in jstack.

If you feel the urge to limit "the number of threads", what you actually need to limit is something else (connections, API calls, memory), so limit that directly.

8. 

What are StructuredTaskScope and ScopedValue, and in which Java versions are they available?

StructuredTaskScope implements structured concurrency: subtasks started inside a block must finish before the block exits; if one fails, the others are cancelled and the error propagates to the caller. With a plain ExecutorService you have to cancel the second task by hand after the first one fails. By default each subtask gets its own virtual thread. Status: preview since Java 21 (JEP 453); Java 25 ships the fifth preview (JEP 505) with a reworked API. It compiles only with --enable-preview on the matching JDK, so check the documentation for your version before using it.

ScopedValue replaces ThreadLocal for passing immutable context down the call chain: the value is bound for the duration of a block, is visible to StructuredTaskScope subtasks and is not copied into every thread. Status: preview in Java 21 (JEP 446), final API in Java 25 (JEP 506). On Java 21 without preview flags you are left with ThreadLocal.

Virtual threads themselves: preview in Java 19 (JEP 425) and 20 (JEP 436), final in Java 21 (JEP 444), no more pinning in synchronized since Java 24 (JEP 491).

Page 1 of 1