Home > Enterprise >  What is the difference between green threads and virtual threads?
What is the difference between green threads and virtual threads?

Time:12-02

Green Threads have been implemented with Java 1.1 and dropped in subsequent Java versions, according to https://en.wikipedia.org/wiki/Green_thread.

Java 19 introduced Virtual Threads as a preview feature. https://openjdk.org/jeps/425

Both threads seem to work in User Space and not in Kernel Space as Javas Native Threads do.

What's the difference between them, and are the previous limitations of Green Threads omitted with the new Virtual Threads?

CodePudding user response:

Short Answer:

Green Threads had an N:1 mapping with OS Threads. All the Green Threads ran on a single OS Thread. With Virtual Threads, multiple virtual threads can run on multiple native threads (n:m mapping)

A bit more details from the JEP 425

  • Java's green threads all shared one OS thread (M:1 scheduling) and were eventually outperformed by platform threads (Java's Native Threads) implemented as wrappers for OS threads (1:1 scheduling)

  • Virtual threads employ M:N scheduling, where a large number (M) of virtual threads is scheduled to run on a smaller number (N) of OS threads.

Just a small overview

Thread Type Description Mapping (Java Thread Type: Native Threads)
Platform Threads Just a wrapper for OS Threads. 1:1
Green Threads Runs multiple "Green Threads" on a single OS Thread. 1:N
Virtual Threads Runs multiple Virtual Threads on Multiple OS threads N:M (N < M)

Full Quote from JEP

Virtual threads are a lightweight implementation of threads that is provided by the JDK rather than the OS. They are a form of user-mode threads, which have been successful in other multithreaded languages (e.g., goroutines in Go and processes in Erlang). User-mode threads even featured as so-called "green threads" in early versions of Java, when OS threads were not yet mature and widespread. However, Java's green threads all shared one OS thread (M:1 scheduling) and were eventually outperformed by platform threads, implemented as wrappers for OS threads (1:1 scheduling). Virtual threads employ M:N scheduling, where a large number (M) of virtual threads is scheduled to run on a smaller number (N) of OS threads.

  • Related