Sobes.tech
Senior

Java 21 — virtual threads, have you worked with them?

sobes.tech AI

Answer from AI

In Java 21, the concept of virtual threads has been introduced — lightweight threads managed not by the OS, but by the JVM. They allow creating millions of parallel tasks with minimal resource costs, significantly simplifying the writing of concurrent code.

Virtual threads integrate with the existing thread API, but their creation and switching are much cheaper compared to traditional OS threads.

Example of creating a virtual thread:

Thread.startVirtualThread(() -> {
    System.out.println("Virtual thread is running");
});

They are convenient for IO-bound tasks, where there is a lot of waiting, such as network requests or database operations. They allow writing code in a synchronous style but with the scalability of asynchronous code.

I have worked with virtual threads in test projects, evaluating their performance and convenience, especially in the context of server applications with a large number of simultaneous connections.

Java 21 — virtual threads, have you worked with them… - sobes.tech