Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Immutable Objects

I've got a highly multithreaded app written in Ruby that shares a few instance variables. Writes to these variables are rare (1%) while reads are very common (99%). What is the best way (either in your opinion or in the idiomatic Ruby fashion) to ensure that these threads always see the most up-to-date values involved? Here's some ideas so far that I had (although I'd like your input before I overhaul this):

  • Have a lock that most be used before reading or writing any of these variables (from Java Concurrency in Practice). The downside of this is that it puts a lot of synchronize blocks in my code and I don't see an easy way to avoid it.
  • Use Ruby's freeze method (see here), although it looks equally cumbersome and doesn't give me any of the synchronization benefits that the first option gives.

These options both seem pretty similar but hopefully anyone out there will have a better idea (or can argue well for one of these ideas). I'd also be fine with making the objects immutable so they aren't corrupted or altered in the middle of an operation, but I don't know Ruby well enough to make the call on my own and this question seems to argue that objects are highly mutable.

like image 830
Chris Bunch Avatar asked Jan 02 '09 22:01

Chris Bunch


People also ask

Is Ruby string immutable?

In most languages, string literals are also immutable, just like numbers and symbols. In Ruby, however, all strings are mutable by default.

Are floats immutable in Ruby?

Integers and floats are frozen by default, while booleans are not. So while some primitives are not frozen, Ruby does not provide mutation methods for them and they usually can be treated as immutable objects.

What is mutable in Ruby?

Don't let fancy words confuse you, “mutability” just means that an object's internal state can be changed. This is the default of all objects, excluding those that have been frozen, or those that are part of a list of special objects. In other words, not all objects in Ruby are mutable!

Are Ruby arrays mutable?

Since all arrays in Ruby are mutable, when we pass the variable some_words (which is a reference to an array) into the method change_the_array , the method actually changes the array! On the other hand, variables bound to objects that are passed by value, like integers, are not mutable.


1 Answers

Using the lock is the most appropiate way to do this. You can see this presentation by Jim Weirich on the subject: What All Rubyist Should Know About Threading.

Also, freezing an object won't help you here since you want to modify these variables. Freezing them in place means that no further modifications will be applicable to these (and therefore your 1% of writes won't work).

like image 164
Federico Builes Avatar answered Oct 03 '22 22:10

Federico Builes