0

I'm getting UNABLE_TO_LOCK_ROW excpetion and tried couple of solutions like

  1. "FOR Update" in SOQL.
  2. Changed normal upsert statement to database.upsert & tried to catch,save failed records using upsertresult(after that using batch i am updating the failed records).

But still getting the same exception: UNABLE_TO_LOCK_ROW

I found the below solution as a workaround from one of the blog. Please do let me know would it be helpful ?

Code Snippet :

Integer counterUnableToLockRow = 0;
                while(counterUnableToLockRow < 10){
                    try{
                        if (!uniqIdClaimMap.isEmpty())
                            upsert uniqIdClaimMap.values() Unique_Id__c;
                    }catch(Exception ex){
                        if (StatusCode.UNABLE_TO_LOCK_ROW == ex.getDmlType(0) || ex.getMessage().contains('unable to obtain exclusive access to this record')) 
                            counterUnableToLockRow ++;
                        else if(StatusCode.DUPLICATE_VALUE == ex.getDmlType(0))
                            counterUnableToLockRow ++;
                        else
                            counterUnableToLockRow = 10;
                    }
                }
  • 1
    Can you add Batch Code? specially start method and SOQL? – Pranay Jaiswal Jul 19 at 9:21
0

I've used techniques like this before, but be aware that 10 is probably too many retries. You're likely to run in to CPU or DML limits, especially in a trigger context. You might want to limit it to just 3-5 retries or so, and if it still fails, make sure you report an error instead of continuing on. Finally, one minor nitpick, instead of setting the counter to the max value (which means if you do change the counter's maximum, you have to edit two lines of code each time), simply break instead:

else
    break;

Break immediately ends the current for, do, or while loop and goes to the next section of code. As a simple example:

while(true) {
    break;
}

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.