0 votes
1 view

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'* 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?

1 Answer

0 votes
Best answer

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.

Welcome to Memory Exceeded, where you can ask questions and receive answers from other members of the community.
You can donate any amount for Orphans village using following QR Code.