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?
Create a Virtual Thread and Continuation object and assign Continuation to a VT.
Submit this task to a ForkJoin pool
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.
I believe that it is as you mentioned, all that has to be created in order to store the state of the virtual thread.
As far as I understand, the task is not submitted to a
ForkJoinPool, theForkJoinPoolwill "activate" the virtual thread when one of its threads becomes available (idle).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 willyield, 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 theForkJoinPool. This may happen many times during the course of the task, until therunmethod ends.If the
ForkJoinPoolthreads are busy, no one will call theContinuation.start(). That would be called as soon as theForkJoinpool 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.