CodeGym /Courses /JAVA 25 SELF /Threads vs virtual threads: differences and advantages

Threads vs virtual threads: differences and advantages

JAVA 25 SELF
Level 57, Lesson 0
Available

1. Classic threads: how it works and where it hurts

Let’s first recall how regular threads in Java work (also called platform or native threads). The very ones created via new Thread(...).

When you call new Thread(() -> { ... }).start();, the JVM doesn’t just run a piece of code. It asks the operating system to create a real execution thread. The OS allocates a separate stack (usually several megabytes) and reserves other housekeeping resources.

Such a thread lives as long as its task runs, and during that time it occupies a slot in the operating system’s thread table. The more of these threads you have, the more memory goes to their stacks and the higher the load on the OS. That’s why, with a large number of concurrently running threads, an application can start to “choke” — the system spends too much time switching between them.

Example: a classic thread

Thread thread = new Thread(() -> {
    System.out.println("Hello from a thread!");
});
thread.start();

Looks simple, right? But try to create not one or two, but say ten thousand such threads — and your program will quickly start choking. You’ll either run out of memory or hit the OS thread limit. This isn’t a Java bug, but a natural consequence of the architecture: threads are heavy and expensive.

Why does this happen? Each thread gets its own stack (typically 1–2 megabytes), plus a set of OS-managed structures. And the OS isn’t thrilled when you hand it tens of thousands of threads — it has limits, and they can be quite strict.

Even if you don’t run out of memory, another problem appears — context switching. When there are too many threads, the system constantly jumps between them, saving and restoring their state. That takes time and eats into performance, so you don’t get any benefit from “mass parallelisation.”

The “thread‑per‑request” problem

In older server applications (for example, on Tomcat or Jetty) the “thread‑per‑request” model was common: a separate thread was allocated for each incoming user request. It’s convenient, but if you have 10_000 users, you need 10_000 threads! The server struggles, and you end up racing against memory limits rather than improving request throughput.

Bottom line:
Classic threads are good for a small number of parallel tasks, but they don’t scale to tens or hundreds of thousands.

2. What are virtual threads (Virtual Threads)?

Here’s where today’s hero appears — virtual threads. This isn’t “just another thread,” but a fundamentally different architectural idea.

Virtual threads are threads managed not by the operating system, but by the JVM itself. They’re implemented entirely within Java and can be created in huge numbers (tens or hundreds of thousands) without bloating memory or slowing down.

In short:

  • Platform Thread (platform thread): a regular thread that directly maps to an OS thread.
  • Virtual Thread (virtual thread): a lightweight thread managed by the JVM, not the OS.

How does it work?

Virtual threads are “lightweight” threads that live not in the operating system, but inside the JVM. They run on top of a small pool of real threads, called platform threads. You can imagine the JVM conducting them like an orchestra: it has a limited number of musicians (real threads), but skillfully distributes parts among them (virtual threads).

Architecture diagram:

+-------------------+           +-------------------+
|  Virtual Thread 1 |---\       |  Platform Thread  |
|  Virtual Thread 2 |---->====> |  (Carrier Thread) |
|  Virtual Thread 3 |---/       +-------------------+
         ...                        (Operating system)

A Carrier Thread is a regular OS thread on which the JVM executes many virtual threads. If a virtual thread suddenly blocks — for example, while waiting for data from disk or network — the JVM simply “parks” it, freeing the carrier thread for other tasks.

Why is this revolutionary?

Because you can now write familiar, linear code — without endless callbacks, CompletableFuture, and hellish thenApply chains — while scaling the application to thousands of concurrent operations.

Virtual threads take only tens of kilobytes (instead of megabytes for regular ones) and are created almost instantly. So you can start and tear them down by the thousands without worrying that the operating system will buckle under their weight. This finally makes parallel programming in Java easy and natural.

3. Advantages of virtual threads

Scalability

With virtual threads, you can afford to run tens or hundreds of thousands of parallel tasks. For example, handle each network request in a separate thread — without worrying that the server will “burst.”

Demo: 100,000 virtual threads

for (int i = 0; i < 100_000; i++) {
    Thread.ofVirtual().start(() -> {
        // Any logic can be here
        try {
            Thread.sleep(1000); // Simulating work
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    });
}
System.out.println("All threads started!");

This code runs just fine on a regular laptop!
Try doing the same with regular threads — you’ll see an OutOfMemoryError or turn your machine into a brick.

Ease of programming

Virtual threads let you write familiar “blocking” code without turning it into spaghetti made of asynchronous calls. For example, you can safely use Thread.sleep, InputStream.read, Socket.accept — the JVM will ensure the carrier thread isn’t blocked.

Improved readability and maintainability

Instead of complex schemes with callbacks and CompletableFuture, you write linear, understandable code. This reduces bugs and makes maintenance easier.

No need to reinvent the wheel

Previously, to handle thousands of requests in parallel, you had to use asynchronous frameworks and reactive libraries (Netty, Vert.x, Project Reactor) that require a special programming style. Now you can do without them and still get scalability.

4. Architecture: how virtual threads work “under the hood”

Mapping to carrier threads

The JVM creates a small pool of real threads (carrier threads) — usually as many as there are CPU cores. All virtual threads “ride” on these carrier threads, like passengers on buses.

  • When a virtual thread blocks (for example, waiting for a network response), the JVM “unmounts” it from the carrier thread and queues it.
  • As soon as the thread can continue, the JVM “mounts” it back on a free carrier thread.

Analogy:
Imagine you have 4 taxis (carrier threads) and you serve 10,000 clients (virtual threads). As soon as one client arrives and exits, a taxi immediately picks up the next one. Nothing sits idle, and the taxis don’t break under the weight of passengers.

Scheduling and switching

The JVM decides on its own which virtual thread to run at any given moment. If a thread blocks on I/O, it doesn’t prevent other threads from running.

5. Limitations and caveats of virtual threads

Not everything virtual is golden

Not for long computations: If you have a task that continuously occupies the CPU (heavy CPU‑bound), a virtual thread won’t improve performance. Carrier threads are still limited by the number of cores.

Some locks are inefficient: Older synchronisation mechanisms (for example, synchronisation via synchronized on objects backed by native mutexes) may prevent the JVM from parking a virtual thread. In such cases, the carrier thread will wait along with the virtual thread, reducing scalability.

Not all libraries play nicely with virtual threads: If a library makes native calls or uses specific locks, virtual threads may not behave as expected.

Example: when you shouldn’t use Virtual Threads

If you have a task that spins in an endless loop and just crunches numbers, a virtual thread gives no benefit. You’re still limited by the number of cores.

Thread.ofVirtual().start(() -> {
    while (true) {
        // Counting to infinity
    }
});

Result:
One carrier thread will be occupied by this virtual thread, and other tasks will have to wait their turn.

6. Comparison: Platform Thread vs Virtual Thread

Characteristic Platform Thread (Regular) Virtual Thread (Virtual)
Managed by Operating system JVM
Memory per thread Megabytes Tens of kilobytes
Number of threads Usually < 10_000 Thousands, hundreds of thousands
Cost of creation Expensive Cheap
Scalability Limited Almost unlimited
Best suited for Long tasks, CPU‑bound Short, I/O‑bound tasks
Thread switching OS JVM
Compatibility 100% Almost always, but with caveats

7. Example: how a server would look before and after Virtual Threads

Before (Platform Threads)

ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
    Socket client = serverSocket.accept();
    new Thread(() -> handleClient(client)).start();
}

Problem:
After around 5,000 connections, the server starts to choke.

After (Virtual Threads, Java 21+)

ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
    Socket client = serverSocket.accept();
    Thread.ofVirtual().start(() -> handleClient(client));
}

The magic:
Now you can handle tens of thousands of connections — without worrying about thread limits!

9. Common mistakes when moving to virtual threads

Mistake #1: Expecting speedups for compute‑bound tasks. Virtual threads don’t speed up tasks that fully saturate the CPU. For such tasks, you’re still limited by the number of cores.

Mistake #2: Using legacy blocking synchronisations. If you use old locks (for example, synchronized on objects that can be locked natively), virtual threads may not be unmounted from the carrier thread, losing their advantages.

Mistake #3: Ignoring third‑party library behaviour. Some third‑party libraries may not be ready for virtual threads (for example, if they use JNI or native locks).

Mistake #4: Expecting magical performance gains. Virtual threads aren’t a silver bullet. They don’t speed up everything; they make parallelism cheap and convenient for I/O‑bound tasks.

1
Task
JAVA 25 SELF, level 57, lesson 0
Locked
Launching the secret messenger 💬
Launching the secret messenger 💬
1
Task
JAVA 25 SELF, level 57, lesson 0
Locked
Preparing to Launch a Drone Fleet 🚀
Preparing to Launch a Drone Fleet 🚀
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION