13

Future methods can only take primitives or collections of primitives as parameters. To get around this you could serialize Sobjects (or classes) to a string and then deserialize them in the future method. Ex:

@future
public static void test(string foo)
{
    Contact con = json.deserialize(foo);
}

test(JSON.serialize(mycontact));

This seems to work but I'm wondering if anyone knows of any drawbacks or pitfalls to this approach?

13

A few thoughts:

  • If you are dealing with a collection the string resulting from JSON serialization could become prohibitively large. This could result in heap size limit issues during deserialization.
  • The data in the sObject may be stale by the time the future method executes. Fields may have been changed on the Contact before the future method runs.
  • You may be serializing and passing data that you otherwise don't care about. E.g. You probably wouldn't want to serialize a blob data field.

Weather any of these are an issue or not will entirely depend on your usage.

  • My actual use case is for passing in an apex object not an Sobject but those are definitely good points. Do you have an idea of how much larger the serialized string is compared to the collection? – Greg Grinberg Nov 29 '12 at 0:19
  • 1
    No sorry, I don't. Best bet would be to check the results of Limits.getHeapSize() and Limits.getLimitHeapSize() in some test cases. – Daniel Ballinger Nov 29 '12 at 0:37
4

I've actually utilized this pattern to @futurize restful api callouts. In my case they objects were sObjects, but sobjects I wasn't worried about changing on me. As a design pattern, it works fairly well, even with moderately sized objects.

However, Daniel brings up the single most salient point, and one that needs to be re-iterated. If you choose to implement this pattern, you must start adding heap-stress-tests cases! I like to set my own heap "limits" and assert that Limits.getHeapSize() is below my own limit. This lets me isolate the heapsize used by json de/serialization of exemplar objects. That way I have some idea what my heapsize budget is for the rest of the @future call.

0

If you have a method that you want to run asynchronously and pass non-primitive arguments, one other option that became available in the Winter ’15 release is the Queueable Interface.

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.