Sub topic 12
Queueable, future, and batch: static state resets
This chapter assumes you can write an Apex trigger, you know what a static variable is, and you have read the chapters on the static Boolean flag and the static Set of Ids. It explains why those guards stop working once your code crosses into asynchronous Apex.
Static state belongs to one transaction
A static variable lives for the length of one transaction. Queueable jobs, @future methods, and batch Apex each run in their own new transaction. That new transaction starts with fresh static variables, so every guard you set earlier is back to its initial value.
The result is a common surprise. Your trigger sets hasRun = true, enqueues a job, and the job updates the same records. The update fires the trigger again. In this new transaction hasRun is false, so the guard lets the logic run a second time.
An example of the loop
This trigger and job form a loop that static guards cannot break.
trigger AccountTrigger on Account (after update) {
if (!System.isFuture() && !System.isBatch() && !System.isQueueable()) {
System.enqueueJob(new AccountReviewJob(Trigger.newMap.keySet()));
}
}public class AccountReviewJob implements Queueable {
private Set<Id> accountIds;
public AccountReviewJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> toUpdate = new List<Account>();
for (Id accId : accountIds) {
toUpdate.add(new Account(Id = accId, Description = 'Reviewed'));
}
update toUpdate;
}
}The trigger checks System.isQueueable(), System.isFuture(), and System.isBatch(). These methods report which kind of asynchronous context the current code runs in, so the trigger does not enqueue another job from inside one. Without the check, each job would update the records, fire the trigger, and enqueue the next job. Salesforce limits how deep a chain of queueable jobs can go, but you should not rely on that limit to stop your code.
Guards that survive the boundary
Because statics reset, the guard has to rely on data that persists. These options work across transactions:
- Changed-field check. Compare new and old values, as in the earlier chapter. The data itself records whether work is needed, so it works in every transaction.
- A field on the record. Set a checkbox or a status value such as
Reviewed__c, and skip records where it is already set. This costs a field and an extra update, but it is reliable. - Context checks. Use
System.isFuture(),System.isBatch(), andSystem.isQueueable()to skip the enqueue step when you are already asynchronous. - A bypass switch. Pass a flag into the job and set the handler's bypass before the job's DML, so the job does not trigger its own follow-up work.
public void execute(QueueableContext context) {
AccountTriggerHandler.bypass = true;
try {
update buildUpdates();
} finally {
AccountTriggerHandler.bypass = false;
}
}This bypass is a static, but it is set inside the same transaction as the update, so it works. The finally block restores the value even if the update throws.
Batch Apex and chunks
A batch job runs execute once per scope, and each scope is its own transaction. Statics reset between scopes. A static Set of Ids will not remember records from an earlier scope. Records in different scopes are different records, so this is usually harmless, but it means you cannot use statics to count or deduplicate across a whole batch run. Use Database.Stateful for state you need to carry between scopes.
Exercise
A trigger sets a static Boolean hasRun and enqueues a Queueable that updates the same records. The trigger fires again from the job's update and enqueues another job. Why did the static flag not stop this, and name two fixes.
Show answer
The Queueable runs in a new transaction, and static variables reset for each transaction, so hasRun is false again. Fixes include checking System.isQueueable() before enqueueing, comparing changed field values, setting a field on the record that marks it as processed, or setting a bypass switch around the job's DML.