Future Method

What is the future method in Salesforce? 

Future Method is one of asynchronous ways of processing in apex. Where the method will run in the background using a separate thread. 


Syntax



Points to remember:

  • Future method must be annotated with @future annotation
  • Must be static
  • There should be no return type
  • Parameters must be primitive or collection of primitive data type
  • We can't call one future method from another future method
  • We can’t pass object or sObject type of parameter for future
  • While writing test class future methods should be called between code block StartTest() and StopTest(). So, after StopTest All Asynchronous Methods will become Synchronous.

When to use a future method?

  1. To perform Mixed DML operation.
  2. To Perform long run Operation so we can get advantage of higher limits (For example web service call out).

Syntax to perform web service callout using future method:


NOTE: We should make use of @future(callout=true).


Let's take real life example to understand future method,

John wants to perform following activities during his weekend,
  1. Wake up early
  2. Take bath
  3. Have breakfast
  4. Give vehicle for service
  5. Movie with friend
Let's analyze the above activities and see how we can make use of future method.

To wake up early, John needs to be there.

To Take bath, John needs to be there.

 

To have breakfast, John needs to be there.


For movie, John needs to be there.


But for vehicle service he can tell the problems of the vehicle with the mechanic, the mechanic can correct it. so, he can go to the movie by giving the vehicle for service. Hence, we can run the service in different threads.


Now let's write a class for it to see how future method works,




Let's check how it worked using log: 


Here we can see two log items,


Let's check first log,


Now let's check second log of future method,


If you observe logs, the vehicle for service method ran in a different thread. 




Comment below If you have additional information about future methods.


Thank You

Comments