[SalesForce] Getting heap size error while serializing collection of records in apex

I am suffering with Salesforce apex LimitException issue. I am fetching thousands of records from few objects and putting it into the collection like Map. Now I have a requirement to generate JSON for same records which will be used for mobile devices to download data from Salesforce. When I tried to serialize those records by using System.JSON.Serialize() method; it is generating a huge JSON string and I am getting System.LimitException error because there will be more memory required than available space. I tried to catch that issue using try/catch block but here is a reference available which says that System.LimitException can’t be caught by Catch block. Referral URL:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_exception_methods.htm

I know that we can check heap size limit through Limits.getHeapSize() method. But is there any work around so that I can handle this issue from apex side. A code sample or some reference in this regard would be highly appreciated. Thanks in advanced.

Best Answer

You're receiving this error because you're trying to process and store too much data through a method and architecture that's not designed to do this. Specially if you intend to use this for data download or synchronization you have to consider that if you're hitting a heap limit, you're likely going to have usability issues for your mobile users too.

Please consider an alternative way of processing and sending over this data. Consider segmenting your data and implement some polling, pagination or lazy loading algorithm to get your data across.

Governor limits are not something you want to attempt to "work around", they usually are an indication that something in your design is flawed and you should attempt to reflect on this.

Related Topic