Activity Forums Salesforce® Discussions What is Database.Stateful used for in batch class in Salesforce?

  • Deepak

    Member
    February 25, 2020 at 6:45 am

    Hi Aditya,

    You will need Database.Stateful is when the execute method modifies a class variable in such a way that it is to be used across multiple execute methods or in the finish method. The majority of batches you will 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?"

    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.

    Fact is 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.

  • Manish

    Member
    February 25, 2020 at 12:51 pm

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

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos