Race condition in custom schedulers example
Alan Bateman
alan.bateman at oracle.com
Wed Jul 9 08:36:39 UTC 2025
On 08/07/2025 23:37, Liam Miller-Cushon wrote:
> In particular, the `vthreadTask.attach(null)` can race with the
> earlier `vthreadTask.attach(new Context(...));`. This happens because
> the virtual thread can be scheduled again as soon as its run
> continuation finishes under `vthreadTask.run()`, so if the platform
> thread it was bound to deschedules and the virtual thread is then
> scheduled on a different platform thread, the newly scheduled task’s
> call to `vthreadTask.attach(new Context(...));` races with the first
> platform thread’s `vthreadTask.attach(null);`.
Yes, thanks. This is part of the prototype API that this project was
experimenting with before JDK 19. It was dropped before the first
preview but is back in the loom repo as one of two approaches to allow
for further exploration into using different schedulers for virtual
threads. So yes, it's possible to overlap so there are 2+ executing
tasks for the same virtual thread. The virtual thread will only ever be
mounted on a single carrier at a time but a custom scheduler can't
currently tell this.
>
> It may also be worth mentioning the risk of deadlocks with the virtual
> thread: any locks that we might block on in this custom scheduler code
> must not be held by the virtual thread, else if it deschedules while
> holding the lock, our custom scheduler deadlocks.
Right. If something is exposed then it it will need to come with several
warnings that include never attempting to coordinate virtual threads and
carriers with locking. I think Francesco's experiments with using Netty
event loop thread as carrier rang into this before changing the event
loop to be run in the context of a virtual thread.
-Alan
More information about the loom-dev
mailing list