+ Start a Discussion
sonali  vermasonali verma 

stateful & stateless in batch apex

Hello friends
I just begining to understand concept of batch apex.
But pls explain what is stateful & stateless in batch apex:?
In what scenario in real time do we implement statefull & vice versa.
which is better:?

Amit Chaudhary 8Amit Chaudhary 8
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{

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>{

Please let us know if this will help you

Amit Chaudhary
sonali  vermasonali verma
as per documentation, Static variables lose their values across every transaction when using Database.stateful.
Please correct my understanding.​​
Amit Chaudhary 8Amit Chaudhary 8
In Stateless it will lose but not in statefull. Statefull batch job is used only to mantain the state.