Command Palette

Search for a command to run...

Back to the lesson: Topic 13.10 — Virtual Threads
Core Java · Example 1 of 3 Java 21+

Ten thousand blocking tasks

With 10,000 platform threads this would use gigabytes of stack; with virtual threads it finishes in well under a second on a normal laptop.

Virtual threads (Java 21, JEP 444) are threads managed by the JVM instead of the operating system. They're so cheap that you can start one per task, even a million of them, and write simple blocking code that scales like asynchronous code.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a program that starts 1,000 virtual threads with Thread.ofVirtual(), each adding 1 to an AtomicInteger, joins them all and prints the total.

Explain it without notes

01

What is a virtual thread and how is it different from a platform thread?

02

Why don't virtual threads speed up CPU-bound work?

03

How should you limit concurrency when using virtual threads?

Ten thousand blocking tasks Java 21+
This example needs Java 21+. The in-browser compiler is Java 17: install JDK 21 or newer and run it with "java Main.java".

Expected output

10,000 tasks finished, sum = 49995000