Using @Future Annotation in Apex

Future Apex is a helpful tool to use when you're working with asynchronous methods. These methods get executed as soon as Salesforce has the resources, and they don't hold up the rest of the thread from processing. Implementing the @future annotation is relatively straightforward, but it's important to know the appropriate times to use it and when it's not suitable for your needs.

Future Apex Use Cases

Future Apex is particularly useful in a few use cases. When you leverage these for your Salesforce development, you can create more efficient, effective code.

  • External web service callouts: These callouts have the potential to slow everything else down while they wait for a response from the web service. Future Apex avoids this problem by processing these requests separately.
  • Preventing mixed DML errors: You probably won't run into this use case often, but future Apex is helpful if you encounter DML errors due to multiple sObject types that don't play nicely together.
  • Moving resource-intensive operations to their own threads: This use case is another way to optimize your code because particularly resource-heavy operations get a dedicated thread, rather than monopolizing one that is shared with everything else.

Future Syntax

You have a few requirements to follow when it comes to the @future annotation syntax:

  • Static methods only
  • Limited to void-type returns
  • Parameters have to be primitive data types. You can also use arrays and collections of this type of data.
  • Standard or custom argument objects do not work with the @future annotation

 

    @future
    public static void updateSObjects(String jsonString) {
        
        List<SObject> sObjs = new List<SObject>();
        
        try {
            sObjs = (List<SObject>) JSON.deserialize(jsonString,                List<SObject>.class);
        } catch (Exception e) {
            System.debug('Error in JSON deserialization');
        }
        
        if(!sObjs.isEmpty()) {
            try {
                update sObjs;
            } catch (Exception e) {
                System.debug('Error updating SObjects');
            }
            
        } 
        

Future Apex Tips

Make sure that your @future annotation adheres to all governor limits. You get higher limits than you otherwise would, but they still need to meet the requirements. This tip is particularly important when you're working with loops.

  • Don't exceed the limit of 10 @future annotations within a single transaction.
  • You can use list of method IDs to identify the methods to process with an @future annotation.

Future Apex is an excellent way to make the best use of your processing resources, and it's relatively simple to implement. If you run into trouble, Salesforce offers extensive documentation on how to use this option.