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

Before Update Trigger and DML operations

We have two custom objects, say object A and object B. Object A has a before update trigger. The trigger does the following


a) Query object B records

b) Perform some business logic

c) Update object B records.


Assume, there are 10 records being updated in object A. Since there is a before update trigger, the trigger fires and runs for all the ten records.  Also, please keep in mind that as trigger executes for those 10 records, the records in object B are updated using an update DML statement. Currently, the updates to custom object B is a bulk update ( i.e. it creates a list of object B instances with new values, and runs the update DML finally on the list of Object B's ) During this process of execution ( i.e. trigger for 10 records has not completed its execution) , assume another 15 records are updated in object A. Now my doubt is, would this trigger execution ( 15 records execution flow)  see the updated values of object B during step a)  of the trigger mentioned above ? The key to the use case is that, these 15 records need to see the updated values of object B.


Also, if I do update on object B for every record, instead of doing it finally, would that help so that when the 15 records ( object A update ) come in they see updated values of object B in step a) ? I understand that there is a potential chance of hitting the governer limit here. Has anyone faced a situation like this before? Are there better alternatives or suggestions to handle this? Thanks a lot in advance for your help and suggestions.


Tricky question.


Are you doing "FOR UPDATE" in your SOQL query of B?  That should lock the rows of B, but I'm unsure if it is an exclusive or a shared lock for that short period of time.  Hopefully row locking is exclusive, and reads block.  It also might depend on whether the processes are the same user or not.  But row locking is only part of it...


I think the real question you have is are transactions processed concurrently or somehow serialized, and I believe the answer to that is they are NOT serialized.  You can have multiple Apex going at once as much as four Apex on each App Server.


My belief is that placing the phrase "FOR UPDATE" in your query of B may solve your problem, but I don't know enough of the technical details of how they are doing things behind the scenes to verify that.


Does that help?