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.
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.
Performing writes/reads on class variables in Ruby is not thread safe. Performing writes/reads on instance variables appears to be thread safe.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With