What really happens under the hood when a virtual thread is created?

134 views Asked by At

When a virtual thread is created, what happens under the hood? I believe it does the below set of things, can someone explain it in detail?

  1. Create a Virtual Thread and Continuation object and assign Continuation to a VT.

  2. Submit this task to a ForkJoin pool

  3. Execution of the Runnable

Apart from this, I have one more question, when a virtual thread is unblocked which thread calls Continuation.start() assuming that ForkJoin pool threads are busy serving other requests.

1

There are 1 answers

0
Andrés Alcarraz On
  1. I believe that it is as you mentioned, all that has to be created in order to store the state of the virtual thread.

  2. As far as I understand, the task is not submitted to a ForkJoinPool, the ForkJoinPool will "activate" the virtual thread when one of its threads becomes available (idle).

  3. The runnable will start to be executed when the virtual thread is executed by the ForkJoinPool. But as soon as it performs a blocking operation, the virtual thread will yield, as soon as the blocking operation ends, it will be in a state in which it will be resumable. This will happen, again, when there is an available thread in the ForkJoinPool. This may happen many times during the course of the task, until the run method ends.

If the ForkJoinPool threads are busy, no one will call the Continuation.start(). That would be called as soon as the ForkJoin pool has an available thread.

In addition to that, one thread of the ForkJoin pool is always reserved for managing the others. That would be the thread that takes the virtual thread, associates it to a platform thread, and then call Continuation.run() on that available thread, which in turn will mount the virtual thread on the platform thread.

It's worth noticing, that you don't want to use virtual threads for processing intensive tasks, only for tasks that blocks, for instance on network calls or reading files.