I'm implementing an apex batch process.

public class BatchName implements Database.Batchable<XYZClass.wrapper>,Database.Stateful{

I have declared an integer variable as public and assigning value to it in execute method.

Public Integer Counter=0;

When I try to access it in finish method, I am getting null value.

While declaration, when i set it to zero, I'm getting zero. I'm unable to get the assigned integer value.

I'm using the database.stateful, as it allows you to maintain state.

Please help me. Am I overlooking anything here?

  • Anurag, can you share more of your code than just the first line? Commented Mar 7, 2016 at 16:25
  • 3
    Best to add the definition of your variable to the question (as e.g. static wouldn't work).
    – Keith C
    Commented Mar 7, 2016 at 16:25
  • You need to give us more context if we are to help you.
    – Adrian Larson
    Commented Mar 7, 2016 at 16:27
  • I edited the question above, i was using static variable while declaration. Keith's suggestions help me that static doesnt work.. Thanks Keith..!!
    – Anurag
    Commented Mar 7, 2016 at 16:33
  • No Adrain. The comments solved my problem.
    – Anurag
    Commented Mar 9, 2016 at 21:15

1 Answer 1


From the documentation:

Using State in Batch Apex

Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter is considered five transactions of 200 records each.

If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions.

The following works for me...

public class Throwaway implements Database.Batchable<SObject>, Database.Stateful
    public Integer batches;
    public Throwaway() { batches = 0; }
    public Database.QueryLocator start(Database.BatchableContext bc)
        return Database.getQueryLocator([SELECT Id FROM Account]);
    public void execute(Database.BatchableContext bc, List<SObject> scope)
    public void finish(Database.BatchableContext bc)
        system.assert(false, batches);

You must log in to answer this question.

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