Rails Model Associations Mutex / Locking?

I've read quite a bit about pessimistic and optimistic locking on models in rails. However, I have not yet found any information on how to implement locking in ActiveRecord :: Associations :: CollectionProxy ..

For example,

class Model < ActiveRecord::Base
  has_many :model_other_models
  has_many :other_models, :through => :model_other_models

  def do_stuff
    self.with_lock do
      # do other stuff
      new_model = OtherModel.new ( ... )
      other_models << new_model
    end
  end

  def modify_other_models
    self.other_models.each do |other_model|
      other_model.with_lock do
        # other stuff
      end
    end
  end

end

      

Everything seems to be fine and dandy, but what if in another instance of my multithreaded app server the user is accessing the model union "other_models" while in this situation it is being added to it. Wouldn't that lead to a racial state?

Would a class level mutex in the other_models association collection solve this problem? Should I lock the entire table that joins the model to other_models? How can i do this? Is this an optimistic locking task implemented in the model_other_models association?

I found a lot of information on how to actually lock the records of the models themselves, but nothing about the collection of models as part of the model associations.

Thank.



Update

I believe the answer was right in front of me. There is no way to stop other classes from using model methods and accessing associations directly, but if good practice is used it solves this problem.

If one instance is in the process of adding record B to the association proxy and uses a write lock on record A, but another instance directly accesses the record. Collect record B without blocking, then race condition is present.

If the method of adding and removing a model changes the association proxy, but both use the lock associated with the write, the race condition is excluded.

The downside here is that any operation involving record associations must rely on locking on the record itself, which can be very unnecessary depending on the situation. It would be ideal if ONLY the collection of associations could be locked.

+3


source to share





All Articles