Skip to content

Conversation

@franz1981
Copy link
Owner

@franz1981 franz1981 commented Dec 15, 2025

This pull request refactors how virtual threads are created and scheduled in the Netty Loom integration. The main improvement is a more robust and leak-resistant approach to virtual thread scheduling, ensuring that threads are properly offloaded when a scheduler is no longer available. The code is also simplified by removing an unnecessary helper method.

Improvements to virtual thread scheduling:

  • Refactored newEventLoopSchedulerFactory in EventLoopScheduler.java to use a Thread.ofVirtual().unstarted() builder for creating virtual threads, and introduced a runWithContext helper to ensure the correct scheduling context is set. This change avoids enforcing a preferred carrier, which helps prevent thread leaks when schedulers are shut down.

Codebase simplification:

  • Removed the now-unused newEventLoopScheduledThread helper method from NettyScheduler.java, as thread creation is now handled directly in the scheduler factory.

return runnable -> NettyScheduler.newEventLoopScheduledThread(() -> ScopedValue
.where(CURRENT_SCHEDULER, new SchedulingContext(Thread.currentThread().threadId(), sharedRef))
.run(runnable), sharedRef);
var unstartedBuilder = Thread.ofVirtual();
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AlanBateman I would have expected this new method to be static in Thread.OfVirtual.

Second: do you think is ok to make users able to set the preferred carrier?
e.g. see the comment below

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you asking why the 3-arg unstarted method is an instance method then it needs to be in order to pick up other properties set via other builder methods. The overload is a restricted method in the prototype to deter casual use.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for answering Alan!
And in relation to setting the preferred carrier instead: do we really want users to be able to do that?
I would have expected this argument to be useful for pollers - whilst users which implement their custom scheduler could enforce it by other means e.g. like I am doing in the Netty scheduler, dynamically

@franz1981 franz1981 merged commit a8519a7 into master Dec 15, 2025
4 checks passed
@franz1981 franz1981 deleted the 49 branch December 15, 2025 20:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants