views:

727

answers:

2

Hi,

Last May at Railsconf on Portland, I went to a presentation where it was argued that, in Rails, Ruby class member variables, like @@foo, are dangerous because they are inherently unthreadsafe.

I researched the question afterward and I never found a link that really fleshed out the question. I would appreciate a pointer to a good article on Rails and threads that really goes into the class member question. Also, It would be nice to know how Rail 2+ and Yarv has changed things in the regard.

Edit:

Perhaps my memory of the presentation is foggy but what I remember was that @@foo had problems beyond the usual caveats that any shared variable access must be strictly controlled. I know that there were memory leaks in the Ruby code itself that were fixed a little while ago. I'm looking for article links on Ruby shared variables and multitasking, the more in-depth, the better. *Currently I don't use class variable for anything because of this but it would be nice to be able use them in certain situations.

+5  A: 

Any shared mutable state is inherently thread-unsafe. You need to lock all accesses to ensure that everything's safe, and ensure that everything is re-entrant. @@foo is particularly bad because it's harder to audit code because any subclass can be accessing the variable. Rails 2+ just "solved" the problem by auditing everything and making sure that mutexes and other synchronisation primitives were used where necessary.

womble
Hmm, can you explain how Rails 2+ does this?
Joe Soul-bringer
I already did -- by finding the shared mutable state and where it is accessed and protecting it with mutexes and other synchronisation primitives.
womble
A: 

I think they're as OK as they ever were, but still to be used with caution in a Rails environment where the class may be loaded multiple times (once per mongrel, for example, if you use mongrel) so the class member variable could vary independently within those processes.

I think there's a scoping change for @@ variables in Ruby 1.9, which should probably be taken into account - we'll all be there one day.

Was there a particular use you had in mind? I thought I needed one recently, but it turned out to be a fault in my (sketchy) understanding of the topic - what I actually needed was an instance variable on the class. (I was building a module to extend a class so that I could add some AR-style declarative macro goodness.)

Mike Woodhouse