2

All the samples I've seen of Apex trigger handlers have them calling static methods in a helper/service class. What happens when a second trigger of the same type (say after insert) on the same object happens before that static method has finished executing? Will the second trigger call that static method and take over its execution - changing records, variables, etc?

This reveals my ignorance, but I've tried to figure this out on my own (using Google, etc.) without success.

Help/guidance/explanation would be greatly appreciated.

1 Answer 1

3

Triggers are never run in parallel within the same transaction. You don't need to worry about thread safety or reentrancy in your handler classes.

Take an example. User A updates 400 records via custom Apex functionality in a single transaction. Triggers execute in 200-record chunks, so the (very simplified) sequence of events runs

1. before update (records 1-200)
2. after update (records 1-200)
3. before update (records 201-400)
4. after update (records 201-400)

Of course, it gets more complicated if there's recursion involved, but fundamentally, everything in the scope of this one transaction runs in sequence.

But suppose during Step 2, some other user B goes into the UI and updates one record. Don't we have a Step 2.5: before update...?

We don't. User B's changes happen in a separate transaction running in parallel. User B's changes get a separate trigger invocation sequence, and any Apex code called by each trigger invocation has static variables that are scoped to the transaction. You never have to worry about these two triggers crossing wires in memory.


Where you can encounter problems with parallelism is in the database. For example, if some code in Transaction A accesses the database, then Transaction B commits and alters the database, then Transaction A commits data calculated from its original access... Transaction A's results might be wrong. This pattern is not particularly common, but can in some forms by solved by using FOR UPDATE SOQL statements to acquire a lock on specific records so that your transaction can complete work atomically, without allowing other transactions to alter those records in the meantime.

1
  • Thank you David. The key statement was, "any Apex code called by each trigger invocation has static variables that are scoped to the transaction."
    – djklord
    Mar 3, 2021 at 16:13

You must log in to answer this question.

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