Multithreading & ConcurrencyBeginner
1Question 1 of 1
javaHow does Java handle multithreading and what are Virtual Threads (Project Loom)?
Explanation & Concept
Traditionally, every `java.lang.Thread` mapped 1:1 to an operating system kernel thread, consuming ~1MB of stack memory and making millions of concurrent threads impractical.
Java 21 introduced **Virtual Threads**: lightweight, JVM-managed user-mode threads that run on a small pool of carrier OS threads. When a virtual thread blocks on socket I/O, the JVM unmounts it and runs another task, allowing millions of concurrent tasks with standard blocking code.
Code Example
java
import java.util.concurrent.Executors;
public class VirtualThreadDemo {
public static void main(String[] args) {
// Create an executor that spawns a virtual thread per task
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
final int taskId = i;
executor.submit(() -> {
Thread.sleep(100); // Does NOT block an OS thread!
return "Task " + taskId + " complete";
});
}
} // Automatically waits for all 10,000 tasks to finish!
System.out.println("All virtual threads finished!");
}
}How It Works & Key Takeaways
Spawning 10,000 platform threads would exhaust OS memory. Virtual threads consume only bytes of RAM and yield carrier threads during `Thread.sleep` or I/O.
Mock Test · 1 Questions · Optional
Ready for Generics?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate2 questions