img1

Preface

Checkout the following articles before tackling this one:

  1. Basics and Definitions

Learning Objectives

After completing this article, you’ll be able to describe:

Prologue

In the previous article, the concept of Asynchronous programming on the Salesforce platform was discussed. Future methods an asynchronous feature in Apex will be the topic today. So what are future methods? There are regular functions in Apex but with the difference been that the method is annotated with @future annotation. Future methods are executed on a newly created thread, which is queued, and runs at a later time when system resources become available.

Benefits

Using future methods your awarded with a new batch of governor limits in its own thread. This convenience means that the users are not blocked performing their usage operations.

Use Cases

Listed below are some the typical use cases for Future methods when incorporating the feature in your next or existing codebase:

  • Callouts to external services, if your creating functionality to connect to external systems vis REST you must use a future method
  • Generally used to run long running operations on its own thread, these are resource intensive operations such calculations or batch processes
  • Certain Sobject types cannot be mixed when performing DML operations, Future methods help to prevent such errors from happening

Best Practices

Future methods as discussed are asynchronous in nature and gets executed in a separate thread. Hence, every invocation tally one request to an queue. The practices listed below are directed towards proper usage considerations:

  • Avoid design patterns that add large numbers of future requests over a short period of time
  • For batch processing of records, consider using Batch Apex instead to process large number of records
  • Try to minimize future method invocations for callouts to external services
  • Test thoroughly to make ensure callouts wont time out to delays for large number of records

Callouts to remember

To make a Web service callout to an external service or API, you create an Apex class with a future method that is marked with @future(callout=true).

Things to Remember

Please consider the following when ever your thinking of using Future methods in your next or existing program:

  • You’re limited to 50 future calls per Apex invocation, there is also limits enforced per 24 hour calls as well
  • Methods with the future annotation must be static methods, and can only return a void type
  • The getContent() and getContentAsPDF() methods can’t be used in methods with the future annotation
  • You cannot invoke a future method from another future method.
    • you also cannot call a Trigger invoked in another future method
  • Future methods can’t be used in Visualforce controllers in getMethodName(), setMethodName(), nor in the constructor.
  • The order in which future methods are invoked is not linear
  • It’s possible that two future methods could run concurrently, which could result in record locking if the two methods were updating the same record
  • The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types; future methods can’t take objects as arguments

Practical Example

The code snippet below is about using to future methods to update a custom field on the Account object with the number of contacts associated to the Account.

  1. First navigate to the Account object and create “Number of Contacts” integer field.
  2. Create a Account with FirstName = Future, LastName=Mike, in test class
  3. Create another Account FirstName = Future, LastName=Jackson
    1. create a contact linked to this Account in test class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public with sharing AccountProcessor {
	@future
    public static void countContacts(List<String> accountIds){
        List<Account> accounts = new List<Account>();
        List<Account> contactAccounts = [SELECT Id,(SELECT Id FROM Contacts) FROM Account WHERE Id IN :accountIds];
        for(Account record: contactAccounts){
            record.Number_of_Contacts__c = record.Contacts.size();
             accounts.add(record);
        }
        if(!accounts.isEmpty()){
            update accounts;
        }
    }
}

Testing Example

To test Future methods, you must execute them synchronously using the Test.startTest() and Test.stopTest(), invoke your Future methods in that code block.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@isTest
public class AccountProcessorTest {
    @isTest
    public static void testAccountWithContacts(){
        Test.startTest();
        Map<String, Account> mappedAccounts = new Map<String,Account>([SELECT Id FROM Account WHERE Name ='Future Mike']);
        List<String> accounts = new List<String>(mappedAccounts.keySet());
        AccountProcessor.countContacts(accounts);
        Test.stopTest();
    }
}

Epilogue

Thanks for reading this article, to summarize we discussed the concept , limitations, use cases and best practices for Future methods on the Salesforce platform. Future methods are asynchronous block of code that gets executed on a separate thread yielding a new batch of governor limits. A basic example was demonstrated and accompanied by a simple class to drive the concepts home. Thanks for stopping by 😃 and i hope you was able to learn something new or reinforce what you already knew. A través del aprendizaje continuo, ¡mejorará!