In Salesforce, batch Apex allows you to process large volumes of records asynchronously. A key concept in batch processing is whether the batch class is stateful or stateless, which determines how the class handles instance variables across transaction boundaries.
1. Stateful Batch Apex
A stateful batch class maintains the values of instance variables between transactions. This means that data stored in instance variables persists across different chunks (or "batches") of records processed. This is particularly useful when you need to accumulate data or maintain a state that is updated with each batch execution.
To implement a stateful batch, you need to use the Database.Stateful interface in addition to Database.Batchable.
Example: Accumulating Total Number of Processed Records
global class MyStatefulBatch implements Database.Batchable<SObject>, Database.Stateful {
private Integer totalProcessed = 0;
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id FROM Account]);
}
global void execute(Database.BatchableContext bc, List<SObject> scope) {
// Process the current batch
totalProcessed += scope.size();
}
global void finish(Database.BatchableContext bc) {
// Log the total number of processed records
System.debug('Total processed records: ' + totalProcessed);
}
}
In this example, the totalProcessed variable accumulates the number of records processed across all batches, allowing you to log the total once all batches are complete.
2. Stateless Batch Apex
A stateless batch class does not maintain the values of instance variables between transactions. Each execution of the execute method is independent, and there is no carryover of variable values from one batch to the next. This is the default behavior of batch classes if Database.Stateful is not implemented.
Example: Independent Processing of Records
global class MyStatelessBatch implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id FROM Account]);
}
global void execute(Database.BatchableContext bc, List<SObject> scope) {
// Process the current batch independently
System.debug('Processing batch with ' + scope.size() + ' records');
}
global void finish(Database.BatchableContext bc) {
System.debug('Batch processing complete');
}
}
In this example, each batch is processed independently, with no accumulation or carryover of data between batches.
Conclusion
Understanding the difference between stateful and stateless batch Apex is crucial for implementing effective batch processes in Salesforce. While stateful batches are useful for tasks that require accumulation or state maintenance across transactions, stateless batches are ideal for independent processing where each batch stands alone.
Comments