0

I have a batch class that uses Database.Batchable<SObject>.

  • How can I programmatically check for the heap-size limit in my batch?
  • At the point where my check returns true and I'm either close to the limit or have already reached the limit (depending on the checking), is my only way to make sure I process all records needed, to set a flag on the currently processed records (these records are saved in a stateful variable which I assume cause the heap-size limit to be hit) and update them and then re-run the batch (or have the batch schedule itself for a run), to process remaining records in a new transaction?
2
  • 1
    What do you mean "with a refreshed head-size limit"?
    – sfdcfox
    Apr 19 at 19:23
  • Sorry I'll edit my question to be more clear on that part.
    – Bahman.A
    Apr 19 at 19:27
1

You can check if you're near the limit with something like:

if(Limits.getHeapSize() > 0.9*Limits.getLimitHeapSize()) {

This puts you at 90% or more usage, typically a safe value, but you may want to experiment for your use case. When you're done with a record or other data, you can "free" it by clearing the variable; you don't necessarily need to go to a new transaction.

Also note that heap size is per context, not transaction. For example, if you insert records in a DML statement, the heap size temporarily becomes whatever is used in the trigger. I go into more detail in this answer.

If you're having heap size problems, just remember to free data when you no longer need it, and you should generally be okay. Note that the serialization size of a batch is undocumented, but much smaller than the total heap size limit, so store only the stateful data you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.