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
minciminci 

Another Batch Apex issue: class members.

I wrote somthing like this to check the way class fields are

behaving in Batch apex:

This code counts number of times execute method was called

For my surprise I saw that I get only 1 in the debug logs!

 

Code:

global class To_Bach implements Batchable{

 

global Integer _i;

 

global Bach(){

   _i = 0;

}

 

global

 

global void execute(){

   _i++;

   System.debug('times visited '+i);

}  

 

}

 

SO! How thies field behave?

What am I missing?

Thanks!

grigri9grigri9

By default each execution of a batch apex job is considered a discrete transaction. To maintain state across transactions you have to declare the class as database.stateful. 

 

I.E.

 

 

global class To_Bach implements Database.Batchable<sObject>, Database.Stateful{

   global integer i;
   global final string query;
global To_Bach(string q){
i = 0;
query = q; } global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<sObject> scope){
i++;
system.debug('times visited: '+i); } global void finish(Database.BatchableContext BC){ } }