What is the Database.Stateful Interface in Batch Apex?
We know Salesforce has a powerful way to do bulk processing with Batch Apex. However, I rarely come across scenarios where Database.Stateful is needed.
Batch Apex is an asynchronous process that is stateless by default. Simply put, stateless processes can be understood in isolation. There is no stored knowledge or references to past transactions. All transactions are created from scratch. This means that you get a new copy of the object each time you run the execute method.
However, if your batch process requires information shared by all transactions, you can use Database.Stateful to make your batch vertices stateful.
What exactly is Stateful?
Stateful processes are easy to understand because they run in the context of previous transactions and the current transaction can be affected by the events of previous transactions.
Making batch Apex stateful in Salesforce serializes the class and updates the internal state at the end of each executed method. This additional serialization increases execution time.
Don't forget to check out: How To Use Database.Stateful Interface In Batch Apex In Salesforce
Each execution of a batch Apex job is considered a separate transaction. For example, a bulk Apex job containing 1,000 records and executed without the optional range parameter is considered 5 transactions of 200 records each.
Stateful can be preserved between these transactions by specifying Database.Stateful in the class definition. When using Database.Stateful, then only instance member variables retain their values between transactions whereas static member variables do not retain their values and are reset between transactions. Maintaining status is useful for counting or summarizing records that are being processed. Suppose a job processed an Opportunity record. You can define an execution method that summarizes the sum of opportunity amounts as they are processed.
Omitting Database.Stateful resets all static and instance member variables to their original values.
Check out another amazing blog by Mohit here: How to Use Map In Lightning Component?
A simple example given below:
Above example Consider the first case.
Case 1: Without Stateful
Without database.stateful the count value will be reset to zero for every executed method.
Case 2: With Stateful
With database.stateful the count value will not reset for every batch executed method.