How to specify scheduler for virtual threads

Arkadiusz Gasiński jigga at jigga.pl
Wed Nov 20 00:21:35 UTC 2019


Awesome, thanks!

I've played with it for a moment and managed to come up with this weird
code below:

var dinosaurs = Executors.newFixedThreadPool(2);
var factory = Thread.builder()
    .virtual()
    .scheduler(dinosaurs)
    .name("virtual-thread-", 1)
    .inheritThreadLocals()
    .factory();
var virtualOverDinosaurs = Executors.newFixedThreadPool(1000, factory);

If I understand my code correctly, I created an Executor that multiplexes
1000 virtual threads over 2 dinosaur threads.

What I'm confused about is that once I started submitting tasks to this
virtualOverDinosaurs executor, it quickly became apparent that it does not
create a new virtual thread for each task submitted, but rather multiplexes
these tasks over some rather small number of virtual threads. My questions
then are:

Does it mean that this virtualOverDinosaurs executor caches virtual
threads? If so what does it mean to cache virtual thread?
Should something like this be even possible? I thought that one of the
purposes of virtual threads was to support 1:1 mapping between a task and a
thread and this is apparently not the case here.

Thanks,
Arek




On Tue, Nov 19, 2019 at 11:50 PM Alan Bateman <Alan.Bateman at oracle.com>
wrote:

> On 19/11/2019 21:43, Arkadiusz Gasiński wrote:
> > Hi,
> >
> > Quick question... How do I specify scheduler to be used to schedule
> virtual
> > threads after recent changes? The Thread.newLightWeightThread method that
> > was removed, had an overloaded version that allowed to specify scheduler,
> > but that's not true for Thread.newThread method. What am I missing? Or is
> > that functionality not yet ready in the new API?
> >
> Still work in progress but you should find what you need in
> Thread.Builder. There are several examples in the javadoc, this one is
> probably close to what you want:
>
> Executor scheduler = ...
> ThreadFactory factory =
> Thread.builder().virtual().scheduler(scheduler).factory();
>
> -Alan
>


More information about the loom-dev mailing list