1

As written, virtual threads are eventually mapped to actual threads. Let's say there are 1 million virtual threads that are created. In a 8 core processor, I assume there will be 8 kernel threads. So, my questions are

  1. how 1 million virtual threads are mapped to 8 kernel threads? What is the algorithm behind this?
  2. Why blocking is cheap in the virtual threads? As I understood this is because it does not block Carrier (Kernel) thread. But kernel thread uses context switch, so why it is still cheap?
  3. Is the virtual thread a good fit for use cases where code needs to call native method ( public native String getSystemTime();)
Pakira
  • 1,951
  • 3
  • 25
  • 54
  • 1
    Too many questions at once. – Johannes Kuhn Jan 04 '22 at 11:02
  • You can have more than n kernel threads with a n-core processor. – akuzminykh Jan 04 '22 at 13:17
  • When the VT blocks it registers itself with the blocking subsystem (e.g. async I/O), unwinds the stack, and returns back to the carrier thread pool. When resuming the subsystem submits the VT to the thread pool with the results, which restores the stack when executing. The carrier thread pool is a regular ForkJoinPool. A native call cannot be descheduled so it pins the carrier thread, but this is only concerning for long-running calls like custom JNI. – Ben Manes Jan 04 '22 at 17:59

1 Answers1

1
  1. Mapping of virtual threads and kernel threads is done by the thread model. There are 3 kinds of thread models available

    1. many to one

enter image description here

  1. one to one

enter image description here

  1. Many to Many

enter image description here

Essentially, the thread library keeps a mapping between the user threads/ virtual threads to kernel threads.

  1. The blocking of user thread is easy because all the kernel threads need to do is save the state of the user thread inside the kernel thread or process itself, and pick up the other user thread. On the other hand, if the kernel thread needs to be context switched a large set of registers require to evicted and stored in memory. This process is expensive.

Additionally, creating a kernel thread requires creating a complete thread control block so that kernel can manage those threads. This process is again slow.

  1. You always work at the user thread level. So any call you make needs to be on the user thread itself.
Avishek Bhattacharya
  • 6,534
  • 3
  • 34
  • 53