Wednesday 22 July 2020

Episode 5-The Complete Guide on Future Methods in Salesforce

In this blog, we will have insights about future methods in Salesforce. This blog will be the complete guide blog for Future Methods. Before Wasting time let's get started.😊


Future Method:

Future method is the method that runs asynchronously i.e it runs in a separate thread in the background later when the resources become available. These methods are annotated with the @future keyword. The advantage of using future methods is users will not get blocked from performing other operations or processes. The future method has high governor limits in some cases like total no of SOQL queries issued, Total Heap Size, and CPU Time limit.

Future Methods can be used to make a callout to external web services and also used to isolate the different DML operations on certain sObjects to prevent mixed DML Error. For more detail checkout sObjects That Cannot Be Used Together in DML Operations.

Future Method Syntax:

global class FutureClassExample{
@future 
public static void testFutureMethod(List <Id> contactIds){
//perform some operations using contactIds
}
}

Key Points To Remember:

  • Future Methods must be static methods with return type void.
  • The parameters used in future methods must be primitive data types, an array of primitive types, or a collection of primitive data types.
  • Objects can't be passed as arguments in future methods because object can change between the time when the method is called and when it actually gets executed.
  •  The maximum no of methods with future annotation allowed per apex transaction is 50.
  • Future Method does not guarantee to execute in the same order as it was called.
  • The maximum no of asynchronous future method execution as per 24-hour period is 250,000 or the number of user licenses in your org multiplied by 200, whichever is greater.
  • You cannot call the future method from another future method.
  • Future methods can't be used in controllers nor in the constructor.
  • The getContent() and getContentAsPDF() methods can't be used in future methods.

Example Callout Code:

In order to allow the callout from the future method to external web service we have to use (callout=true) parameter. For Example:

global class ExampleCallout
{
    @future(callout=true)
    public static void geInfo(String acctName)
    {   
        // Perform a callout to an external service
    }
}

Test Classes:

To test future methods , we have to enclose the test code  between Test.startTest() and Test.stopTest() 
methods.All Asynchronous calls made after Test.startTest() are collected by the system and when 
Test.stopTest() is executed all the collected asynchronous process  run synchronously.

01@isTest
02private class MixedDMLFutureTest {
03    @isTest static void test1() {
04User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
05  // System.runAs() allows mixed DML operations in test context
06   System.runAs(thisUser) {
07  // startTest/stopTest block to run future method synchronously
08            Test.startTest();       
09            MixedDMLFuture.useFutureMethod();
10            Test.stopTest();
11        }
12        // The future method will run after Test.stopTest();
13     
14        // Verify account is inserted
15 Account[] accts = [SELECT Id from Account WHERE Name='Test'];
16 System.assertEquals(1, accts.size());
17        // Verify user is inserted
18 User[] users = [SELECT Id from User where username='Test.example@c.com'];
19      System.assertEquals(1, users.size());
20    }
21}

Best Practices of Future Method:

  • Avoid using separate future methods for each callout. If you are using web service try to group together all callouts in one future method.
  • Use Batch Apex instead of future methods to process large no of records asynchronously as it is a more effective method.
  • Ensure that future methods execute as fast as possible.
  • Avoid adding large no of future methods in the asynchronous queues over a short period of time. 
  • Test your future methods at scale  i.e test with the environment that generates the records that your future method is expected to handle. This gives an idea about the design performance in terms of the time required for processing the records.
Please check out  the below link of my earlier blog on Asynchronous Apex :
Thank you for reading my blog. I hope this blog is helpful to clear your concepts on future methods.
If you find it worthy do like and comment and don't forget to share with your friends who want to learn about future methods. Keep Learning and Reading my Blog☺.




















No comments:

Post a Comment

If you have any doubts ,Please let me know.

Episode 13 : RollUp Summary Trigger for Lookup Relationship

 As we all know we can use roll-up summary field logic only for the master-detail relationship, but in case you have the business requiremen...