[External] : Re: Executors.newVirtualThreadPerTaskScheduledExecutor() ?
Dr Heinz M. Kabutz
heinz at javaspecialists.eu
Wed Aug 2 14:38:35 UTC 2023
>> Could you perhaps expand a bit on the problems that are caused by my solution above?
> There is no problem, and at least in one specific case I would say it’s perfectly valid: you have a single task that you want to run on a single thread at a fixed rate. I was commenting not on the approach but on suggesting it in public before people gain experience with virtual threads, i.e. the only “problem” is a pedagogical risk.
>
> One of the questions I see coming up on social media over and over is “how many virtual threads do I need?” or “why would anyone ever need so many threads?” The thing we are trying to communicate to those encountering cheap threads for the first time is that even though they’re a familiar abstraction, the form factor requires a different kind of usage and, in fact, that is precisely where the benefit lies. Platform threads are viewed as a computational resource. Virtual threads, on the other hand, represent a domain object: a task. The question of “how many virtual threads do I need?” Is, therefore, similar to the question, “how many strings do I need to keep a list of active user named in memory?”. The answer, in both situations is, “as many as there are domain objects”, which, in the case of virtual threads means “as many as there are tasks.” Similarly, the answer to the second question of “why would anyone ever need so many threads?” is “because a virtual thread is a task, and we often need that many tasks.”
>
> That is why I fear showing beginners, *at this early stage*, any usage that appears to use a single virtual thread to run multiple tasks. People should first get used to thinking “a virtual thread is a task” before considering exceptions such as, “in this particular case, scheduling some operation to run at a fixed rate is conceptually a single task.” So there’s nothing intrinsically wrong with your usage, it’s just something that should be shown after people have already internalised the proper way of thinking about virtual threads.
Thanks so much for your detailed response Ron! I was going to write an
article on this usage, but will hold back for now. I do mention it in my
"Mastering Virtual Threads in Java" Course, but of course first we take
a good look at the mental model of one "virtual thread" per task.
We also have to think differently in other ways - for example - whilst
virtual threads are cheap, resources like PrintStream and BufferedReader
are not.
Heinz
More information about the loom-dev
mailing list