Using Stateful Batch Apex

Batch Apex is stateless by default. That means for each execution of your execute method, you receive a fresh copy of your object. All fields of the class are initialized, static and instance. If your batch process needs information that is shared across transactions, one approach is to make the Batch Apex class itself stateful by implementing the Stateful interface. This instructs Force.com to preserve the values of your static and instance variables between transactions.

To try a simple example of stateful Batch Apex, create a new Apex class with the code in Listing 9.4.

Listing 9.4 Stateful Batch Apex Sample


global class Listing9_4
  implements Database.Batchable<SObject>, Database.Stateful {
  Integer count = 0;
  global Database.QueryLocator start(Database.BatchableContext context) {
    System.debug('start: ' + count);
    return Database.getQueryLocator(
      [SELECT Name FROM Project__c ORDER BY Name]);
  }
  global void execute(Database.BatchableContext context,
    List<SObject> scope) {
    System.debug('execute: ' + count);
    for(SObject rec : scope) {
      Project__c p = (Project__c)rec;
      System.debug('Project ' + count + ': ' + p.Name);
      count++;
    }
  }
  global void finish(Database.BatchableContext context) {
    System.debug('finish: ' + count);
  }
}


Take a moment to examine the differences between this class and the original, stateless version. Implementing the interface Database.Stateful is the primary change. The other changes are simply to provide proof in the debug log that the value of the count variable is indeed preserved between transactions.

Run the modified class with a scope of two records and examine the debug log. Although the log entries might not be ordered in any discernible way, you can see all the Project records have been visited by the batch process. Assuming you have six Project records in your database, you should see a total of six new debug log entries: one to begin the batch, one for the start method, three entries’ worth of transactions (of two records each), and one for the finish method.

Notice the value of the count variable throughout the debug output. It begins at 0 in the first transaction, increments by two as Project records are processed, and begins at 2 in the second transaction. Without implementing Database.Stateful, the count variable would remain between 0 and 2 for every transaction. The value of the count variable is 6 when the finish method is reached.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.164.143