Executors.newVirtualThreadPerTaskScheduledExecutor() ?
Attila Kelemen
attila.kelemen85 at gmail.com
Tue Aug 1 11:26:40 UTC 2023
I guess one problem is that there are multiple ways to implement such a SES
(and it is not obvious to me which is the best).
1. For every schedule* method, SES submits a new task to a thread per task
executor which simply sleeps before executing the task.
2. The virtual thread based SES has an underlying single threaded SES (also
using VT), and all scheduled tasks are scheduled by the wrapped SES, but
the tasks are wrapped into another one which - instead of directly
executing the actual task - just submits it to a thread per task executor.
The above two are actually not that hard to implement (though a bit
cumbersome at places, especially the 2nd), if really needed.
That said, I think VT based code should just use a simple
`ExecutorService`, and loop as it sees convenient with sleeps (of course,
this might not be possible, if you rely on an API needing a SES). In fact,
instead of a SES implementation, I would rather see convenient utilities
for repeated synchronous task execution. Though I believe this would first
require a sensible cancellation mechanism in the JDK (as opposed to the
awkward interrupt based one).
Formula Salt <formulasalt410 at gmail.com> ezt írta (időpont: 2023. aug. 1.,
K, 7:58):
> 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() ?
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20230801/6c11b596/attachment.htm>
More information about the loom-dev
mailing list