Sub topic 6
Static Variables Live for One Transaction
This chapter assumes you can write a simple Apex trigger, use List, Set, and Map, and issue DML statements such as insert and update. It also assumes you know that governor limits apply per transaction. Static variables are the tool that most recursion guards depend on, so you need a precise model of how long they live and who can see them.
What a static variable is
A static variable belongs to the class, not to an instance of the class. Apex keeps one copy of it for each transaction. Every piece of code that runs in that transaction reads and writes the same copy, whether it is a trigger, a handler class, a flow-invoked action, or a helper method.
public class Counter {
public static Integer calls = 0;
public static void hit() {
calls++;
}
}If trigger code calls Counter.hit() three times during one transaction, Counter.calls is 3 at the end. An instance variable does not behave this way. Each new object gets its own copy, so a trigger that creates a new handler object on every firing would start with fresh state each time.
What "transaction" means here
A transaction is the full set of operations Salesforce treats as one unit of work. It starts when a request begins, for example a user clicking Save, an API call, or a test method. It ends when the request commits or rolls back.
Static state is created when the transaction first touches the class. It is discarded when the transaction ends. The next transaction starts with the initial values again.
The following table shows where the boundary falls.
| Situation | Same static state? |
|---|---|
| A trigger fires, runs DML, and the same trigger fires again | Yes, same transaction |
| A trigger calls a method in another class | Yes |
| A workflow field update causes the trigger to re-fire | Yes |
| Two separate users save records at the same time | No, each has its own transaction |
| A second save by the same user a minute later | No, new transaction |
| A `@future`, Queueable, or Batch job started by the trigger | No, the job runs in its own transaction |
The last row matters for recursion guards. A guard cannot stop an asynchronous job from running its own logic, because that job sees fresh static values. A later chapter covers this in detail.
Static state across trigger re-entry
When a trigger runs DML on the same object, Salesforce starts the trigger again inside the same transaction. This is why a static variable works as a guard. The first firing sets a value, and the second firing can read it.
Both firings belong to one transaction, so both see the same hasRun. When the transaction commits, the variable disappears.
Initialization and default values
A static variable is initialized once, the first time the class is used in a transaction. You can set the initial value inline or in a static block.
public class GuardState {
public static Boolean hasRun = false;
public static Set<Id> processedIds = new Set<Id>();
}Two details cause bugs.
- A
Booleandeclared without a value isnull, notfalse. Writingif (!hasRun)against a null Boolean throws aNullPointerException. Always give a Boolean guard an explicit initial value. - A collection declared without
newis alsonull. CallingprocessedIds.contains(...)on a null Set fails the same way.
Scope inside a single transaction
Static variables are not scoped to a trigger. They are scoped to a class. This gives you a useful design choice.
- A guard in
AccountTriggerHandleris shared by every code path that calls that class during the transaction. - A guard in a separate class is shared by every trigger that reads it.
- Two different classes with two different static variables do not interfere with each other.
A common mistake is to place a static flag in a class that several unrelated triggers use, and then set it from one of them. The other triggers see the flag as true and skip logic they should have run. Give each guard a clear owner and a name that says what it protects.
A demonstration you can run
The following anonymous Apex shows that static state survives repeated calls inside one execution and that the value is shared. Run it in the Developer Console under Debug and Open Execute Anonymous Apex.
public class StaticDemo {
public static Integer counter = 0;
public static void increment() {
counter++;
System.debug('counter = ' + counter);
}
}
StaticDemo.increment();
StaticDemo.increment();
StaticDemo.increment();
System.assertEquals(3, StaticDemo.counter);Defining a class and using it in the same anonymous block is not allowed in every context. If your org rejects it, save StaticDemo as a class first, then run only the last four lines as anonymous Apex. The debug log shows 1, 2, and 3. The next time you run the anonymous block, counter starts at 0 again, because each execution is its own transaction.
Static state and tests
Each test method runs in its own transaction, so static values start fresh for every @IsTest method. Within one test method, the setup and the code between Test.startTest() and Test.stopTest() share the same static state, with one exception. Test.startTest() resets governor limits, but it does not reset static variables.
This has a practical effect. If you insert a record during test setup and that insert runs your handler, a Boolean guard may already be true when you reach the update you want to test. The guard then skips your logic, and the assertion fails for a reason that does not exist in production. You have two ways to handle this.
- Keep test setup free of DML that fires the guarded handler. Use
Test.startTest()after setup, and make the handler's guard apply only to the event under test. - Provide a reset method on the guard class, used only from tests.
public class AccountTriggerHandler {
@TestVisible
private static Boolean hasRun = false;
@TestVisible
private static void resetForTest() {
hasRun = false;
}
}@TestVisible lets a test class read or change a private member without making it public to production code. Use this sparingly. A guard that needs a reset in every test often points to a design problem, such as a Boolean that is too coarse for the data it protects.
Rollback and static state
A rollback does not restore static variables. If you set a savepoint, set a guard to true, and then call Database.rollback(sp), the database changes are undone but the Boolean stays true.
public class RollbackDemo {
public static Boolean flag = false;
public static void run() {
Savepoint sp = Database.setSavepoint();
flag = true;
insert new Account(Name = 'Temp');
Database.rollback(sp);
System.debug('flag after rollback = ' + flag); // still true
}
}The same applies when a partial-save DML call, such as Database.update(records, false), fails on some records. The guard has already marked those records as processed even though they were not saved. If you add an Id to a processed Set before the DML, a failed record will never be retried in that transaction. When correctness depends on the save succeeding, add Ids to the Set only for records you know were processed, or check the Database.SaveResult before treating them as done.
Limits of the model
Keep these points in mind when you rely on static variables.
- Static state is per transaction and per Apex runtime context. It is not shared across users, requests, or asynchronous jobs.
- A static variable is not persistent storage. If you need data to survive past the transaction, store it in a record, a custom setting, or Platform Cache.
- A static variable remembers only what you tell it. It does not know which records, which fields, or which 200-record chunk it is being asked about. A single Boolean carries one bit of information, which is why it can be too coarse. The next chapters build on that point.
Summary of the model
- One copy of a static variable exists per class per transaction.
- Trigger re-entry caused by DML or a workflow field update happens in the same transaction, so static state is shared.
- Static state is not reset by
Test.startTest()or byDatabase.rollback. - Static state is not shared with Queueable, future, or Batch jobs, which run in their own transactions.
- The value lasts until the transaction commits or fails, then it is gone.
Exercise
A trigger sets hasRun = true on a static Boolean, then runs Database.rollback(sp) to a savepoint taken before the flag was set. What is the value of hasRun afterward, and why does it matter for a recursion guard?
Show answer
It is still true. A rollback restores database changes, not static variables. For a recursion guard this means that records whose changes were rolled back are still treated as handled, so the logic will not run for them again in the same transaction.
Exercise
A trigger on Account enqueues a Queueable job. The job updates the same Accounts, which fires the trigger again. The trigger has a static Boolean guard that was set to true. Does the guard stop the logic in the second trigger firing? Explain.
Show answer
No. The Queueable job runs in its own transaction, which starts with fresh static values, so hasRun is false again. The guard does not carry over, and the logic runs a second time.
Exercise
Why does a test that inserts an Account in setup, then updates it after Test.startTest(), sometimes fail to run guarded logic on the update?
Show answer
The insert may have run the handler and set a static Boolean to true. Test.startTest() resets governor limits but not static variables, so the guard is still true when the update fires and the logic returns early.