Category: java
What Are Virtual Threads?
Published on 27 Oct 2026
Explanation
Virtual threads are lightweight threads finalized in Java 21. They make it practical to create many concurrent tasks, especially tasks that spend time waiting on blocking I/O. They do not make CPU-bound work execute faster by themselves.
Code:
public class VirtualThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.startVirtualThread(() -> System.out.println("Hello from a virtual thread"));
t.join();
}
}
Explanation
Thread.ofVirtual() creates a virtual-thread builder. Virtual threads are scheduled by the Java runtime over a smaller set of platform threads, reducing the per-thread overhead for many blocking tasks.
Code:
public class VirtualThreadBuilderDemo {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.ofVirtual().name("virtual-worker").start(() ->
System.out.println(Thread.currentThread()));
t.join();
}
}
Explanation
Executors.newVirtualThreadPerTaskExecutor() creates an executor that starts a new virtual thread for each submitted task. Close the executor or shut it down to wait for submitted tasks to finish.
Code:
import java.util.concurrent.*;
public class VirtualThreadExecutorDemo {
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> result = executor.submit(() -> "Task completed");
System.out.println(result.get());
}
}
}
Explanation
Platform threads are backed more directly by operating-system threads and are suitable for many workloads. Virtual threads are lightweight and useful for high-concurrency blocking workloads. Choose based on workload and measure real application behavior.
Code:
import java.util.concurrent.*;
public class VirtualVsPlatformDemo {
public static void main(String[] args) throws Exception {
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 3; i++) {
int id = i;
pool.submit(() -> System.out.println("Request " + id));
}
}
}
}
Explanation
Avoid pooling virtual threads merely to limit thread creation; create one per task and use semaphores or other resource-specific limits when necessary. Virtual threads do not increase CPU capacity, and blocking or synchronized code should be reviewed for the target JDK's behavior.
Code:
import java.util.concurrent.*;
import java.util.concurrent.Semaphore;
public class VirtualThreadLimitDemo {
private static final Semaphore API_LIMIT = new Semaphore(10);
static void callExternalApi() throws InterruptedException {
API_LIMIT.acquire();
try { System.out.println("External API call"); }
finally { API_LIMIT.release(); }
}
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> { try { callExternalApi(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } });
}
}
}