Should instance variables in Rails be set in a mutex?

Say I have a Ruby class in my Rails project that sets an instance variable.

class Something
  def self.objects
    @objects ||= begin
      # some logic that builds an array, which is ultimately stored in @objects
    end
  end
end

Is it possible that @objectscan be installed several times? Is it possible that during one request when executing code between begin/ endabove, so that this method can be called during the second request? It really comes down to the question of how Rails server instances are deployed, I suppose.

Should I use Mutexor thread synchronization? eg:.

class Something
  def self.objects
    return @objects if @objects

    Thread.exclusive do
      @objects ||= begin
        # some logic that builds an array, which is ultimately stored in @objects
      end
    end
  end
end
+5
source share
2 answers

( ) Rails MRI. , production.rb.

config.threadsafe!

MRI , . Rubinius JRuby .

, :

class Something
  def self.objects
    @objects ||= begin
      # some logic that builds an array, which is ultimately stored in @objects
    end
  end
end

||= :

class Something
  def self.objects
    @objects || (@objects = begin
      # some logic that builds an array, which is ultimately stored in @objects
    end)
  end
end

, :

  • @objects
  • @objects , @objects begin/end

, . , 2. , , . , , .

class Something
  MUTEX = Mutex.new

  def self.objects
    MUTEX.synchronize do
      @objects ||= begin
        # some logic that builds an array, which is ultimately stored in @objects
      end
    end
  end
end
+6

.

. Rails- , (read: ). @objects, Something, , .

, , , .

, : @objects , , -.

: , , , , - :)

+6

All Articles