As part of the batch context, the static variables get reset at each transaction irrespective of Stateful/Stateless.
class batch_test implements database.batchable, database.stateful () {
static int value =1;
start () {
value =2 ;
}
execute () {
System.debug ( value ) ; // this will print 1 and not 2
}
finish () {
System.debug ( value ) ; // this will print 1
}
}
Does anyone know why does database.stateful not persist state for static variables and only for instance variables ?
Best Answer
As Bri mentioned, static variables persist for the duration of the execution context in Apex.
start()
,finish()
, and each invocation of theexecute()
method operate in separate execution contexts, so static variables are reset in the same way they would be reset in separate trigger executions.Implementing
Database.Stateful
allows you to use member variables that act in the way you're expecting in this case.