views:

339

answers:

2

It seems to me that the Ruby community has been freaking out a little about autoload since this famous thread, discouraging its use for thread safety reasons.

Does anyone know if this is no longer an issue in Ruby 1.9.1 or 1.9.2? I've seen a bit of talk about wrapping requires in mutexes and such, but the 1.9 changelogs (or at least as much as I've been able to find) don't seem to address this particular question. I'd like to know if I can reasonably start autoloading in 1.9-only libraries without any reasonable grief.

Thanks in advance for any insights.

+3  A: 

I don't know about the general case, but repro example from that thread doesn't break in 1.9.1:

autoloaded.rb:

sleep 1
Bar::Foo = 1

autoloader.rb:

module Bar
   autoload :Foo, 'autoloaded.rb'
end

t1 = Thread.new { Bar::Foo }
t2 = Thread.new { Bar::Foo }
t1.join; t2.join
Isaac Cambron
D'oh. Why oh why didn't I think of that? After reproducing it myself and trying some stress-test variations (and confirming with RVM that it IS still broken in 1.8.7, JRuby, and Rubinius -- everything **except** 1.9.1 and 1.9.2) I'm calling this answered. Thank you!
SFEley
I'm surprised that it isn't thread-safe in JRuby - I thought that thread-safety was one of their aims.
Andrew Grimm
A: 

it's always broken.

subload allows you to switch modes when in a threaded environment.

I use autoload still in threaded environment, but only during a single threaded boot sequence. I don't see any good reason to have a multithreaded startup process in a real world application. If you do have one, you will likely need to queue up actions for loading shared libraries as you will always have thread safety issues with class and instance level setup, most partuclarly with things like:

class Lib extend SomeClassFuncs do_something_with_class_funcs end

This code is not thread safe a load time, irrespective of the loader.

If you can't see this, you shouldn't be threading.

raggi
Subload? What's subload? --I do see your point, but as you point out, that sort of metaprogramming is just as thread-unsafe with `require` as with `autoload`. My question was whether the specific bug in `autoload` that was documented by Charles Nutter some time ago had been fixed in Ruby 1.9, and it has been.
SFEley