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
Paras JainParas Jain 

Why Static variables loose their state in batch class during every execution

why static variables loose their state in batch class during every execution.
 
NagendraNagendra (Salesforce Developers) 
Hi Paras,

May I suggest you to please check with below link which might help you with above question. Please let us know if anything else is required.

Regards,
Nagendra.
Ramssf70Ramssf70
Hi paras Jain,

Not only static variable ,every variable will lose their state in the batch class why because once the batch is completed all the values  will be initialised to null that is how the excuetion happening in the salesforce for my understanding .If you  want to maintain the state in the batch class you need to use  Database.stateful
global class Class_Name implements Database.Batchable<sobject>, Database.Stateful{
    Integer i = 0;
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocatory('SELECT Id, Name, Sequence_Number__c FROM Employee__c');
    }
    
    global void execute(Database.BatchableContext bc, List<Employee__c> listEmployee){
        for(Employee__c e : listEmp){
            e.Sequence_Number__c = i;
            i += 1;
        }
    }
    
    global void finish(Database.BatchableContext bc){
    }
}

here i value will be maintained even though execute method is called several times.

Thank you
Paras JainParas Jain
hi for every execution all the variable loose their state but why?
Ramssf70Ramssf70
Hi Paras,

By default salesforce excuete the batch class like this from my understanding because  it it will not initialise to null there is chance to exist previous data  then the batch class will fail.
if you will not initialise to null
Let us assume you have excueted the batch with 200 records by five batches after excuetion of one batch list having 200 records again if we excuete the batch next two hunderd records will add to batch then list will be having 400records then the batch class can not excuete four hundered records at the the same then batch will fail like that there is a chance to happen like that 
Thanks
Ramssf70Ramssf70
Hi Paras,

By default salesforce excuete the batch class like this from my understanding because  it it will not initialise to null there is chance to exist previous data  then the batch class will fail.
if Salesforce not initialise to null
Let us assume you have excueted the batch with 200 records by five batches after excuetion of one batch list having 200 records again if we excuete the batch next two hunderd records will add to batch then list will be having 400records then the batch class can not excuete four hundered records at the the same then batch will fail like that there is a chance to happen like that 
Thanks