Junior — Middle
What are the differences between virtual threads and system threads in programming?
sobes.tech AI
Answer from AI
System threads (native threads) — are threads managed by the operating system. Each such thread corresponds to one system thread, and switching between them occurs at the OS level. They have overhead costs for creation and context switching.
Virtual threads — are lightweight threads implemented at the JVM level, not directly tied to system threads. They allow creating thousands and millions of threads with minimal resource costs, as scheduling and switching between them happen within the JVM.
Main differences:
- Virtual threads are easier and faster to create.
- Virtual threads allow more efficient resource utilization when handling a large number of parallel tasks.
- System threads provide a lower level of control and interact directly with the OS.
Example of using virtual threads (Java 19+):
Thread.startVirtualThread(() -> {
System.out.println("Virtual thread is running");
});