Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Ruby class member variables OK now?

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.

like image 544
Joe Soul-bringer Avatar asked Feb 20 '09 01:02

Joe Soul-bringer


People also ask

Are instance variables thread safe in Ruby?

Performing writes/reads on class variables in Ruby is not thread safe. Performing writes/reads on instance variables appears to be thread safe.

Are class variables inherited Ruby?

Ruby doesn't have class variables in the sense that, say, Java (where they are called static fields) has them. It doesn't need class variables, because classes are also objects, and so they can have instance variables just like any other object.

How do you access class variables in Ruby?

Re accessing instance/class variables (mainly from the console), for me it worked like FooClass. class_variable_set(:@@foo, 'bar') and FooClass. class_variable_get(:@@foo) , and for instances foo_class. instance_variable_set(:@foo, 'baz') and foo_class.

How do you declare a class variable in Ruby?

Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.


1 Answers

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.

like image 163
womble Avatar answered Oct 21 '22 03:10

womble