Class VirtualThreadUtils

java.lang.Object
dev.langchain4j.internal.VirtualThreadUtils

public class VirtualThreadUtils extends Object
Utility class for working with virtual threads introduced in Java 21.

This class provides a mechanism to create a virtual thread per task executor through reflection, enabling compatibility with both Java versions that support virtual threads and those that do not.

Author:
Konstantin Pavlov
  • Constructor Details

    • VirtualThreadUtils

      public VirtualThreadUtils()
  • Method Details

    • createVirtualThreadExecutor

      public static @Nullable ExecutorService createVirtualThreadExecutor(Supplier<@Nullable ExecutorService> fallback)
      Creates a virtual thread per task executor using reflection. This allows code to run on both Java 21+ (where virtual threads are available) and earlier Java versions.
      Parameters:
      fallback - a Supplier that provides a fallback ExecutorService when virtual threads are not available.
      Returns:
      an ExecutorService using virtual threads if supported, otherwise a fallback implementation.
    • createVirtualThreadExecutor

      public static ExecutorService createVirtualThreadExecutor()
      Creates a virtual thread per task executor, assuming virtual threads are supported.
      Returns:
      an ExecutorService using virtual threads if supported, otherwise a RuntimeException.
      Throws:
      RuntimeException - if virtual threads are not supported.
    • isVirtualThread

      public static boolean isVirtualThread()
      Checks if the current thread is a virtual thread.
      Returns:
      true if the current thread is a virtual thread, false otherwise
    • isVirtualThreadsSupported

      public static boolean isVirtualThreadsSupported()
      Checks if virtual threads are supported in the current runtime environment.
      Returns:
      true if the current runtime supports virtual threads, false otherwise.