[SalesForce] Why does the value of Static variables in batch context reset for each transaction

As part of the batch context, the static variables get reset at each transaction irrespective of Stateful/Stateless.

class batch_test implements database.batchable, database.stateful () {
   static int value =1;
   start () {
      value =2 ;
   }

   execute () {
      System.debug ( value  ) ; // this will print 1 and not 2 
   }
   finish () {
       System.debug ( value  ) ; // this will print 1  

   }
}

Does anyone know why does database.stateful not persist state for static variables and only for instance variables ?

Best Answer

As Bri mentioned, static variables persist for the duration of the execution context in Apex. start(), finish(), and each invocation of the execute() method operate in separate execution contexts, so static variables are reset in the same way they would be reset in separate trigger executions.

Implementing Database.Stateful allows you to use member variables that act in the way you're expecting in this case.

global class batch_test implements Database.Batchable<sObject>, Database.Stateful {
    global Integer value = 1;
    global Database.QueryLocation start(Database.BatchableContext BC) {
        value = 2;
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        // this will print 2 the first execution, and so on...
        System.debug(value++);
    }

    global void finish(Database.BatchableContext BC) {
        // this will print 2 + however many batches were executed
        System.debug(value);
   }
}