SoFunction
Updated on 2025-03-08

The specific use of virtual threads in Java19 new features

Java 19 introduces Virtual Threads, an important new feature in the JDK Project Loom project. The purpose is to simplify concurrent programming in Java and improve the efficiency and performance of thread management. The introduction of virtual threads is aimed at coping with the bottlenecks of the traditional Java threading model, making thread management in high concurrency scenarios lighter and more efficient, thereby improving the system's concurrency processing capabilities.

1. Background: Limitations of Java threading model

In Java, traditional threads (also known as platform threads) correspond directly to threads of the operating system. When an application creates a new thread, it is actually allocating a new thread at the operating system level. Although this method works well in simple concurrency scenarios, it has the following limitations in scenarios with high concurrency and large I/O operations:

  • High thread overhead: Each Java thread will take up a lot of memory, especially each thread has its own stack space (1MB by default). This means that when creating a large number of threads, the memory consumption is very high.
  • High context switching cost: The operating system needs to perform context switching between different threads, and context switching is an overhead operation. When the number of threads is large, frequent context switching can significantly affect performance.
  • Blocking operations affect thread utilization: In traditional threading models, blocking operations (such as I/O operations) will cause the thread to be suspended until the operation is completed. This results in very low thread utilization in high concurrency I/O intensive scenarios.

To improve these problems, Java 19 introducedVirtual threadThe concept of   greatly reduces the complexity and overhead of concurrent programming.

2. What are Virtual Threads?

Virtual threadis a new lightweight thread that is different from traditional operating system threads. Virtual threads are managed by Java virtual machines (JVMs). Compared with traditional threads, virtual threads are lighter and can be created and scheduled at scale within the JVM without posing too much burden on operating system resources.

The core goals of virtual threads are:

  • High concurrency: Supports higher concurrency on the basis of maintaining the same programming model as traditional threads. The creation cost and resource consumption of virtual threads are very low, and developers can create millions of virtual threads in their applications.
  • Simplify the concurrency model: Virtual threading allows developers to continue to use familiar threading models, but at the same time enjoy higher concurrency efficiency without having to deal with complex thread pools and asynchronous programming models.

3. How virtual threads work

Virtual threads achieve lightweight by decoupling thread blocking from operating system threads. When a virtual thread blocks, the operating system thread will not stagnate. The JVM will manage the blocking and scheduling of virtual threads in the background, thereby greatly reducing resource waste.

The implementation of virtual threads is based on the following key mechanisms:

  • Thread decoupling: The virtual thread is decoupled from the operating system thread (platform thread). Virtual threads can be scheduled to the operating system thread at any time during runtime. When the virtual thread blocks, the operating system thread will be released for other tasks.
  • Cooperative Scheduling: The JVM is responsible for scheduling virtual threads and mapping them to a limited number of operating system threads. In this way, virtual threads can exist in large quantities without putting pressure on the underlying operating system thread resources.

4. Comparison between virtual threads and traditional threads

characteristic Traditional Threads Virtual Threads
Management method Directly managed by the operating system, each thread consumes OS resources Managed by JVM, lightweight, and does not occupy OS resources
Creation overhead Creation costs are high, and thread pools are usually required to reuse threads. Low creation cost, can create a large number of virtual threads
Memory consumption Each thread consumes a lot of memory (stack space) Each virtual thread stack consumes little and is almost negligible
Context Switching Relying on the operating system for context switching, high overhead JVM internal scheduling, low overhead
Blocking operation Blocking operations will occupy system resources Blocking operations are managed by the JVM and do not affect OS threads
Applicable scenarios Suitable for moderate concurrent task processing Suitable for high concurrency, high I/O intensive scenarios

5. How to use virtual threads

Java 19 provides a new API to create and manage virtual threads. Virtual thread creation is similar to traditional threads, but is lighter and more efficient.

5.1 Create a virtual thread

Can be passed().start()or()To start a virtual thread.

public class VirtualThreadExample {
    public static void main(String[] args) {
        // Create a virtual thread and start        Thread virtualThread = ().start(() -> {
            ("The virtual thread starts running");
        });
        
        // Wait for the virtual thread to complete        try {
            ();
        } catch (InterruptedException e) {
            ();
        }
    }
}

In this example, we pass().start()The method creates a virtual thread and performs a simple task.

5.2 Use virtual threads to execute concurrent tasks

Virtual threads are particularly suitable for highly concurrent tasks, such as handling large numbers of I/O requests. The following example shows how to use a virtual thread to handle multiple concurrent tasks.

import ;

public class VirtualThreadExample {
    public static void main(String[] args) throws InterruptedException {
        // Start 1000 virtual threads to execute tasks concurrently        var threads = (0, 1000)
                .mapToObj(i -> (() -> {
                    ("Task " + i + "Start Run");
                    try {
                        (1000); // Simulate I/O operations                    } catch (InterruptedException e) {
                        ();
                    }
                })).toList();

        // Wait for all threads to complete        for (var thread : threads) {
            ();
        }

        ("All tasks are completed");
    }
}

In this example, we started 1,000 virtual threads to process tasks concurrently. Such a task scenario is extremely overhead under the traditional thread model, but it can be easily dealt with through virtual threads.

5.3 Execute virtual threads using ExecutorService

Virtual threads can be used withExecutorServiceUse it in conjunction with more complex concurrent task management. Java 19 can be passed()Create virtual thread-basedExecutorService

import ;
import ;

public class VirtualThreadExecutorExample {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = ();
        
        // Submit multiple tasks        for (int i = 0; i < 1000; i++) {
            int taskId = i;
            (() -> {
                ("Task " + taskId + "Start Run");
                try {
                    (1000); // Simulate I/O operations                } catch (InterruptedException e) {
                    ();
                }
            });
        }
        
        // Turn off the actuator        ();
    }
}

passnewVirtualThreadPerTaskExecutor(), We can easily create an executor that starts a virtual thread for each task, suitable for handling a large number of concurrent tasks.

6. Scenarios using virtual threads

Virtual threads are ideal for highly concurrency and I/O intensive scenarios, such as:

  • High concurrency web server: Virtual threads can handle hundreds of thousands or even more concurrent requests at the same time without causing excessive thread overhead.
  • Data flow processing: For example, processing data streams or message queues from multiple sources, virtual threads can easily manage thousands of concurrent connections.
  • Asynchronous I/O operation: Virtual threads are ideal for handling I/O blocking operations without the need for complex asynchronous callback models.

7. Pros and cons of virtual threads

advantage:

  • Significantly improve concurrency performance: The creation and management of virtual threads is very low and can support large-scale concurrent operations.

Keep the traditional programming model: Developers do not need to learn complex asynchronous models and can continue to write code using familiar threading models.
3. Improve resource utilization: Virtual threads reduce the waste of thread resources and can better utilize CPU and memory resources.

shortcoming:

  • Still in preview: The virtual threading function in Java 19 is still in the preview stage and there may be some restrictions or future API changes.
  • Complex task scheduling: Although the JVM has optimized the scheduling of virtual threads, in some extreme cases, additional adjustments to the scheduling policy may be required.

8. Conclusion

Virtual threading is a revolutionary feature in Java 19 that simplifies the model of concurrent programming and significantly improves performance in high concurrency scenarios. With virtual threading, Java developers can easily create millions of concurrent tasks without being restricted by traditional threading models. Although virtual threads are still in the preview stage, it demonstrates the great potential of Java in the field of high-performance concurrency in the future. With the continuous development of Project Loom, virtual threads will become a powerful tool for dealing with concurrency problems in Java development.

This is the introduction to this article about the specific use of virtual threads in Java19's new features. For more related Java19 virtual thread content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!