function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Batch Apex - Reference Variables?

So with Batch Apex we have to define 3 methods; start, execute, finish.


Start = The data source. This is called once

Execute = Callback for each "chunk" of data. This is called N times

Finish = Execute at the end of the batch, and only called once


In my execute, I need to keep a running total of counters. Based on how 'execute' works, it will be called over and over, thus "resetting" my counter.


So what I am looking for are variables that are passed by reference? 



Ritesh AswaneyRitesh Aswaney

what you're looking for is a static variable.  declare a static class variable in your BatchApex class and reference that in your execute method. static variables are unique in the execution context.


Thanks a lot


If your class implements Database.Stateful, the member variables of the class will be saved and restored each time one of the methods is called. (They won't be "reset" as you said.)

The "Using State in Batch Apex" section on this page has more information and an example of what it sounds like you are trying to do: