I have an EmailService that takes the data from an email and creates a Lead if no match is found for the supplied email address. If a Lead is found then the Lead is updated with the new details supplied.
This works fine when emails come in with a suitable gap. If 2 emails come in quick succession (ie. simultaneously?) then duplicate Leads are created for the same email address. Is there a way to stop this happening?
The code is essentially
global class leadCreationEmailService implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,
Messaging.InboundEnvelope env) {
//parse email and get email, phone, etc...
list<Lead> leads = [select id from Lead where email=:emailAddress];
if(leads.size() > 0){
l = leads[0];
l.MobilePhone = phone;
l.firstName = firstName;
l.lastName = lastName;
}
else{
l = new Lead();
l.firstName = firstName;
l.lastName = lastName;
l.Company = 'my co.';
l.email = emailAddress;
l.MobilePhone = phone;
l.LeadSource = 'Website';
insert l;
}
result.success = true;
return result;
}
}
I expect its because there are 2 threads running concurrently and so the 2nd thread is doing the search before the 1st thread has finished.
I have tried moving the code to a future method to try and force a 'time gap' but this also fails.
UPDATE - putting code in a future method is more reliable than first thought; with the email processing done in the service and the DML statements in the async method.
Any ideas?