+ Start a Discussion
Ken KoellnerKen Koellner 

Locks held on Insert to Opportunity and OpportunityLineItem

I need to write some code to concurrently create, via queueable async apex, up to 5-6 Opportunity on the same Account.  In addition to the insert to Opportunity will be inserts of up to a few hundred records to OpportunityLineItem and also several records to custom tables related to Opportunity.  I have code that inserts all the records already but haven't tried using it concurrently yet.  There is no expicit commit in Apex so all those updates are in one transaction and that transaction can run for 20-30 seconds.

When I start doing the create Opportunities concurrently, I'm worried about locking errors.  The main resource shared by all Opps is Account.  If the first transaction write-locks Account then the others will likely fail with locking errors.  There's also the issue of PricebookEntry and Product as many of the Opps will be using similiar lists of Products.

Anyone know what locks will be held when the inserts are happening to Opp and Opp Line Item and what the likelihood of interference is?
ShashankShashank (Salesforce Developers) 
According to this cheatsheet: https://help.salesforce.com/help/pdfs/en/record_locking_cheatsheet.pdf , creating/updating an opportunity does lock the parent account. However, I believe these locks do not happen within the same transaction, and would affect only inter-transaction situations. Also, as long as you are not updating the parent account, there should not be a lock error. 
Ken KoellnerKen Koellner
I don’t know if I would draw the same conclusion. The table doesn’t define whether it is a write lock or a read lock. If updating an Opp causes a read lock on the Account, then another insert of an Opp would not have a problem. But if insert of an Opp puts a write lock on Account, no operation in a different transaction would be able to get a write lock on Account and therefore would not be able to insert an Opp. Regarding inter-transaction, I doubt SF would consider the threads of execution part of the same transaction. So the locks would be in effect in this situation as it is inter-transaction. -K