-
Notifications
You must be signed in to change notification settings - Fork 1
Description
One of the underlying assumptions of this library is that there can be at most one Scheduler per Thread. Its purpose is to manage all of the fibers under that parent thread, hand off IO operations to the IOLoop thread, process replies, etc. The Scheduler is recorded as a thread-local var for the parent thread.
In JRuby a Fiber is backed by a Thread to ease management of the stack. However, each Fiber does not report the true parent Thread for the Fiber. Instead it reports the name/identity of the Thread backing the Fiber. (Note that it enforces the rules about not allowing Fibers to move between threads, but it enforces this rule relative to the true parent thread!)
So in this library when we wrap a block in a Fiber and schedule it to run, it will start up with a new Thread. When the code confirms that it can reach the Scheduler, it notices that it is not recorded in the thread-local var so it assumes this is a new parent thread. It then creates a new Scheduler.
This leads to a situation where a parent thread has multiple children Fibers all using their own Fiber Schedulers that are not aware of each other. Chaos ensues.
To fix, I run some extra code to pass the Scheduler reference around to newly created Fibers. When they check to see if they can find the Scheduler in the thread-local var and fail, they can setup a new thread-local var to point to a known Scheduler. This enforces the rule where we have one Fiber Scheduler per parent thread.
This is a patch. I can imagine scenarios where user code creates a Fiber and is unaware of this limitation on JRuby so they skip this extra step. Ideally JRuby could be fixed so that every Fiber reports the parent Thread as Thread.current instead of the Thread backing the Fiber.
Note that Rubinius which also backs Fibers with Threads does not share this bug. It correctly reports the true parent Thread in Thread.current.
There are two issues in JRuby tracking this problem. They are issue 1717 and issue 1806.