Jeremy Kemper just added pessimistic locking to ActiveRecord:
Person.transaction do
person = Person.find(1, :lock => true)
person.visits += 1
person.save!
end
Related posts:
- Photoshop Tip: Locking Transparent Pixels Jennifer demonstrates how the Lock Transparent Pixels button can help...
- CSIRO Receives $185 Million for Wi-Fi Patent It's official: wi-fi is a patented technology. Several large companies...







Wow ground breaking.
June 21st, 2006 at 9:24 am
I know I sorely missed this feature. Not sure about others… but thanks for the input Tex ;)
June 21st, 2006 at 11:02 am
Tim,
I am having trouble figuring out what this does. Can you explain for those of us new to this, and give us an example of what we could use it for?
June 22nd, 2006 at 2:08 am
Sorry SRTech, a full explanation would have been much more helpful.
Read locks such as this ensure that no other queries can read that table row until the transaction has completed. Because you want to be able to execute your code simultaneously, and from different servers, database locks can be used to make sure your is consistent.
For example, say you want to implement something that tracks the visits for your user accounts.
A simple implementation could be:
If the user makes simultaneous requests you can get what’s called a race condition.
For example, the following could be the order of execution if the the same user made 2 simultaneous requests:
The problem here is that visits should really be 3, not 2.
With web applications you need multiple application servers to be able to execute the code concurrently. The database is the perfect fit to handle this case.
Changing the code to:
produces the following SQL code:
Does that make more sense?
(updated to remove inaccurate SQL comments)
June 23rd, 2006 at 9:17 am
Tim, there is a major error in your code above. Calling update_attribute will NOT update a single attribute – it will update the single attribute in memory then save the ENTIRE record.
June 28th, 2006 at 7:31 pm
Thanks Luke, you’re totally right!
Not that it really matters in the above example, because we are locking the entire row, but I’ll update the article for correctness.
June 29th, 2006 at 12:14 pm
hey Tim dats a gud article for quick reference. thnx :)
July 25th, 2006 at 7:57 pm
Thanks for the writeup!
I’ve written up some notes on testing rails code with concurrency issues over here
December 11th, 2006 at 9:58 pm