Virtual thread fundamentals
What you will learn
A virtual thread is a Java Thread scheduled by the runtime onto carrier platform threads. It can suspend during many blocking operations, allowing the carrier to run other work. It is useful for large numbers of independent waiting tasks, not a way to make arithmetic run faster.
- Create and identify virtual and platform threads.
- Use a virtual-thread-per-task executor for a finite set of jobs.
- Explain mounting, unmounting and the limits of virtual threads.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. The stable examples use finite submissions, cooperative tasks and executor ownership. The fixture runner also enforces a process deadline.
Identify the two thread kinds
import java.util.*;import java.util.concurrent.*;import java.util.concurrent.atomic.*;public class Main {
public static void main(String[] args) throws Exception { AtomicBoolean result = new AtomicBoolean(); Thread t = Thread.ofVirtual().name("lookup").start(() -> result.set(Thread.currentThread().isVirtual())); t.join(3000); if (t.isAlive()) { t.interrupt(); throw new AssertionError("join deadline"); } System.out.println(result.get()); System.out.println(Thread.currentThread().isVirtual()); }}Expected output:
truefalseThe main thread is a platform thread for this ordinary launcher. Join establishes visibility of completed actions.
A thread is not a processor
Platform threads typically correspond to operating-system threads. Virtual threads are mounted on carrier threads while executing and can unmount when supported blocking operations park them. A virtual thread may resume on a different carrier. Thread.currentThread() still identifies the virtual thread. CPU-bound tasks still compete for CPU cores. Virtual threads are daemon threads; keep the owning operation alive until they finish.
One task, one virtual thread
Thread.ofVirtual() provides a builder; startVirtualThread starts a task immediately. A virtual-thread-per-task executor creates a new thread for each submitted task, not a reusable worker pool. This executor has no intrinsic submission bound; use a finite batch or admission control. Use try-with-resources and cooperative, bounded tasks. Keep results and failures in futures rather than relying on interleaved prints.
Thread-local state
ThreadLocal works with virtual threads, but per-thread caches can grow with the number of tasks. Do not treat a virtual thread as a reusable database connection cache. Remove values when their lifetime ends, especially on reused platform workers. Prefer explicit immutable context or version-appropriate scoped values.
Run independent quote calculations
import java.util.*;import java.util.concurrent.*;import java.util.concurrent.atomic.*;public class Main {
public static void main(String[] args) throws Exception { try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { Future<Integer> a = executor.submit(() -> 12 * 3); Future<Integer> b = executor.submit(() -> 8 * 2); System.out.println(a.get(3, TimeUnit.SECONDS) + b.get(3, TimeUnit.SECONDS)); } }}Expected output:
52Each task has a separate virtual thread. The caller collects results in a fixed order. This small calculation proves correctness, not a throughput benefit.
Check thread identity across tasks
import java.util.*;import java.util.concurrent.*;import java.util.concurrent.atomic.*;public class Main {
public static void main(String[] args) throws Exception { try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { Future<Thread> a = executor.submit(Thread::currentThread); Future<Thread> b = executor.submit(Thread::currentThread); Thread first = a.get(3, TimeUnit.SECONDS), second = b.get(3, TimeUnit.SECONDS); System.out.println(first.isVirtual() && second.isVirtual()); System.out.println(first != second); } }}Expected output:
truetrueThe two results refer to distinct threads, even if execution happens sequentially.
Keep request state separate
import java.util.*;import java.util.concurrent.*;import java.util.concurrent.atomic.*;public class Main {
public static void main(String[] args) throws Exception { ThreadLocal<String> context = new ThreadLocal<>(); context.set("caller"); try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { System.out.println(executor.submit(() -> { context.set("job"); try { return context.get(); } finally { context.remove(); } }).get(3, TimeUnit.SECONDS)); System.out.println(context.get()); } finally { context.remove(); } }}Expected output:
jobcallerOrdinary ThreadLocal is per thread; the worker does not overwrite the caller binding.
Common mistakes
Do not start a virtual daemon thread and immediately exit main expecting it to finish. Do not use a virtual-thread pool as a concurrency limiter. Do not assume virtual threads remove data races or accelerate CPU-bound work.
Practice
Submit three independent integer tasks (2, 4, 6), return their squares, and collect their sum in the owner. Use a virtual-thread-per-task executor with finite submission and bounded gets.
Expected output:
56Compare your answer with the manual practice criteria.
Official reading: Thread · Executors · Virtual threads. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Virtual thread fundamentals — knowledge check
Original virtual-thread and versioned concurrency questions.
What is a carrier?
What does a virtual-thread-per-task executor create?
What improves for suitable blocking workloads?
Can a virtual thread keep an otherwise finished JVM alive?
Why avoid large ThreadLocal caches on virtual threads?