Batch Apex running mode (parallel and series) and how to maintain state in it

In my early post, I’d shared about how to write a Schedulable Batch Apex in Salesforce, and I’ll show you how transactions run in batch Apex and how to maintain their state across these transactions in this post.

Batch Apex running mode (parallel / series)

As we know, each execution of a batch Apex job is considered a discrete transaction, so if a batch contains 1,000 records, it is considered 5 transactions of 200 records each. Batch Apex job runs in parallel if more than one job is running, but which mode these transactions in one batch Apex job run in, parallel or series?
Actually, they run in series , the following sample code and DebugLogs will explain this.

SampleBatch.cls


Debuglogs of 5 batch Apex transactions

Maintaining state

The member variables (includes static member variables) in batch Apex don’t retain their values and are reset between transactions, if you want to maintain state across these transactions, such as for counting or summarizing records, you can specify Database.Stateful in the class definition, and only instance member variables (not static member variables) retain their values, as the sample code below :

SampleBatchWithState.cls


Debuglogs of 5 batch Apex transactions


Reference : https://developer.salesforce.com/docs/atlas.en-us.204.0.apexcode.meta/apexcode/apex_batch_interface.htm

Enjoy it!