Class VirtualThreadsExamples

java.lang.Object
net.jrodolfo.java_evolution.java21.VirtualThreadsExamples

public class VirtualThreadsExamples extends Object
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 Details

    • VirtualThreadsExamples

      public VirtualThreadsExamples()
  • Method Details

    • taskRunsInVirtualThread

      public boolean taskRunsInVirtualThread() throws InterruptedException, ExecutionException
      Runs one task in a virtual thread.
      Returns:
      whether the task observed a virtual thread
      Throws:
      InterruptedException - when waiting is interrupted
      ExecutionException - when the task fails
    • startNamedVirtualThreads

      public List<String> startNamedVirtualThreads() throws InterruptedException
      Starts several virtual threads and collects their names.
      Returns:
      virtual thread names
      Throws:
      InterruptedException - when waiting is interrupted
    • runManyBlockingVirtualThreadTasks

      public int runManyBlockingVirtualThreadTasks(int numberOfTasks) throws InterruptedException
      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