What is the purpose of @future method in Salesforce? How can we implement @future method?

In Salesforce usually we write a trigger for an object, and then from the trigger we call a method on a class.  If we need to make call out to an external web service from the trigger we get “System.CalloutException: Callout from triggers are currently not supported”. @future method with callout=true is the way to make this happen.

@future method executes asynchronously. When you specify @future annotation, the method executes on a separate thread when Salesforce has available resources. The future call basically acts like a scheduled job that has been kicked off. The method is placed in a queue and is kicked off as resources are available.

@future has many purposes:

  1. Making external callouts from Apex trigger.
  2. Allow us to control the governor limit by starting a new/separate thread.
  3. Avoid MIXED_DML_OPERATION error, by separating a thread to performing DML on Setup and NonSetup objects.

See the example below. You can use the @future annotation with callout=true when making an asynchronous Web service callout to an external service.

@future(callout=true)
static void doCallout(){
//do callout
}

Key points to remember about @future method :

  1. No more than 10 @future method calls per Apex invocation.
  2. You cannot call a @future method from another @future method.
  3. The parameters specified 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. Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
  6. @future(callout = true) means that the method has ability to invoke external web services.

 
Author:

Ajomon Joseph AJOMON JOSEPH
Senior Salesforce Architect
In Connect me on LinkedIn
twitter Follow me on Twitter @apexcoder
blogger Subscribe to my blog https://apexcoder.com
email Email me ajomon@apexcoder.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s