Circular dependency detected while autoloading constant

I recently ran into this frustrating and intermittent error in Ruby on Rails 4 (JRuby, actually):
Circular dependency detected while autoloading constant

Googling turned up several articles advising one to abide by the Rails conventions, but that was not the issue.

The application I’m writing uses background threads. The problem shows up when trying to instantiate a Rails controller in one of them. Rails searches for object definitions dynamically, so when multiple threads are trying to instantiate the same object, there’s a race condition.

The fix is define a mutex for access control:

And then use it in the threads when instantiating the controller, model, or some Ruby class:

Published by

Leons Petrazickis

I'm a full-stack developer at IBM Analytics Emerging Technologies. I do Ruby, JS, Python, Hadoop, Spark, as well as web scale devops with Chef and Docker. My opinions are my own.