PessmisticLocking

Posted by Shugo Maeda Wed, 10 May 2006 21:35:00 GMT

PessimisticLocking provides row-level pessimistic locking using SELECT FOR UPDATE.

You can specify the new option :lock of ActiveRecord::Base.find() to lock rows:

Account.transaction do
  shugo = Account.find(:first, :conditions => "name = 'shugo'", :lock => true)
  yuko = Account.find(:first, :conditions => "name = 'yuko'", :lock => true)
  shugo.balance -= 100
  shugo.save
  yuko.balance += 100
  yuko.save
end

Or you can also use ActiveRecord::Base#lock() instead:

Account.transaction do
  accounts = Account.find(:all, :conditions => ...)
  account1 = accounts.detect { |account| ... }
  account2 = accounts.detect { |account| ... }
  account1.lock
  account2.lock
  account1.balance -= 100
  account1.save
  account2.balance += 100
  account2.save
end

The latter way may be better if you don't need lock all SELECTed rows.

Leave a comment, View comments, View trackbacks

Your Comments.

Leave your own response

Other posts about this post.

This post has been discussed on the following web sites / blogs. If you wish to trackback to this post please use the following trackback address: http://blog.shugo.net/articles/trackback/17

Spread the word.

Shugo's Blog supports RSS (Real Simple Syndication), and Trackbacks from other blogs.

RSS feed for this post Trackback URI

Your Reply

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.