Command Palette

Search for a command to run...

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

Protect a scarce resource with a Semaphore

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?

Protect a scarce resource with a Semaphore 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

200 queries done; at most 5 connections at once: true