Question

I have a Ruby on Rails server for a web application.

I am wondering if instance variables in Ruby are shared on different requests. Here is my problem:

Bob makes a Get request to my ruby server; it first initiates a instance variable @x and then its request is processed for a while.

In the meantime, Alice makes another Get request that initiates a instance variable @x. At the end of Bob's process, the variable @x is looked at. Will it have the value given by Bob or Alice?

What if Bob and Alice are the same person that quickly makes the same request twice in a row? Will the first request see the value initiated by the second request at the end of its process?

Edit: this happens when config.cache_classes is set to true and from my experiments, it doesn't concern controllers' instance variables but it do concern librairies. Here is what I have done. When an http request arrives, I set an instance variable @x to a random value and save it in a variable x. I sleep for a while and then I compare @x and x. When I launch several requests at the same time, I sometime find different values when doing the comparison. However, this mismatch doesn't happen in controllers but it does in librairies. Does it means that the controllers are not cashed but librairies are when config.cache_classes = true ?

Was it helpful?

Solution 2

Rails 4 is the first version to be multi-threaded by default - you shouldn't run into variable concurrency issues with earlier versions unless you explicitly turned threading on in the config (config.threadsafe!).

You can still have database-related concurrency issues in single-threaded Rails: If, for example, you read from a field at the start of a request, perform some calculation on that value and then write it back.

In multi-threaded Rails you can have concurrency problems with global or class variables too, as these are stored in shared memory space. Global variables are defined with the dollar symbol $x and class variables are defined with two at symbols @@x - both have their uses but there are usually better ways to pass data around.

OTHER TIPS

  1. @x is not a global variable, it's an instance variable.

  2. No, controller instance variables are not shared between requests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top