Understanding Future Methods in Salesforce

Understanding Future Methods in Salesforce



Introduction

Salesforce allows us to run tasks in the background using Future Methods. These methods help improve performance by running long processes separately, so the user doesn’t have to wait. Future methods are mostly used when working with callouts, batch processing, and handling large data operations.

What is a Future Method?

A Future Method is a way to run code asynchronously, meaning it runs in the background while other tasks continue. This is helpful when dealing with operations that take time, such as calling an external system or updating many records at once.

When to use Future Methods?

1.     Making Callouts to External Systems: Salesforce does not allow callouts from triggers. Using a future method helps make callouts without hitting limits.

2.     Processing Large Data: When handling thousands of records, future methods help process them without slowing down the system.

3.     Avoid Mixed DML Errors: When working with both setup (User, Profile) and non-setup (Account, Contact) objects, future methods prevent conflicts.

How to Create Future Method?

Future methods are defined using the ‘@future’ annotation in Apex.

Example 1:



public class FutureMethodExample {
 @future(Callout = true)
  public static void updateAccounts(List accountIds) { 
  List accList = [SELECT Id, Name FROM Account WHERE Id IN: accountIds];
   for (Account acc: accList) 
   {
    acc.Name = acc.Name + ‘ -Updated’; 
    } 
    update accList;
     }
      }


Example 2:


public class AccountFutureHandler {

    @future
    public static void updateAccountIndustry(Set accountIds) { 
        List accountsToUpdate = [SELECT Id, Industry FROM Account WHERE Id IN :accountIds];

        for (Account acc : accountsToUpdate) {
            acc.Industry = 'Technology';
        }

        if (!accountsToUpdate.isEmpty()) {
            update accountsToUpdate;
        }
    }
}




Calling the Future Method

public class AccountHelper {

public static void processAccounts() {

List accounts = [SELECT Id FROM Account WHERE Industry = NULL LIMIT 5];

if (!accounts.isEmpty()) {

Set accountIds = new Set();

for (Account acc : accounts) {

accountIds.add(acc.Id);

}

AccountFutureHandler.updateAccountIndustry(accountIds);

}

}

}

 

Considerations for Using Future Methods in Apex

1.    Method Definition

  • Future methods must be declared as static.
  • They must have a return type of void.

2.    Parameter Constraints

·       Parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types.

·       Future methods cannot accept sObjects or custom objects as parameters.

 

Reason - sObjects cannot be passed as arguments to future methods because there may    be a delay between when the method is called and when it executes. During this time, the sObject’s data could change, leading to the future method processing outdated values, which might result in unintended data overwrites.

 

3.    Invocation Rules

·       Future methods are invoked similarly to standard methods.

·       A future method cannot call another future method.

 

4.    Limits and Execution Considerations

·       A maximum of 50 future method calls can be made per Apex transaction.

·       Asynchronous calls, including @future and executeBatch, made within a startTest() and stopTest() block do not count toward the limit for queued jobs.

·       The maximum number of future method invocations permitted within a 24-hour period is 250,000 or 200 times the number of user licenses in the organization, whichever is greater.

 

5.    Testing Future Methods

·       To test a future method, encapsulate the method call within a startTest() and stopTest() block.

·       Any asynchronous calls made after startTest() are collected and executed synchronously when stopTest() is called.

 

Real Time Example

Scenario: Updating Customer Data

A retail company wants to update customer records every night based on external system data. Instead of slowing down the system during the day, they use a future method to process updates in the background.

 

Best Practices

1.     Do not use Future Methods for Small Tasks: They are best for long – running operations.

2.     Avoid Chaining Future Methods: One future method cannot call another future method.

3.     Use Queueable Apex for Complex Tasks: If there is a need of better control, we should use Queueable Apex Instead.

Conclusion

Future methods in Salesforce help improve system performance by handling time-consuming operations in the background. They are useful for callouts, large data processing, and avoiding mixed DML errors. However, they should be used wisely to avoid hitting Salesforce limits.

@powered By Kumar Sir (Groviya)

 

Write a comment
Your email address will not be published. Required fields are marked *
Scroll