1

When sharing Static Variables between a Trigger Context and an Async Operation such as Batch Apex, is it possible for there to be a conflict between the two? For example, say I have a Trigger that does some processing on some data, but if that dataset is too large, I default to a Batch Class that does the same operation, but limits the amount of data within the context. To reduce code overhead, a helper class is created with Static Variables and code that can be referenced from both the Trigger, and the Batch Apex contexts.

Now lets say that the Trigger is executed again immediately after executing Batch Apex. What would be the consequences of the Trigger firing while the Batch Apex job is running?

Is it possible that one of these processes could overwrite data in a Static Variable set by the other, or do they have two separate instances that execute in different threads?

4
  • Wouldn't the batch and trigger be different transactions? I'm not sure I understand the use case – adriancg Jun 23 '20 at 18:33
  • I understand that they are different transactions. I guess that my question is do they share the state of the helper class static variables since new instances of the class methods and variables are not being explicitly created, or do they continue on different threads with multiple instances running concurrently? – 02384705287409872098374 Jun 23 '20 at 18:42
  • 1
    AFAIK static variables are scoped to the transaction. So the new transaction will have whatever default values are set in the code. – adriancg Jun 23 '20 at 18:45
  • @adriancg - post as the answer - static variable values apply only to the transaction; never shared across transactions - batch apex and trigger context initiated by user will be diff transactions – cropredy Jun 23 '20 at 19:39
2

Static variables are scoped to the transaction. So any new transactions from batch apex or triggers will have whatever default values are set in the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.