Sobes.tech
Senior

What are the differences between a native thread and a virtual thread (Java)?

sobes.tech AI

Answer from AI

In Java, a native thread is a traditional operating system thread created and managed by the JVM, but it is directly mapped to a system thread. A virtual thread, introduced with Project Loom, is a lightweight thread implemented at the JVM level, which does not correspond to a single system thread.

Main differences:

  • Resources: Native threads require significant OS resources (stack, descriptors), while virtual threads are much lighter and can be created in large numbers.

  • Scheduling: Native threads are scheduled by the OS, which can lead to overhead and context switching. Virtual threads are scheduled by the JVM, allowing for more efficient use of system threads.

  • Scalability: Virtual threads enable running millions of parallel tasks, which is difficult with native threads.

  • Blocking: When a virtual thread blocks, the JVM can switch execution to another virtual thread without blocking the system thread.

Example of creating a virtual thread (Java 19+):

Thread.startVirtualThread(() -> {
    System.out.println("Virtual thread is running");
});

Thus, virtual threads are a tool for more scalable and efficient multithreading, hiding the complexities of managing system threads.