function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sai krishna 267sai krishna 267 

what is the use of database.stateful interface in batchapex?

RKSalesforceRKSalesforce
Hi Sai,

The only time you need Database.Stateful is when the execute method modifies a class variable in a way meant to be used across multiple execute methods or in the finish method. The majority of batches you will ever write will not need Database.Stateful. It's important to know that using Database.Stateful will harm your batch's performance, because the class will be serialized at the end of each execute method to update its internal state. This extra serialization results in longer execution time.
If you're ever not sure if you need it, simply ask yourself two questions: (1) "Does one execute method need data from a previous execute method?", and (2) "Does the finish method need data from any previous execute method?" If the answer to both of these questions is no, then you do not need Database.Stateful. If the answer is yes, then you may want to use Database.Stateful. Keep in mind that there are alternative means to using Database.Stateful, such as storing data in a Custom Setting, which may offer better performance in some cases.
eg. Let's say you  are processing All Contacts in your execute method. And in the finish method of your batch you need to send email to all processed contacts. In this case we need to implement database.Stateful.

PLease mark as best answer if helped.

Regards,
Ramakant