1

As You know how we can lock records in Apex by adding a FOR UPDATE at the end of SOQL query. In one of my classes I have to query for a bunch of records and then updating them.

In this query I use FOR UPDATE as well to lock them and then I wrap it in a try/catch and put it in a loop, so whenever records are unlocked, my query return them and lock them. This is how it looks:

While(isLocked) {
    try {
        records = [SELECT ... FOR UPDATE];
        isLocked = false;
    } catch(QueryException e) {
        isLocked = true;
    }
}

So basically it keeps querying until it is unlocked. This clearly is not a good idea, I may even hit query limits! What I need here is basically to find a way to be notified when the object is unlocked and then proceed with my query and rest of the logic.

In my search, everyone was talking about Apex Approval Process. I am not familiar with this process but from documentation it says:

An approval process automates how records are approved in Salesforce

so it doesn't seem to be relevant, or at least I can't figure out how to relate that and use it for my usecase.

  • Yeah approval locking and transaction locking are completely distinct phenomena. Totally unrelated. – Adrian Larson Aug 29 '17 at 18:13
3

Record locks and approval "locks" are two different things. There's nothing inherently wrong with the design of using this sort of loop, although you shouldn't do this in a trigger, because it could cause significant delay for users trying to save records. Typically, when we use this design, we will first attempt to lock the records, and if it fails, we queue a queueable job to try again later so users can get on with their work. The queueable itself uses a spin lock (waits in an infinite loop until the records are acquired) so it can do what it needs to do, but asynchronously.

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.