SOQL Record Locking (FOR UPDATE)

I am looking for some more definitive and in depth information about record locking in Salesforce. I will admit I am quite a novice when it comes to the topic of record locking, and am not sure it is even going to solve my issue.

The reason I am investigating the feature is a difficult random bug that has been discovered. The code in question is a trigger that rolls up (lookup relationships hence code needed) some numeric values onto a parent, grandparent and great grandparent object. The value is being correctly calculated on the grandparent and great grandparent, but on rare occasions for reasons unknown the parent value is not calculated correctly. 99 times out of a 100 everything is calculated as expected.

The Salesforce Docs are quite bare of any real information.

There is a forum post which is 2.5 years old that as I read it has conflicting information. Anand claims the record locking is pessimistic, but cbarry9’s quote from the unspecified manual is that other processes will wait, suggesting optimistic locking. FWIW I can not find that quote anywhere.

If I was to implement record locking, I would want to use optimistic locking.


FOR UPDATE will take an underlying database write lock on the selected rows, other requests that require the lock while another thread has it locked will wait a short amount of time (in the order of 5-10 seconds) for this lock, and then timeout if it wasn’t able to get the lock (this lock timeout gets propagated as a UNABLE_TO_LOCK_ROW error). for roll-up type operations you’ll want to ensure that you lock all the parents in a deterministic order.

The forum thread you mention uses an odd definition of optimistic locking, which might be confusing things more than helping.

Source : Link , Question Author : Daniel Blackhall , Answer Author : superfell

Leave a Comment