Using @future method in salesforce and its limitations

Salesforce provides different ways to run your code asynchronously like Batch apex, @future method. In this post we will see how to use @future method, its advantages, limitations and the precautions that we need to follow while using it.

We can use the @future methods in cases where methods are long running. In such cases we can prevent governers limits by making it as asynchronous transaction. @ future methods also help in preventing  mixed dml errors by isolating multiple dmls.

In order to mark a method  as future we have to simply mark it with the ‘@future’ keyword as shown in below snippet.

Public static void futureMethod(){
//Your Code Here

Points to remember while creating @future methods:

1. future methods must always be static methods.

2. @future methods cannot return anything and its return type should always be void.

3. The input parameters to such methods can only be primitive types, arrays of primitive type or collections of primitive types.

4. Input parameters cannot be sobjects or collection of sobjects.

@future methods can also be used to make callouts to external services. To use this we must mark callout=true specifically. If it is not specified then the default value is taken as false.

public static void myfuturecalloutmethid(){
//code to call external services

Why are sObjects not allowed as parameters in case of @future methods?

It is because the sobjects may change by the time the method is executed, in such cases the @future method may overwrite the already saved values of the sObject record.

What is the workaround for above sobject case?

We can pass the object Id as parameter and then query the record within the @future method and then work on the latest data.

Limitations of @future method:

1. You cant call a future method from another future method.

2. You can call up to 50 @future methods per transaction.

3. You can call up to 250000 future methods per 24 hours. This is in conjunction with all types of asynchronous methods like batch apex.

4. @future methods are not executed during salesforce downtime and any already running jobs during the start of downtime are halted and restarted after the downtime.

Please go through Future Methods with Higher Limits (Pilot)

Precautions that we need to follow while using future methods:

1. Make sure you dont put too much in a future method as this will increase the execution time and may lead to delaying of other requests after the organisation limit of 2000 unprocessed future jobs is hit.

2. Opt for batch apex when you are processing large no of records.

3. Test your future methods with maximum possible data as this will give you an idea of how much the job may take during real time.


Leave a Comment

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

Select Language »