Class VirtualThreadsExamples
java.lang.Object
net.jrodolfo.java_evolution.java21.VirtualThreadsExamples
Demonstrates virtual threads, finalized in Java 21.
Traditional platform threads are easy to program with, but each one is a relatively expensive operating-system resource. That makes simple thread-per-task code hard to scale for workloads with many blocking I/O operations.
Virtual threads solve that scalability problem while preserving the familiar blocking style. They are especially useful for request handling and network I/O where tasks spend much of their time waiting.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionintrunManyBlockingVirtualThreadTasks(int numberOfTasks) Starts many virtual threads that briefly block, then waits until all of them complete.Starts several virtual threads and collects their names.booleanRuns one task in a virtual thread.
-
Constructor Details
-
VirtualThreadsExamples
public VirtualThreadsExamples()
-
-
Method Details
-
taskRunsInVirtualThread
Runs one task in a virtual thread.- Returns:
- whether the task observed a virtual thread
- Throws:
InterruptedException- when waiting is interruptedExecutionException- when the task fails
-
startNamedVirtualThreads
Starts several virtual threads and collects their names.- Returns:
- virtual thread names
- Throws:
InterruptedException- when waiting is interrupted
-
runManyBlockingVirtualThreadTasks
Starts many virtual threads that briefly block, then waits until all of them complete.This is not a benchmark. It is a small demonstration of the design goal: virtual threads make thread-per-task code practical for many tasks that spend most of their time waiting.
- Parameters:
numberOfTasks- number of virtual threads to start- Returns:
- number of completed tasks
- Throws:
InterruptedException- when waiting is interrupted
-