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
dmchengdmcheng 

Batch Apex Stateful maintains sObject variables and collections?

Hello.  If I use Stateful in Batch Apex, will a List of contacts maintain its state across all the batch chunks?  I want to do a DML update with the List in the finish method.  The documentation is not clear if sObject variables/collections are maintained.  Thanks.

 

 

global class CalcFYTDBatch implements Database.Batchable<sObject>, Database.Stateful {
	Contact[] changedCons = new List<Contact>();

    //Execute the query.
    global database.querylocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        for(sObject s : scope) {
			Contact con = (Contact)s;
			tmpCon = new Contact(Id = con.Id);
			//various calculations
			changedCons.add(tmpCon);
			}
        }
    }
    
    global void finish(Database.BatchableContext BC) {
        if(!changedCons.isEmpty()) update changedCons;
    }

}

 

 

sfdcfoxsfdcfox

That's actually a good question. I would assume that the answer is 'yes', because anything that can be serialized could be a viable option. Obviously, you can't use a save point for a rollback, for example, because they are not valid across transactions. Any other type of data should maintain its state, even maps and complex classes, across each run of execute. Keep in mind though, that the normal governor rules apply here, so if changedCons exceeds 1000 entries, it will cause a governor exception (the unrecoverable kind). The documentation doesn't seem clear on what would happen in this scenario, but I'd have to assume the moment you crossed that threshold, it would fail all remaining batches since you can't recover from that condition. You should avoid using that method unless you can accurately predict that you will not exceed governor limits by using that method.

dmchengdmcheng

Thanks for your reply.  Wasn't the 1000 item limit removed from collections in Winter '11?  I'll give it a try and see what happens.

sfdcfoxsfdcfox

You're right on that last part. I did not see it in the release notes, but I double-checked the documentation which states:

 

 

There is no limit on the number of items a collection can hold. However, there is a general limit on heap size.

That being said, you'll still need to be careful about stepping on other governor limits, such as heap size, total statements, DML limits, and so on.

 

BT23BT23

We are working on a very similar solution.  Researching and testing Batch Apex Stateful code.

 

 

Did you ever resolve this issue?