Executors.newVirtualThreadPerTaskScheduledExecutor() ?

Alan Bateman Alan.Bateman at oracle.com
Tue Aug 1 16:46:04 UTC 2023


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.


More information about the loom-dev mailing list