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
kevoharakevohara 

Question about locking

I am building a Lead prioritization class for a client.  To give a background, here are the requirements.

 

1) Sales reps are assigned one lead at a time

2) Leads are held in queues until they are assigned

3) Leads are dynamically prioritized, then assigned programatically at the time of request based on numerous factors...including time of day

 

So I have a pretty awesome class that does this prioritization and dishes one lead out at a time.  My only concern is that with the expected volume of Lead requests, there could be a possibility of accidentally re-assigning a lead to another rep that was just assigned.

 

Example:

 

Rep A makes a request for a lead.  At nearly the same time, so does Rep B.  

 

During the request, the appropriate queue is queried by the Prioritization class and about 50 records are returned.  Some calculations are performed and the list of Leads are prioritized and reordered.  The class then assigns the top Lead to the rep by updating that single record.

 

So if Rep A and Rep B make a request at the same time, it's possible that the class queries the same 50 records for each rep.  I need to make sure that if a lead is assigned to a rep, it is no longer available to anyone else to be reassigned.

 

Do I need to introduce locking or some other keyword or modifier?  Am I overthinking this?  Any help is appreciated.  

Afzal MohammadAfzal Mohammad

You may use locking statements.

 

To lock a set of sObject records in Apex, embed the keywords FOR UPDATE after any inline SOQL statement. For example,
the following statement, in addition to querying for two accounts, also locks the accounts that are returned:

 

Account [] accts = [select id from Account limit 2 for update];

 

Or in a for loop

 

 

 

for (Account[] accts : [select id from Account
for update]) {
// Your code
}

 Hope that helps.

 

Afzal