Future method in salesforce

There are multiple processes in salesforce to execute your code asynchronously. In this post, we will discuss using the future method in Salesforce. Remember that any method using the @future annotation requires special consideration because the method does not necessarily execute in the same order it is called.

What is Future method in Salesforce?

A future runs as asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time. Each future method is queued and executes when system resources become available. That way, the execution of your code doesn’t have to wait for the completion of a long-running operation.

Future method in Salesforce

Future method syntax

To define a future method, simply annotate it with the future annotation, as follows:-

global class MyClass {
    @future
    public static void myFutureMethod(){   
         // Perform some operations
    }
}

Future method consideration

  1. Methods with the future annotation must be static methods
  2. can only return a void type
  3. The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types
  4. Methods with the future annotation cannot take sObjects or objects as arguments.
  5. You can invoke future methods the same way you invoke any other method. However, a future method can’t invoke another future method
  6. No more than 50 method calls per Apex invocation
  7. Asynchronous calls, such as @future or executeBatch, called in a startest, stopTest block, do not count against your limits for the number of queued jobs
  8. The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater
  9. To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously

Why sObjects can’t be passed as arguments in the future method?

The reason why sObjects can’t be passed as arguments to future methods is that the sObject might change between the time you call the method and the time it executes. In this case, the future method will get the old sObject values and might overwrite them. To work with sObjects that already exist in the database, pass the sObject ID instead (or collection of IDs) and use the ID to perform a query for the most up-to-date record.

What is the use of the future method in Salesforce?

There are many use cases when we can use the future methods in Salesforce.

  1. Avoid the CPU time limit Error: To avoid the log running talk and avoid the CPU time limit we can use the @Future method in Salesforce. Learn more about Apex CPU Time Limit Exceeded.
  2. Callout from Trigger: As we know we cannot do the callout from the trigger but we can invoke callouts from triggers by encapsulating the callouts in @future methods.
  3. Avoid Mixed DML operation: A Mixed DML operation error occurs when you try to persist in the same transaction, change to a Setup Object, and a non-Setup Object.
  4. You can also make use of future methods to isolate DML operations on different sObject types to prevent the mixed DML error.
  5. Higher governor limit: A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits.

Future method callouts using @future(callout=true)

Example of a future method that makes a callout to an external service. Notice that the annotation takes an extra parameter (callout=true) to indicate that callouts are allowed

global class FutureCalloutExample{

    @future(callout=true)
    public static void doCalloutInFuture(String acc){
         // Perform a callout to an external service
    }

}

What is the difference between the future method and Queueable?

Now let’s look at the main differences between Future and queueable apex.

FUTURE APEXQUEUEABLE APEX
It is annotation based so we can use the same apex class to write the future method. Syntax: @futureIt is a class which implements’ queueable interface. Syntax: public class CLASS_NAME implements Queueable{}
We cannot monitor the jobsWe can monitor the jobs based on the job Id.
we cannot call a future from another future or batch apex. The limit on future method for single apex invocation is 50.We can chain the Queueable jobs and the stack depth in developer org is 5 and in enterprise edition you can chain 50 jobs.
Future method supports only primitive datatypesQueueable supports both primitive and non-primitive data types.

Future Method Best Practices

Here are some future method best practices in Salesforce.

  • Avoid too many future methods to the callout, If more than 2,000 unprocessed requests from a single organization are in the queue, any additional requests from the same organization will be delayed.
  • Ensure that future methods execute as fast as possible. Minimize Web service callout times and tune queries used in your future methods.
  • Test your future methods at scale. To help determine if delays can occur, test using an environment that generates the maximum number of future methods you’d expect to handle.
  • Consider using batch Apex instead of future methods to process large numbers of records.
Amit Chaudhary
Amit Chaudhary

Amit Chaudhary is Salesforce Application & System Architect and working on Salesforce Platform since 2010. He is Salesforce MVP since 2017 and have 17 Salesforce Certificates.

He is a active blogger and founder of Apex Hours.

Articles: 461

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *