Future Methods in Apex Salesforce

by Rijwan Mohmmed
0 comment
future-methods-in-apex-salesforce

Hello folks, today we are going to discuss Future Methods in Apex Salesforce. Future Apex is used to run processes in a separate thread, at a later time when system resources become available. A future method runs in the background, asynchronously.

Also, check this: Implement Iteration for:each directives in LWC

Key Highlights :

  1.  A future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time.
  2. Use @future annotation before method declaration.
  3. Run asynchronously.
  4. Use future methods to isolate DML operations on different sObject types to prevent the mixed DML error.
  5. A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits.
  6. Future methods must be static methods and void return types.
  7. Future methods can’t take standard or custom objects as parameters.
  8. Most of the time we pass a List or Set of Ids.
  9. Ensure that future method execute as fast as possible.
  10.  Test that a trigger enqueuing the @future calls is able to handle a trigger collection of 200 records. This helps determine if delays may occur given the design at current and future volumes.
global class FutureClass
{
    @future
    public static void myFutureMethod()
    {   
         // Perform some operations
    }
}
global class FutureMethodExample
{
    @future(callout=true)
    public static void getStockQuotes(String acctName)
    {   
         // Perform a callout to an external service
    }

}

Code :

FutureApex.cls :

public class FutureApex {
    @future
    public static void insertUserWithRole(String uname, String al, String em, String lname) {

        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
        // Create new user with a non-null user role ID 
        User u = new User(alias = al, email=em, 
            emailencodingkey='UTF-8', lastname=lname, 
            languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
            timezonesidkey='America/Los_Angeles', 
            username=uname);
        insert u;
    }
}

MixedDMLFuture.cls :

public class MixedDMLFuture {
    public static void useFutureMethod() {
        // First DML operation
        Account a = new Account(Name='Acme', AccountNumber='123333');
        insert a;
        
        // This next operation (insert a user with a role) 
        // can't be mixed with the previous insert unless 
        // it is within a future method. 
        // Call future method to insert a user with a role.
        FutureApex.insertUserWithRole('techdicer@techdicer.com', 'techdicer', 'techdicer@techdicer.com', 'techdicer');        
    }
}

MixedDMLFutureTest.cls :

@isTest
public class MixedDMLFutureTest {
    @isTest static void unitTest1() {
        User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
       // System.runAs() allows mixed DML operations in test context
        System.runAs(thisUser) {
            // startTest/stopTest block to run future method synchronously
            Test.startTest();        
            MixedDMLFuture.useFutureMethod();
            Test.stopTest();
        }
        // The future method will run after Test.stopTest();
    
        // Verify account is inserted
        Account[] accts = [SELECT Id from Account WHERE Name='Acme'];
        System.assertEquals(1, accts.size());
        // Verify user is inserted
        User[] users = [SELECT Id from User where username='mruiz@awcomputing.com'];
        System.assertEquals(1, users.size());
    }
}

Reference :

  1. Future Methods
  2. Future Methods Trailhead

What’s your Reaction?
+1
1
+1
0
+1
0
+1
0
+1
0
+1
1

You may also like

Leave a Comment