Repaso
EspaƱol
Java CoreAdvancedJV-30

What problem do virtual threads (Java 21) solve?

Options

  1. They make CPU-heavy code run faster on more cores
  2. Simple blocking code scaled to huge numbers of tasks (Correct option)
  3. They replace the garbage collector with a cheaper one
  4. They remove the need for synchronization in shared code

Answer

They let you write simple blocking code while handling hundreds of thousands of concurrent tasks, because they are very cheap and the JVM, not the OS, schedules them

Why

A normal (platform) thread maps 1:1 to an OS thread and is expensive, so a server can only have a few thousand. When a thread waits for I/O (database, HTTP), it just sits there wasting its slot.

Virtual threads are lightweight threads managed by the JVM. When one blocks on I/O, the JVM parks it and runs another on the same OS thread. You can create millions.

They help with I/O-bound workloads (typical web services). They do NOT speed up CPU-bound work, and you still need to protect shared data.

try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
    ex.submit(() -> callSlowService());
}

Remember

Virtual threads = cheap blocking for I/O-heavy servers.

Key terms

Practice this question in Repaso