I have a custom Object TaskEvent with an Event Type and a Task ID

Throughout the life-cycle of the task I will receive events such as

  • Start Event
  • Routing Event
  • End Event

I receive a web request containing the Task ID and Event Type and store that in my custom object. I have a trigger that performs a process on the task ID based on the event type. (@future)

I need to ensure that I don't process multiple events for the same task at the same time.

Is there a way to do this in Salesforce / APEX?

I'm not aware of any locking mechanism, etc.

1 Answer 1


See this blog post for more info but you can lock sObject records. To lock records, simply use the FOR UPDATE keywords in your SOQL statements. You do not have to manually commit the records so if your Apex script finishes successfully the changes are automatically committed to the database and the locks are released. If your Apex script fails, any database changes are rolled back and the locks are also released.

for (List<opportunity> ops : [select id from Opportunity
   where stagename = 'Closed Lost' for update]) {
    // process the records and issue DML

The Apex runtime engine locks not only the parent sObject record but all child records as well. So if you lock, for instance, an Opportunity sObject all of its Opportunity Line Items will be locked as well. Other users will be able to read these records but not make changes to them while the lock is in place.

If your record is locked and another thread tries to commit changes, the platform will retry for roughly 5 -10 seconds before failing with a “Resource Unavailable” error. For end users, I believe if they try to save a locked record from the Salesforce.com UI, they will receive an error message stating that the record has been changed and that they should reload the page. I can’t confirm but I’ve seen this in the past.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .