Locking sObject Records

I don't see this discussed often, but Salesforce.com has the ability to lock sObject records while they are being updated to prevent threading problems and race conditions.

To lock records, simply use the FOR UPDATE keywords in your SOQL statements. You do not have to manually commit the records so if your Apex script finishes successfully the changes are automatically committed to the database and the locks are released. If your Apex script fails, any database changes are rolled back and the locks are also released.

for (List<opportunity> ops : [select id from Opportunity
  where stagename = 'Closed Lost' for update]) {
 // process the records and issue DML
}

The Apex runtime engine locks not only the parent sObject record but all child records as well. So if you lock an Opportunity sObject all of its Opportunity Line Items will be locked as well. Other users will be able to read these records but not make changes to them while the lock is in place.

If your record is locked and another thread tries to commit changes, the platform will retry for roughly 5 -10 seconds before failing with a "Resource Unavailable" error. For end users, I believe if they try to save a locked record from the Salesforce.com UI, they will receive an error message stating that the record has been changed and that they should reload the page. I can't confirm but I've seen this in the past.