GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • β†’

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev β€” Virtual thread executor | java.evolved

Home / Streams / Virtual thread executor
Streams Intermediate

Virtual thread executor

  • πŸ› Report a code issue
  • 🌐 Report a translation issue
  • πŸ’‘ Suggest a new pattern

Use virtual thread executors for unlimited lightweight concurrency.

Virtual Threads Concurrency
Code Comparison
βœ• Java 8
ExecutorService exec =
    Executors.newFixedThreadPool(10);
try {
    futures = tasks.stream()
        .map(t -> exec.submit(t))
        .toList();
} finally {
    exec.shutdown();
}
βœ“ Java 21+
try (var exec = Executors
        .newVirtualThreadPerTaskExecutor()) {
    var futures = tasks.stream()
        .map(exec::submit)
        .toList();
}
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
♾️

No sizing

No pool size to tune β€” create as many threads as needed.

⚑

Lightweight

Virtual threads use KB of memory, not MB.

🧹

Auto-closeable

try-with-resources handles shutdown automatically.

Old Approach
Fixed Thread Pool
Modern Approach
Virtual Thread Executor
Since JDK
21
Difficulty
Intermediate
JDK Support
Virtual thread executor
Available

Widely available since JDK 21 LTS (Sept 2023)

How it works

The virtual thread executor creates a new virtual thread for each task. No pool sizing needed β€” virtual threads are cheap enough to create millions of them.

Related Documentation
Executors.newVirtualThreadPerTaskExecutor() β†— Virtual Threads (JEP 444) β†—
Proof
View proof source β†—
Related patterns
Streams Advanced

Stream gatherers

Java 8
// Sliding window: manual implementation
List<List<T>> windows = new ArrayList<>();
for (int i = 0; i <= list.size()-3; i++) {
    windows.add(
        list.subList(i, i + 3));
}
Java 24+
var windows = stream
    .gather(
        Gatherers.windowSliding(3)
    )
    .toList();
Hover to see modern ➜
JDK 24+ β†’
Streams Intermediate

Stream.iterate() with predicate

Java 8
Stream.iterate(1, n -> n * 2)
    .limit(10)
    .forEach(System.out::println);
// can't stop at a condition
Java 9+
Stream.iterate(
    1,
    n -> n < 1000,
    n -> n * 2
).forEach(IO::println);
// stops when n >= 1000
Hover to see modern ➜
JDK 9+ β†’
Streams Beginner

Optional.ifPresentOrElse()

Java 8
Optional<User> user = findUser(id);
if (user.isPresent()) {
    greet(user.get());
} else {
    handleMissing();
}
Java 9+
findUser(id).ifPresentOrElse(
    this::greet,
    this::handleMissing
);
Hover to see modern ➜
JDK 9+ β†’
You are visitor 01402503 β€” GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800Γ—600. No cookies required.