Skip to content

Java Virtual Thread Usage

What is Virtual thread?

A Java platform thread is mapped to OS Kernel thread, as the resource is limited, we can't create as many as platform threads as we want.

Even Java provides executor pool, it also can't handle some cases. For example, if we want to create thoudsands of IO tasks, virtual threads is more suitable than platform threads.

For Java virtual thread,

  • VirtualThread is subclass of the Thread

    So, we also can use the methods like start, join of the Thread

  • Unlike platform thread, virtual thread runs Java code on an underlying OS thread but does not capture the OS thread for the code's entire lifetime

    This means that many virtual threads can run their Java code on the same OS thread, effectively sharing it.

  • Virtual thread is more lightweight that platform thread

    The number of virtual threads can be much larger than the number of OS threads.

  • We can use Thread.isVirtual() to check if a thread is a virtual thread

How to Use Java Virtual Thread

  • Create a simple virtual thread

    The VirtualThread runs in a default ForkJoinPool

    Java
    var vThread = Thread.startVirtualThread(()-> System.out.println("I am virtual thread!!!"));
    vThread.join();
    System.out.println("Main thread end");
    

    The output is:

    Bash
    I am virtual thread!!!
    Main thread end
    
  • Using an Executor

    Java
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        IntStream.range(0, 10_000).forEach(i -> {
            executor.submit(() -> {
                Thread.sleep(Duration.ofSeconds(1));
                return i;
            });
        });
    }
    

    If we try to create same number of platform threads, the app will crash.