Sub topic 3
Carrying state in member variables
This chapter assumes you can write basic Apex classes, understand governor limits and transactions, and know SOQL and DML. You should also have seen a minimal Queueable class with execute and System.enqueueJob. Here you will learn how a queueable job gets its input and what survives from one job to the next.
Why a job needs explicit state
A queueable job runs in its own transaction, later than the code that enqueued it. The enqueuing transaction has usually finished by then. Local variables are gone, and static variables are reset, because each transaction starts with fresh static state.
The only data a job can rely on is the data stored in the job object. Apex serializes the Queueable instance when you call System.enqueueJob. It rebuilds the instance in the new transaction and calls execute on the copy. Whatever you put in member variables before enqueuing is what the job sees.
The constructor pattern
The usual pattern has three parts:
- Declare
privatemember variables for everythingexecuteneeds. - Assign them in the constructor.
- Read them in
execute.
execute takes only a QueueableContext, which gives you the job ID through getJobId(). It carries no business data. All business data comes through members.
public class OpportunityCloseJob implements Queueable {
private List<Id> opportunityIds;
private String stageName;
public OpportunityCloseJob(List<Id> opportunityIds, String stageName) {
this.opportunityIds = opportunityIds;
this.stageName = stageName;
}
public void execute(QueueableContext context) {
List<Opportunity> opps = [
SELECT Id, StageName FROM Opportunity WHERE Id IN :opportunityIds
];
for (Opportunity o : opps) {
o.StageName = stageName;
}
update opps;
}
}The state is a snapshot
Serialization happens at enqueue time. The job gets a copy of the state as it was when System.enqueueJob ran. If the caller changes the original list afterwards, the job does not see the change.
List<Id> ids = new List<Id>{ firstId };
System.enqueueJob(new OpportunityCloseJob(ids, 'Closed Won'));
ids.add(secondId); // The queued job still has only firstId.The same applies in the other direction. Changes the job makes to its members do not flow back to the caller. The only way to pass data forward is to build a new job object and enqueue it.
Pass IDs, not records
You can store sObject records in a member variable. The record is then a snapshot too, and it can be stale by the time the job runs. Another user or process may change the record in the meantime. If your job updates the stale copy, it can overwrite newer values.
Prefer to store IDs and query the current records inside execute. This also keeps the serialized state small. Pass whole records only when the data does not exist in the database yet, such as a list of new records built in memory.
Choosing types that serialize well
Members can be primitives, collections of primitives, IDs, sObjects, and instances of your own classes. A custom class is fine if its own members are serializable. A small inner class is a good way to bundle several values into one object.
Keep these points in mind:
- Large state costs heap in two transactions: the one that builds it and the one that runs the job.
- A member that Apex cannot serialize causes an exception when you enqueue, so you find out early.
- Mark a member
transientto leave it out of serialization. After the job is restored, a transient member isnull(or the default for its type).
A transient member is useful for data you can rebuild cheaply, such as a lookup map. Rebuild it lazily in execute:
public class RegionJob implements Queueable {
private List<Id> accountIds;
private transient Map<String, Id> ownerByRegion; // not serialized
public RegionJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
private Map<String, Id> getOwners() {
if (ownerByRegion == null) {
ownerByRegion = new Map<String, Id>();
for (User u : [SELECT Id, Department FROM User WHERE IsActive = true LIMIT 200]) {
ownerByRegion.put(u.Department, u.Id);
}
}
return ownerByRegion;
}
public void execute(QueueableContext context) {
Map<String, Id> owners = getOwners();
System.debug('Loaded ' + owners.size() + ' owners');
}
}Static variables do not carry over
Static variables look like shared state, but they live only for one transaction. Suppose the caller sets MyConfig.mode = 'fast' and then enqueues a job. In the job's transaction, MyConfig.mode is back to its initial value. Copy any static value you need into a member variable before enqueuing.
| Mechanism | Survives into the job? | Notes |
|---|---|---|
| Member variable | Yes, as a snapshot | The standard way to pass input |
| `transient` member | No | Reset to default after restore |
| Static variable | No | Reset in each transaction |
| Local variable | No | Gone when the method returns |
| Database record or custom setting | Yes | Read current values with a query |
Accumulating state across a chain
Chained jobs let a job hand updated state to its child. This is how you keep a running total across slices of a large data set. The next job receives whatever you pass to its constructor, so put the counters in an object and pass it along.
public class ScoreAccountsJob implements Queueable {
public class Progress {
public Integer processed = 0;
public Integer failed = 0;
}
private static final Integer CHUNK_SIZE = 200;
private List<Id> remaining;
private Progress progress;
public ScoreAccountsJob(List<Id> remaining) {
this(remaining, new Progress());
}
public ScoreAccountsJob(List<Id> remaining, Progress progress) {
this.remaining = remaining;
this.progress = progress;
}
public void execute(QueueableContext context) {
Integer n = Math.min(CHUNK_SIZE, remaining.size());
List<Id> current = new List<Id>();
List<Id> rest = new List<Id>();
for (Integer i = 0; i < remaining.size(); i++) {
if (i < n) {
current.add(remaining[i]);
} else {
rest.add(remaining[i]);
}
}
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :current];
for (Account a : accounts) {
a.Rating = 'Warm';
}
List<Database.SaveResult> results = Database.update(accounts, false);
for (Database.SaveResult sr : results) {
if (sr.isSuccess()) {
progress.processed++;
} else {
progress.failed++;
}
}
if (!rest.isEmpty() && !Test.isRunningTest()) {
System.enqueueJob(new ScoreAccountsJob(rest, progress));
} else {
System.debug('Done. Processed=' + progress.processed
+ ' Failed=' + progress.failed);
}
}
}The overloaded constructor keeps the first call simple. A caller writes System.enqueueJob(new ScoreAccountsJob(ids)), and each later job gets the same Progress object with its counters updated. The Progress object is serialized again at each enqueue, so it must stay small. Counters are ideal. A list of every processed ID is not, because it grows with every slice.
Common errors
- Stale records. Passing queried sObjects and updating them later can overwrite newer data. Pass IDs and re-query.
- Expecting a static to persist. A job that reads a static set by the caller sees the default value instead.
- Expecting the caller's variable to update. The job works on a copy, and the caller's variable does not change. If the caller needs results, write them to a record or read them from the job's effects.
- Unbounded state. State that grows each run, such as an ever-longer list of results, eventually hits heap limits. Store results in records and keep only counters or cursors in the job.
- Using
transientwithout rebuilding. The member isnullinexecute. Check fornullbefore use. - Missing no-argument constructor worries. A
Queueabledoes not need a no-argument constructor. Constructors with parameters are the normal way to supply state.
Summary of the working model
State is whatever the job object holds at the moment you enqueue it. Apex serializes it once, restores it in a new transaction, and never syncs it back. Keep the state small, prefer IDs to records, and copy statics into members. When a chain needs memory, pass an updated object to the next constructor.
Exercise
A caller builds List<Id> ids, enqueues new MyJob(ids), and then calls ids.clear() on the next line. What does MyJob.execute see in its member list, and why? What would you change if the job also needs the current Name of each account?
Show answer
It sees the original IDs. The job instance is serialized when System.enqueueJob runs, so later changes to the caller's list do not affect the copy. For the current Name, do not store account records. Query them by ID inside execute, so the job reads current values instead of a snapshot.
Exercise
A developer sets static Boolean skipTrigger = true; in a helper class and then enqueues a job whose execute reads Helper.skipTrigger. The job sees false. Explain the cause and give a fix.
Show answer
Static variables last for one transaction. The job runs in a new transaction where skipTrigger has its initial value. Fix it by passing the value in the constructor and storing it in a member variable, for example new MyJob(ids, true). Then set Helper.skipTrigger from that member at the start of execute.