Sub topic 8
Sharing state across batches with Database.Stateful
This chapter assumes you can write a basic Database.Batchable class with start, execute and finish methods, and that you know SOQL and DML basics.
Why instance variables reset
Each execute call runs in its own transaction. By default, Salesforce serializes the batch instance when a transaction ends and restores it from scratch for the next one. Any instance variable you changed in one execute call goes back to its initial value in the next call.
Suppose you add Integer failed = 0; to a batch class and increment it in execute. When finish runs, failed is 0 again. This is the most common surprise for developers new to batch jobs.
Adding Database.Stateful
To keep field values between calls, implement Database.Stateful next to Database.Batchable. It is a marker interface with no methods to write. Salesforce then serializes the instance at the end of each transaction and restores it, with its field values, before the next one.
Worked example
This class counts how many records were updated and how many failed. It reports both totals in finish.
public class AccountRatingBatch implements Database.Batchable<SObject>, Database.Stateful {
public Integer succeeded = 0;
public Integer failed = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Rating FROM Account WHERE Rating = null
]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
List<Database.SaveResult> results = Database.update(scope, false);
for (Database.SaveResult sr : results) {
if (sr.isSuccess()) {
succeeded++;
} else {
failed++;
for (Database.Error err : sr.getErrors()) {
System.debug('Update failed: ' + err.getMessage());
}
}
}
}
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob WHERE Id = :bc.getJobId()
];
System.debug('Status: ' + job.Status + ', succeeded: ' + succeeded + ', failed: ' + failed);
}
}Without Database.Stateful, finish would print succeeded: 0, failed: 0 no matter how many records were processed.
Costs and limits
State is not free. Keep these points in mind:
- Serialization happens after every
executecall, so a large state slows the job and can hit the heap limit. - Store totals, counters and small lists of Ids. Avoid holding every processed record or a full error message for every row.
- Fields must be serializable. Mark a field
transientif it should not be saved, for example a cached value you can rebuild. - State only moves forward through one job. It is not shared between separate jobs or between parallel runs of the same class.
Alternatives to Stateful
If you only need results after the job ends, you can skip Database.Stateful. Write a log record in each execute call, then query those logs in finish. This keeps memory use flat and survives a job that aborts partway. Use Database.Stateful when the state is small and you want it available for the next call without extra queries.
Exercise
A batch class increments an Integer field processed in each execute call and prints it in finish. The output is always 0 for a job over 5,000 records. What is missing, and what should you watch for after you fix it?
Show answer
The class must also implement Database.Stateful so field values persist between execute calls. After the fix, keep the state small, because the instance is serialized after every execute call and large collections can slow the job or exceed the heap limit.