Sub topic 6
How long static state lives: the transaction
Static variables in Apex do not live forever, and they are not shared with other users. They live for one transaction. This chapter defines that boundary, shows what shares static state and what doesn't, and covers the mistakes that follow from getting it wrong.
This chapter assumes you can read basic Apex, know that Apex runs inside Salesforce transactions, and have seen static declared on a field or method. It builds on the earlier chapter on static members.
What a transaction is
A transaction is one unit of work on the platform. It starts when something enters Apex, such as a record save, an API call, a button click, or a scheduled job. It ends when that work commits or rolls back. Governor limits (for example, 100 SOQL queries in synchronous code) are counted per transaction.
Static state follows the same boundary:
- When a class is first used in a transaction, its static variables are initialized.
- Every piece of code in that transaction sees the same static values.
- When the transaction ends, those values are discarded.
- The next transaction starts again from the initial values, even if it runs one second later on the same server.
A static variable is therefore "global" only inside the current transaction. It is not an application-wide variable.
What stays inside one transaction
Many things that look separate happen in the same transaction, so they share static state:
- A trigger on Account that updates Contacts, which fires a Contact trigger, which updates the Account again.
- Before and after trigger code on the same save.
- Flows, workflow field updates, and Apex called during the same save.
- Every method call in your own code, including calls into other classes.
This sharing is why static variables work well for the two jobs in the next sections.
Job 1: a cache that saves queries
A static map can hold data you have already queried, so the transaction does not query it again. The static variable starts as null, and the first caller fills it.
public class RecordTypeCache {
private static Map<String, Id> idsByName;
public static Id getId(String developerName) {
if (idsByName == null) {
idsByName = new Map<String, Id>();
for (RecordType rt : [
SELECT Id, DeveloperName
FROM RecordType
WHERE SobjectType = 'Account'
]) {
idsByName.put(rt.DeveloperName, rt.Id);
}
}
return idsByName.get(developerName);
}
}No matter how many times the transaction calls RecordTypeCache.getId(...), the SOQL query runs once. The next transaction pays for one query again, because the map starts out null again.
Job 2: a recursion guard
The TriggerGuard class from the plan uses a static Boolean to run logic once per transaction. It is correct for a single record, but it has a well-known flaw.
Salesforce does not hand a trigger an unlimited list of records. When a single transaction saves many records, for example a 500-row API insert, the trigger runs in chunks of up to 200 records. All chunks belong to the same transaction. With a Boolean flag:
- Chunk 1 (records 1 to 200):
shouldRun()returnstrueand sets the flag. - Chunk 2 (records 201 to 400):
shouldRun()returnsfalse. The logic is skipped. - Chunk 3 (records 401 to 500): skipped as well.
Records 201 to 500 are silently never processed. Nothing fails and no error appears.
The fix is to track which records you have handled, instead of whether anything has run:
public class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static List<Account> unprocessed(List<Account> accounts) {
List<Account> fresh = new List<Account>();
for (Account acc : accounts) {
if (!processedIds.contains(acc.Id)) {
processedIds.add(acc.Id);
fresh.add(acc);
}
}
return fresh;
}
}Each chunk passes through. A record is skipped only when it comes back a second time in the same transaction, which is what a recursive update causes.
What does not share static state
The transaction boundary matters most where developers expect continuity and don't get it.
| Situation | Is static state shared? | Notes |
|---|---|---|
| Two methods called in one save | Yes | Same transaction |
| Trigger chunks from one large insert | Yes | Same transaction, which is why a `Boolean` guard breaks |
| Two users working at the same time | No | Separate transactions |
| Two page loads or two clicks by one user | No | Each server request is its own transaction |
| `@future` method or queueable job started from your code | No | Runs later in a new transaction |
| Each `execute` call in a batch job | No | Each chunk is its own transaction |
| Two test methods in one test class | No | Each test method starts fresh |
A short batch example makes the point about execute:
public class StaticDemoBatch implements Database.Batchable<SObject> {
private static Integer calls = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Account');
}
public void execute(Database.BatchableContext bc, List<SObject> scope) {
calls++;
System.debug('calls = ' + calls); // prints 1 for every chunk
}
public void finish(Database.BatchableContext bc) {}
}You might expect calls to count up across chunks. It does not, because each execute runs in its own transaction and the static variable starts at 0 each time.
Choosing where state should live
Because static state disappears at the end of the transaction, it is the wrong place for anything that must outlast it. Use this as a rule of thumb:
- Needed only during this transaction, and shared by many classes: a static variable (cache, guard, collected results).
- Needed by one object and its methods: an instance variable.
- Needed between batch chunks: instance variables with
Database.Stateful. - Needed between transactions or users: store it, either in a custom object, a custom setting, or Platform Cache, depending on how long it must live and who must see it.
Edge cases to watch
- Initialization is lazy. A class's static variables are set up the first time the transaction uses the class, not when the transaction starts. A static initializer that does heavy work is paid for only if the class is touched.
- Constants are rebuilt every transaction. A
static finalmap, likeConfig.LIMITSearlier, is created again in each transaction. That is cheap for small values. For anything expensive, build it lazily as in theRecordTypeCacheexample. - Stale data. A static cache holds the data as it was when first read. If the same transaction changes those records later, the cache is out of date. Update the cache when you change the data, or do not cache data that your own code modifies.
- Tests. Reset happens between test methods, not inside them. If one test method runs two scenarios that depend on a guard flag, the second scenario sees the flag the first one set. Put each scenario in its own test method, or add an explicit reset method to the class for tests.
Exercise
A trigger handler uses private static Boolean hasRun = false; to avoid recursion. A data loader inserts 450 Account records in one API call. How many records does the handler process, and why? What change makes it process all 450?
Show answer
It processes only the first 200. The trigger runs in chunks of up to 200 records, and all chunks share one transaction, so the static hasRun flag is already true for the second and third chunks and the logic is skipped for the remaining 250 records. Replace the Boolean with a static Set<Id> of processed record Ids, and skip only records whose Id is already in the set.
Exercise
A batch class has private static Integer total = 0; and adds scope.size() to it in each execute call, then prints it in finish. With 1,000 records and a scope size of 200, what does finish print, and how would you fix the class?
Show answer
It prints 0 (each execute and finish run in separate transactions, each starting with a fresh static value of 0). Change total to a non-static instance variable and declare the class implements Database.Batchable<SObject>, Database.Stateful, so the platform keeps the value between chunks. Then finish prints 1000.