views:

27

answers:

2

Assuming I'm doing something like this (from the Active Record Querying guide)

Item.transaction do  
  i = Item.first(:lock => true)  
  i.name = 'Jones'  
  i.save 
end 

Is the lock automatically released at the end of the transaction? I've looked at the Active Query guide and the ActiveRecord::Locking::Pessimistic docs, and couldn't find where it explicitly says where the lock is released.

A: 

I believe you'll want an "ensure" block to be certain the lock is released.

http://ruby-doc.org/core/classes/Mutex.src/M000916.html has:

  def synchronize
    lock
    begin
      yield
    ensure
      unlock
    end
  end

http://yehudakatz.com/2010/02/07/the-building-blocks-of-ruby/ seems to suggest, however, that the block structure of that method will automatically unlock.

Martin Eve
This is the wrong kind of lock, database pessimistic lock vs thread locking
Omar Qureshi
+2  A: 

Locking is not a function of rails, it is just adding the lock statement to the query, which will vary depending on the database that you are using. Pessimistic Locking takes a "pessimistic" view in thinking that every query is subject to corruption. So it is going to lock the database until you are finished with the query. so Lock > query > unlock. While these are fairly consistent database to database, it might be good to read up on the database documentation that you using for any database-specific things you should know.

Here is a good thread on optimistic vs. pessimistic locking that explains it better than I can. http://stackoverflow.com/questions/129329/optimistic-vs-pessimistic-locking

Geoff Lanotte
Thanks. I'm using mySQL so I looked it up in those docs and it says the lock is released when the transaction commits or rollbacks. I don't know how it works outside of a transaction.