Stateful and Stateless in Batch Apex

Using Stateful Batch Apex

If your batch process needs information that is shared across transactions, one approach is to make the Batch Apex class itself 
stateful by implementing the Stateful interface. This instructs Force.com to preserve the values of your static and instance 
variables between transactions.

global class SummarizeAccountTotal implements Database.Batchable<sObject>, Database.Stateful
{
global final String Query;
global integer Summary;
global SummarizeAccountTotal(String q)
{
Query=q;
Summary = 0;
}
 
global Database.QueryLocator start(Database.BatchableContext BC)
{
return Database.getQueryLocator(query);
}
 
global void execute(Database.BatchableContext BC, List<sObject> scope)
{
for(sObject s : scope)
{
Summary = Integer.valueOf(s.get('total__c'))+ Summary;
}
 
}
 
global void finish(Database.BatchableContext BC)
{
 
}
}


In Short if you need to send a mail to check number of record pass and failed in batch job counter in that case can you 
Stateful batch job. If you want to create one counter and share/ use in each execute method use same.


Using Stateless Batch Apex

Batch Apex is stateless by default. That means for each execution of your execute method, you receive a fresh copy of your 
object. All fields of the class are initialized, static and instance.

global class SummarizeAccountTotal implements Database.Batchable<sObject>
{
}

Comments

Popular Posts