Suggested answer

By default, Batch Apex re-instantiates the class between each execute() call, resetting all instance variables. Database.Stateful is an interface that, when implemented, preserves instance variables across all execute() chunks. Use cases:

1. Accumulating running totals (total records processed, total errors).
2. Building a summary to include in the finish() notification email.
3. Tracking which records were processed for a final reconciliation. Trade-off: Stateful batches consume more heap memory as state is serialised between chunks. Keep state variables lightweight (primitives, small collections). Example: public class MyBatch implements Database.Batchable<sObject>, Database.Stateful { Integer errorCount = 0; ... } — errorCount persists across all execute() calls.

Practice content for interview preparation; not an official vendor answer. Verify details against current product documentation.

Community comments (0)

No comments yet.

Sign in or create a free account to add a comment. Comments are moderated before they appear.

Plain text only, 3–2000 characters. A moderator reviews every comment before it is published.