Asynchronous Apex Future Method

instagram | bugendaitech  Twitter | bugendaitech  Linkedin | bugendaitech

In technology terminology, Asynchronous operation means that a process operates independently of other processes. Generally, we use asynchronous apex when we need to do an operation on a large dataset, or a very general use case is to call the external web services.

Asynchronous Apex Future Method

A future method runs in the background, asynchronously. You can call a future method for performing long-running operations,and those future methods run in its own thread,on its own time. Each future method is queued and run when system resources become free.That way, the execution of your code doesn’t have to wait for the completion of a long-running operation.A advantage of using future methods is that few governor limits are greater, such as SOQL query limits and heap size limits.

The Syntax for Future Method:

The Syntax for Future Method
  • Use @future annotation before the method declaration.
  • Methods with the @future symbol must be static methods, and can only return a void type.
  • The specified parameters must be primitive data types.
  • Methods with the @future annotation cannot accept sObjects or objects as arguments.
    The main cause why sobjects can’t be moved as arguments to Future methods is the sObject might replace between the time you call the method and the time it executes.
  • In this case, the future method will get the old sObjectvalue and might overwrite them.
  • A future method can not call on another future method.

Future method callout

The following is an example of a future method that makes a callout to an external API. In the below picture, the future annotation takes an add on parameter (callout=true) to indicate that callouts are allowed.

Future method callout

When We Use Future Method:

We can also apply future methods to isolate DML operations on differents Object types to prevent the mixed DML error.

When We Use Future Method

limitation of the Future Method:

  • No more than Zero in batch and future contexts; one in queueable context method calls per Apex invocation.
  • The highest number of future method invocations per 24-hour period is 250,000 or the number of user licenses in your org multiplied by 200, whichever is higher than. This limit is for your whole organization and is shared with all async Apex: Batch Apex, Queueable Apex, scheduled Apex, and future methods. To check how many asynchronous Apex executions are free, make a request to the REST API limits resource. The licenses that count like this limit are full Salesforce user licenses or App Subscription user licenses. Chatter free, Chatter customer users, Customer Portal User, and partner portal User licenses are not included.

Leave a reply