Executors.newVirtualThreadPerTaskScheduledExecutor() ?
Dr Heinz M. Kabutz
heinz at javaspecialists.eu
Wed Aug 2 11:26:01 UTC 2023
I've been doing this for a while (and am using the approach on my
javaspecialists.eu website):
Executors.newSingleThreadScheduledExecutor(
Thread.ofVirtual().factory())
It works very well indeed.
Regards
Heinz
--
Dr Heinz M. Kabutz (PhD CompSci)
Author of "The Java™ Specialists' Newsletter" -www.javaspecialists.eu
Java Champion -www.javachampions.org
JavaOne Rock Star Speaker
Tel: +30 69 75 595 262
Skype: kabutz
On 2023/08/01 19:46, Alan Bateman wrote:
> On 01/08/2023 06:57, Formula Salt wrote:
>> Hi,
>>
>> I am trying to use virtual threads together with the
>> ScheduledExecutorService but I am uncertain what is the best way to
>> do so. To use the ExecutorService with virtual threads we would use
>> Executors.newVirtualThreadPerTaskExecutor() but there seems to be no
>> equivalent method for the ScheduledExecutorService.
>>
>> Executors.newScheduledThreadPool(int, ThreadFactory) would require
>> pooling virtual threads which I believe is considered bad practice.
>> Executors.newSingleThreadScheduledExecutor(ThreadFactory) only allows
>> for a single thread so tasks must execute sequentially.
>>
>> The best way I've found so far is in this StackOverflow answer
>> (https://stackoverflow.com/a/76599122) which suggests using both a
>> single-threaded ScheduledExecutorService and
>> Executors.newVirtualThreadPerTaskExecutor(). This works but perhaps
>> the Executors API should directly support this
>> via Executors.newVirtualThreadPerTaskScheduledExecutor() ?
>
> Just to add to what Ron said is that it's an area that didn't receive
> any feedback or come up during preview. As I think you've figured out,
> delay can be implemented by wrapping the task so that it sleeps before
> running, periodic with fixed delay can be done with a loop + sleep,
> periodic at fixed rate by submitting a delayed task with the time
> remaining after the previous run. So not hard, and the main difference
> being that each delayed or periodic task runs in its own virtual
> thread rather than a pooled thread. There is higher priority work
> require on a more scalable timer implementation and that might be the
> right time to look at Executors factory methods.
>
> -Alan.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20230802/f9b02e41/attachment.htm>
More information about the loom-dev
mailing list