Contents

Using ExecutorService, Future & invokeAll with Java Virtual Threads (JDK 21+)

Updated on 2026-10-21

Introduction: Think of Virtual Threads as Tasks, Not Pooled Resources

With traditional OS platform threads, threads are expensive operating-system resources. That scarcity trained Java developers to pool threads (Executors.newFixedThreadPool()) and share them across thousands of tasks.

With Java Virtual Threads (finalized in Java 21), that mental model flips completely: a virtual thread is as cheap as a task object itself. Instead of pooling virtual threads, you spawn a brand-new virtual thread for every single task, let it block freely on I/O, and let the Garbage Collector clean it up when done.

In this guide, we cover:

  1. Running fire-and-forget or scoped tasks with Executors.newVirtualThreadPerTaskExecutor()
  2. Returning values from virtual threads using Future<T>
  3. Running parallel batches with ExecutorService.invokeAll() vs. StructuredTaskScope
  4. Scheduling delayed or periodic virtual threads with ScheduledExecutorService

1. Using Executors.newVirtualThreadPerTaskExecutor()

Executors.newVirtualThreadPerTaskExecutor() creates an ExecutorService that spawns a fresh, unpooled virtual thread for every submitted Runnable or Callable.

Because ExecutorService extends AutoCloseable in Java 19+, you can use it inside a try-with-resources statement. The try block automatically waits for all submitted virtual threads to finish before continuing:

1
2
3
4
5
6
7
Runnable task1 = () -> System.out.println("Task 1 on " + Thread.currentThread());
Runnable task2 = () -> System.out.println("Task 2 on " + Thread.currentThread());

try (ExecutorService vte = Executors.newVirtualThreadPerTaskExecutor()) {
    vte.submit(task1);
    vte.submit(task2);
} // Automatically joins all submitted tasks before exiting the block!

Why You Should Never Pool Virtual Threads: Passing a virtual ThreadFactory into Executors.newFixedThreadPool(10, factory) or newSingleThreadExecutor(factory) defeats the entire purpose of virtual threads. As Ron Pressler and Alan Bateman emphasize, if you need to rate-limit concurrent requests to a database or third-party API, use a Semaphore instead of a thread pool.


2. Returning Values from Virtual Threads with Future<T>

Submitting a Callable<T> to newVirtualThreadPerTaskExecutor() returns a Future<T>. Calling future.get() inside a virtual thread unmounts the waiting virtual thread without blocking the underlying OS carrier thread:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try (ExecutorService vte = Executors.newVirtualThreadPerTaskExecutor()) {
    Future<String> myFuture = vte.submit(() -> {
        Thread.sleep(1000); // Unmounts virtual thread; OS carrier thread stays free!
        return "Hello from Virtual Thread!";
    });

    String result = myFuture.get();
    System.out.println("result = " + result);
} catch (ExecutionException | InterruptedException e) {
    throw new RuntimeException(e);
}

3. Running Parallel Tasks with invokeAll() vs. StructuredTaskScope

When you want to fan out multiple I/O tasks in parallel and collect all their results, you have two primary options in modern Java:

Option A: ExecutorService.invokeAll() with Virtual Threads

invokeAll() submits a collection of Callable tasks, runs each on its own virtual thread concurrently, and blocks until all futures complete:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
static List<String> invokeAllWithVirtualThreads() throws InterruptedException {
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        List<Callable<String>> tasks = List.of(
                () -> fetchFromServiceA(),
                () -> fetchFromServiceB()
        );

        List<Future<String>> futures = executor.invokeAll(tasks);

        return futures.stream()
                .map(Future::resultNow) // Safe because invokeAll() guarantees all tasks are done
                .toList();
    }
}

Option B: Fail-Fast Parallel Execution with StructuredTaskScope

With ExecutorService.invokeAll(), if the first task throws an exception after 10ms, invokeAll() still waits for the slowest task to finish before returning. If you want fail-fast cancellation, use Structured Concurrency (StructuredTaskScope.ShutdownOnFailure):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
static String invokeAllWithStructuredConcurrency() throws ExecutionException, InterruptedException {
    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
        var taskA = scope.fork(() -> fetchFromServiceA());
        var taskB = scope.fork(() -> fetchFromServiceB());

        scope.join().throwIfFailed();

        return taskA.get() + " + " + taskB.get();
    }
}

4. Using ScheduledExecutorService with Virtual Threads

What if you want to schedule delayed or periodic tasks on virtual threads? You can pass a virtual ThreadFactory into Executors.newScheduledThreadPool(0, factory) with corePoolSize = 0 so idle threads aren't pooled:

1
2
3
4
5
6
7
8
9
ThreadFactory factory = Thread.ofVirtual().name("scheduled-vt-", 0).factory();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(0, factory);

Callable<String> delayedTask = () -> {
    System.out.println("Executed on: " + Thread.currentThread());
    return "Done";
};

scheduler.schedule(delayedTask, 1, TimeUnit.SECONDS);

Conclusion & Further Reading

Thinking of virtual threads as lightweight, disposable tasks—rather than scarce OS resources that must be pooled—unlocks clean, high-throughput concurrent code with standard ExecutorService and Future APIs.

Explore more concurrency deep dives:

🚀 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 & Talks

Want 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:

David Vlijmincx
David Vlijmincx

Senior Java Performance & Concurrency Engineer with 10+ years of production JVM experience. International speaker with 35+ talks at Devoxx, P99 CONF, JFokus, JavaZone, and Devnexus, creator of JUring (Linux io_uring for Java), and enterprise Java workshop trainer.