Search

1/02/2010

Green threads

Green threads

In computer programming, green threads are threads that are scheduled by a Virtual Machine (VM) instead of natively by the underlying operating system. Green threads emulate multithreaded environments without relying on any native OS capabilities, and they are managed in user space instead of kernel space, enabling them to work in environments that do not have native thread support[1].

Green and native threads -- what's the difference?
Green threads, the threads provided by the JVM, run at the user level, meaning that the JVM creates and schedules the threads itself. Therefore, the operating system kernel doesn't create or schedule them. Instead, the underlying OS sees the JVM only as one thread.

Green threads prove inefficient for a number of reasons. Foremost, green threads cannot take advantage of a multiprocessor system. Since the JVM simply runs from within one thread, the threads that the JVM creates are not threads at the OS level. Instead, the JVM splits its timeslice among the various threads that it spawns internally. Thus, the JVM threads are bound to run within that single JVM thread that runs inside a single processor.

In contrast, native threads are created and scheduled by the underlying operating system. Rather than create and schedule threads itself, the JVM creates the threads by calling OS-level APIs. As a result, native threads can benefit from multiple processors. Performance can improve because an IO-blocked thread will no longer block the entire JVM. The block will only block the thread waiting for the IO resource.

There are times when you might want to run green threads. First, native threads are not always available. Second, if your code is not thread-safe, you may experience errors when running native threads.

沒有留言: