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
bohemianguy100bohemianguy100 

Sporadic error: UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record

I am getting the following error message sporadically when I run my unit tests:

 

System.DmlException: Delete failed. First exception on row 0 with id a09f0000000e6DpAAI; first error: UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record: []

 

Sometimes, I don't get the error message at all.  Other times, I get the error, but it occurs on different unit tests.  It occurs randomly.

 

I have a custom setting that I use to externalize some common variables that I use within my apex code.  In my unit test, I first delete my existing custom setting from the org and then recreate my custom setting and the associated values and insert so I have the custom setting setup and populated for my unit test.

 

So, in my unit test, when I delete my existing custom setting, it randomly complains with the UNABLE_TO_LOCK_ROW error.  Is there a way I can avoid this error? 

 

My code runs fine, I've tested it thoroughly and it all runs without error.  The error is only occurring in my unit tests.

 

Any help is appreciated.

Thanks.

Best Answer chosen by Admin (Salesforce Developers) 
truebruceleetruebrucelee

On Apex Test Execution page click options and tick Disable Parallel Apex Testing. Then the testing will take longer but you won't get error.

All Answers

truebruceleetruebrucelee

On Apex Test Execution page click options and tick Disable Parallel Apex Testing. Then the testing will take longer but you won't get error.

This was selected as the best answer
docbilldocbill
It would be much better to help us understand the cause of the error.   For example I have the following bit of code that sometimes throws this error:

    static Map<Id,PricebookEntry> pricebookEntryMap {
        get {
            if(pricebookEntryMap == null) {
                insert pricebookEntries;
                pricebookEntryMap = new Map<Id,PricebookEntry>(pricebookEntries);
            }
            return pricebookEntryMap;
        }
    }

Really, this whole thing confuses me terribly.  As near as I can tell test methods never share data or static information.  If they did it would make test classes much more efficient...   Each test method will spend 30 - 60 seconds creating and inserting objects for my tests.  If I replace inserts with upserts, there is never an existing value that is updated, which is good because I would hate to have conflicting data definitions.   But if the data is not shared, what is the lock that is having problems?  Why is it only for inserting pricebook entries, and not for the many other objects that are inserted?

 
sean*harrisonsean*harrison
@docbill Did you get an answer to this question beyond "disable parallel"?