function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
prasanth sfdcprasanth sfdc 

UNABLE_TO_LOCK_ROW email to case, please help

In case trigger code, I have the below logic,  When more than 3 email to cases are creating at same time (creating under same Account record), I am getting this error.  Please help me to solve this. 

even error is coming, the cases are created and updated sucessfully. 

This  logic in after insert/ update section of trigger. 
if ( newCase.RecordTypeid == RecordTypeHelper.CASES.GENERAL is &&
            String.isNotBlank(settings.Site_Url__c)
        ) {
            Case clonedCase = new Case(Id = newCase.Id);
            String uuId = ApexUtils.encodeValue(newCase.Id);
            clonedCase.SecureUpload_Link__c = settings.Site_Url__c + '?hashCode=' + uuId;
            casesToUpdate.add(clonedCase);
        }
    

try{
if (!casesToUpdate.isEmpty()) {
   update casesToUpdate;
  }
} catch(Exception e) {
            ApexUtils.notifyError(e);
        }

 
AbhinavAbhinav (Salesforce Developers) 
Hi  Prasanth,

Have you check this link which expalin general casuse of this error and work around.

https://salesforce.stackexchange.com/questions/20921/can-anybody-explain-the-unable-to-lock-row-error

Workaround
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_locking_records.htm

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_locking_statements.htm

If it helps mark it as best answer.

Thanks!
prasanth sfdcprasanth sfdc
Hi Abhinav,  
Earlier I have implemented this code also with for update . but no use, please review once. 
 
//Updates these cases to generate the SU Link in the future
            if (!casesToUpdate.isEmpty()) {
                //Fix for 'Unable to lock row' issue
                Map<Id, Case> casesMap = new Map<Id, Case>(casesToUpdate);
                Map<Id, Case> lockedCasesForUpdateMap = new Map<Id, Case>([SELECT Id FROM Case WHERE Id IN :casesMap.keySet() LIMIT 9990 FOR UPDATE]);
                for (Id key : lockedCasesForUpdateMap.keySet()) {
                    Case updatedCase = casesMap.get(key);
                    lockedCasesForUpdateMap.put(updatedCase.Id, updatedCase);
                }
                update lockedCasesForUpdateMap.values();
                
            }