4

If I have a class that is using FOR UPDATE to lock a record. Is there a way to prevent another instance of that class from calling those records that have been locked before the previous class is done with them?

My issue here is I need to have many people query for the same records but if those records are currently being worked I don't want User B to return any Records User A has locked as then we run into long running wait issues.

4
  • 6
    FOR UPDATE is only locking the records for the duration of the transaction, and Salesforce best practice is to keep these as short as possible. The locking here isn't for long-lived locking and you should implement "optimistic locking" approaches if that is something you really need to do (basically what Salesforce does when editing records through the Salesforce UI). As far as I know, there is no way to discover which records are currently covered by a FOR UPDATE lock. – Phil W Dec 19 '19 at 20:11
  • @PhilW This might as well be an answer – Brian Miller Dec 19 '19 at 20:52
  • The issue is the transaction is pretty quick but the calls to the Class happen from like 500 people so can happen from 15 people at the same time so they would all return the same record and only one would win. So the goal would be based on the query the records it would pull would be removed from the population during transaction so any other calls to the class wouldn't return a record to be worked that was currently being worked if that makes sense. – Dan Donin Dec 19 '19 at 21:40
  • 2
    The answer is NO (as PhilW says). You could build retry logic into the class if encountering an unable to obtain access error – cropredy Dec 19 '19 at 21:44
5

There is no way to discover which records are currently covered by a FOR UPDATE lock.

FOR UPDATE is only locking the records for the duration of the transaction, and Salesforce best practice is to keep these as short as possible.

The locking here isn't for long-lived locking and you should implement "optimistic locking" approaches if that is something you really need to do (basically what Salesforce does when editing records through the Salesforce UI).

A given transaction will only wait up to 10 seconds to get a lock before a QueryException is thrown in this scenario. You can catch the exception and deal with it in a manner appropriate to your use case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.