+ 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){ } }