Sobes.tech
Middle+

What are 'green threads' and do they exist in Java?

sobes.tech AI

Answer from AI

"Green threads" are threads managed in user space rather than at the operating system level. They are not associated with native OS threads.

Key features:

  • Management: Fully managed by the Java Virtual Machine (JVM), without OS scheduler involvement.
  • Overhead: Creation and switching are faster and require fewer resources than native threads, as there is no need for system calls.
  • Scalability: They scale better in terms of the number of threads, consuming less memory and OS kernel resources.
  • Parallelism: They cannot execute code in parallel on multi-processor systems because all "green threads" are mapped to a single native OS thread. At any given time, only one "green thread" runs on a native thread. If a "green thread" blocks (e.g., waiting for I/O), it blocks the native thread it runs on, stopping other "green threads" on that native thread.

Historically, "green threads" existed in Java, particularly in older JVM versions (around Java 1.2). Sun Microsystems used them to ensure portability on platforms where native threads were poorly implemented or absent.

In modern Java versions (starting from Java 1.2 and onwards), JVM threads are native threads, mapped 1:1 to OS threads. This allows the JVM to use the OS scheduler and execute threads in parallel on multi-processor systems.

Thus, in modern Java, "green threads" in their original sense do not exist. JVM uses native OS threads for multithreading.

However, the concept of lightweight, environment-managed "threads" or "tasks" that do not map directly to OS threads returns with Project Loom. Project Loom introduces virtual threads. Virtual threads are similar to "green threads" in that they are lightweight, JVM-managed, and millions can be created. But the main difference is that virtual threads map to a pool of carrier threads (which are native OS threads). When a virtual thread blocks (e.g., during I/O), the Loom runtime can "detach" it from its carrier thread and allow another virtual thread to run on the same carrier thread. This provides scalability and efficient resource use while maintaining the ability to execute code on multi-processor systems via a pool of native carrier threads.

Comparison:

Characteristic "Green threads" (historical Java) Native threads (modern Java) Virtual threads (Project Loom)
Management JVM (user space) Operating system (kernel) JVM (user space)
OS thread binding Many-to-one (M:1) One-to-one (1:1) Many-to-pool of carrier threads (M:N)
Overhead Low High Very low
Scalability High (by quantity) Limited (by quantity) Very high
Parallelism No (on a single core) Yes (depending on OS/hardware) Yes (via carrier thread pool)
Blocking operations Block JVM Block OS thread Do not block carrier thread (usually)
Existence in Java Up to Java 1.2 From Java 1.2 to present From Java 19 (preview), Java 21 (stable)