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
Vinnie BVinnie B 

Variables always reset in the execute function of a Batch Apex class

I have a fairly simple batch apex class that goes through contact records.  I'm trying to get a total count of the number of items that are being processed in a batch apex run.  The problem is the variable, numberOfContacts, is always reset to its default value when entering the execute loop.

I have a feeling that the issue of this being a variable in a global class is causing the problem.  Does that make sense?  If so, is there a way around this?

Thanks!!

---

global class OrgDashboardBatchable implements Database.Batchable<SObject> {
 
  global String glstrQuery;
  global List<SObject> gllstScopeRecords;

  private Integer numberOfContacts = 0;
  private ID theODB_ID;

  global OrgDashboardBatchable(ID odbID) {
    glstrQuery = 'SELECT Id FROM Contact WHERE cv__Active__c = TRUE';
    theODB_ID = odbID;
  }
 
  global Database.QueryLocator start(Database.BatchableContext bc) {
    return Database.getQueryLocator(glstrQuery);
  }
 
  global void execute(Database.BatchableContext bc, List<SObject> lstBatchRecords) {
   
    //  The first debug message is always zero.  The second does show the size of this batch.
    gllstScopeRecords = lstBatchRecords;
    System.debug('In execute: numberOfContacts1 = ' + numberOfContacts);
    numberOfContacts += gllstScopeRecords.size();
    System.debug('In execute: numberOfContacts2 = ' + numberOfContacts);
  }
 
  global void finish(Database.BatchableContext bc) {
   
    //  Code that works correctly
 
 }
  
}
Best Answer chosen by Vinnie B
Vinnie BVinnie B
Figured this out myself.  You just need to define the class to implement Database.Stateful as well.

global class OrgDashboardBatchable implements Database.Batchable<SObject>, Database.Stateful {