I have a shared Map type instance variable that I want to process after all batches are executed.

public Map<String,List<ID>> territoryClientIDMap=new Map<String,List<ID>>();

I have some questions here:

  1. When I put the logic of processing the Map into finish() method, the Map seems to be empty. Is it the normal behavior that the instance variable is cleaned after all batches are processed or I messed something up?

  2. Is it necessary to explicitly specify "Database.Stateful" in order to have a variable to store values from all batches? I removed that "Database.Stateful" and checked the size of my Map variable but it seems like to map is not cleaned on each execution.

  3. Since I want to process the shared variable after all batches are processed, and I want to put the logic in the execute method, I need to judge if it's that last batch in the execute method. How am I able to do that?

1 Answer 1



1) If you do not implement Database.stateful all member variables will be reset to default or will be null if not initialized with declaration

2) Perhaps the Map is initialized in execute method. Or you have initialised it with declaration. It is unexpected.

3) Query on AsyncApexJob object it has two fields "JobItemsProcessed" and "TotalJobItems". You can leverage these fields to calculate the last chunk of batch. Id of current batch can be get by BatchContext instance method getTriggerId() ex: bc.getTriggerId();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.