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
lrw757lrw757 

Apex Code inserts records, Queueable updates - UNABLE TO LOCK ROW error

I have a piece of code that inserts multiple records of an object, loops over the objects, and creates a queueable instance for each one that involves a DML on this object. When I perform this code for one record, the code performs successfully, but when I queue up more than one, I get an UNABLE TO LOCK ROW error.

There are no triggers, workflow rules, etc. on the SObject (it's a brand new, fresh object created by myself), and no other DML operations take place in either class on those objects. Any ideas on why this is occuring?

Here is a sample of the code:
public with sharing class QueueableTest {

    public void test() {
        List<MyObject__c> osToInsert = new List<MyObject__c>();
        for(integer i = 0; i < 10; i++) {
           osToInsert.add(new MyObject__c());
        }
        insert osToInsert;

        for(MyObject__c o : osToInsert) {
            System.enqueueJob(new MyQueueableClass(o);
        }
    }
}
 
public class MyQueueableClass implements Queueable {
   
    MyObject__c o;
    
    public MyQueueableClass(MyObject__c o){
        this.o = o;
    }
    
    public void execute(QueueableContext context) {
        o.status__c = 'Running';
        update o;
        //Do something
    }
}

 
David ZhuDavid Zhu
 I highlight all important places. 
system.QueueJob method will run immediately after Test.StopTest().
@istest
public with sharing class QueueableTest {

    public static testmethod void test() {
        List<MyObject__c> osToInsert = new List<MyObject__c>();
        for(integer i = 0; i < 10; i++) {
           osToInsert.add(new MyObject__c());
        }
        insert osToInsert;
 
        Test.StartTest();
        for(MyObject__c o : osToInsert) {
            System.enqueueJob(new MyQueueableClass(o);
        }
        Test.StopTest();

        osToInsert = [select id,xxx from myobject__c];
        for(myobject__c o : osToInsert)
        {
            system.assertequals(expectedata, yourfield);
        }

    }
}
lrw757lrw757
This has nothing to do with test classes, I'm facing the error functionally.