0

I have a batch which stores some information in stateful variable. My question is whether that variable will retain the value in next 'execute' if governor limit occurred in current 'execute'? Consider below code.

global class MyBatch implements Database.Batchable<sObject>, Database.stateful{

    integer stateFullCount = 0;

    global void execute(Database.BatchableContext bc, List<Account> scope){

       stateFullCount++;
       system.debug( stateFullCount );
       if(stateFullCount == 2){
            //Dummy governor limit SOQL rows:510000
            list<account> lstAccount = [select id from account limit 51000];       }
    }
}

If we dry run above code, what will be value for stateFullCount?

1st Execute: debug shows -> stateFullCount as 1;

2st Execute: debug shows -> stateFullCount as 2; //governor limit occurs.

3st Execute: debug shows -> stateFullCount as ?; ( here it will be 2 or 3? if 2 then how to achieve it to retain the value as 3?)

1
  • Maybe it is rhetorical question, but what did you get when you ran the batch?
    – manjit5190
    Commented May 14, 2020 at 15:34

1 Answer 1

0

If the batch suffers a fatal exception (governor limits, uncaught exception, etc), its state is not serialized at the end of the transaction, so it will remain 2 in this theoretical example. There is no way to recover the state if a LimitException occurs. You can see an event via BatchApexErrorEvent, but this won't allow you to update the batch's internal state.

3
  • Hi @sfdcfox, I'm encountering a similar issue. Seems like my member variable does not retain state across batches when they fail, although I do use try/catch and the exception (SObject row was retrieved via SOQL without querying the requested field) for logging. Is this expected? Or the fact that we catch the exception, should make the variable retain states across executions?
    – EranV
    Commented Jan 22, 2021 at 23:01
  • 1
    @EranV If your transaction completes successfully, the state is updated. If you do not catch the exception, the state is not updated. Did the log for the execution state Success? If not, that would be the cause. You may want to ask a separate question with your code, I'd be glad to review it.
    – sfdcfox
    Commented Jan 22, 2021 at 23:20
  • Found the issue, the exception was thrown inside a loop, so the rest of the iterations were skipped and the remaining records did not accumulate into the stateful variable. Thanks!
    – EranV
    Commented Jan 25, 2021 at 22:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .