Mytutorialrack

Future Method in Salesforce

Salesforce, a leading cloud-based CRM platform, offers a powerful feature called the Future Method, which allows developers to execute code asynchronously.

In this blog post, we’ll dive into the world of Asynchronous Apex, starting with an overview of synchronous and asynchronous processes.

We’ll explore the concept of the Future Method in salesforce, its syntax, and how it can be implemented in real-world scenarios. Additionally, we’ll discuss the benefits and limitations of using Future Method in Salesforce development. So, let’s embark on this journey to unlock the true potential of asynchronous execution in Salesforce!

Synchronous and Asynchronous Processes:

Before delving into the Future Method, let’s grasp the difference between synchronous and asynchronous processes. Imagine you have a set of tasks to accomplish during your day. In a synchronous process, each task must be completed before moving on to the next.

Imagine you have a coffee machine that only brews one cup of coffee at a time. In a synchronous process, you need to wait until one cup of coffee is brewed before starting the next cup. So, you load the coffee grounds, water, and start the brewing process.

You have to wait until the machine finishes brewing the first cup of coffee before you can proceed to make the second cup. This sequential flow, where each step waits for the previous one to complete, represents a synchronous process

On the other hand, asynchronous processes allow tasks to run concurrently or in the background without waiting for the completion of a specific task.

Now let’s consider an asynchronous process using a different coffee machine. This coffee machine is capable of brewing multiple cups simultaneously.

In this case, you can load the coffee grounds and water, start the brewing process, and while the first cup is being brewed, you can start loading another cup with coffee grounds and water. The machine will continue brewing the first cup independently while you move on to prepare the second cup. This parallel execution of multiple tasks without waiting for the previous task to complete represents an asynchronous process.

In programming, asynchronous processes are often used for tasks that may take a long time to complete, such as making network requests or performing complex calculations. By running these tasks asynchronously, other parts of the program can continue executing, improving overall efficiency and responsiveness.

What are future methods in salesforce?

The Future Method in Salesforce is a powerful tool that allows developers to execute code asynchronously. It enables you to mark a method with the @future annotation, indicating that it should run in a separate thread or transaction.

By leveraging the Future Method, you can offload non-essential or time-consuming tasks to the background, freeing up resources and improving overall performance.

Syntax

  • To define a Future Method, you simply need to add the @future annotation before the method declaration.
  • It is essential to make the method static and return type void, as the execution happens in the background, and the method does not provide immediate output.
  • Future Methods can only accept primitive data types as parameters, such as integers, booleans, and lists of IDs.
global class FutureExample{
    @future
    public static void futureMethod(){   
         // Perform some operations
    }
}

How to invoke future method in salesforce ?

Calling a Future Method is straightforward. You invoke it like any other method by using the class name followed by the method name. The Future Method will then run asynchronously, allowing you to continue with your current tasks while it executes in the background.

FutureExample.futureMethod();

Real-World Scenarios and Use Cases of Future Method

Here are three common use cases where the Future Method shines:

  1. Background Processing: When you have tasks that don’t require immediate attention or user interaction, such as data deletion or cleanup operations, you can utilize the Future Method to move them to the background. By doing so, you optimize resource utilization and improve overall efficiency.
  2. DML Operations and Mixed DML Exception: In Salesforce, you might encounter a “Mixed DML” exception when trying to perform DML operations on both setup and non-setup objects in a single transaction. By encapsulating the setup object operations within a Future Method, you can separate them into a different transaction, avoiding the exception and ensuring smooth execution.
  3. Trigger Callouts: Salesforce imposes limitations on making callouts directly from triggers. However, by invoking a Future Method from a trigger(trigger handler), you can perform callouts asynchronously, mitigating the restriction and ensuring smooth integration with external systems.

Limitations of Future Methods

While Future Methods offer significant advantages, it’s crucial to be aware of their limitations.

  • Future Methods have their own set of limits, such as the number of method invocations, CPU time, heap size, and more. It’s important to monitor and optimize your code to avoid hitting these limits.
  • Future Methods do not guarantee order of executionSince they run asynchronously, the order in which they are invoked may not necessarily reflect the order in which they are completed. If the order of execution is critical, you should consider alternative solutions or additional logic to handle sequencing.
  • Future Methods do not support transaction control. They operate in their own separate transactions, meaning they cannot be rolled back if an error occurs. If you require transactional consistency, you might need to explore other mechanisms, such as Queueable Apex.

Future method with an example

Now, I will illustrate a simple example to show the power of Future Method in Salesforce. I have created a new field on Account object of the data type Number and it is used to calculate Number of Contacts (Number_of_Contacts__c) associated with an account.

I will create an Apex class to update this field on the account object based on the contacts associated with that account.

public class FutureMethodExample {

    @future(callout=true)
    public static void countNumberOfContacts(List<Id> acctIds)
    {   
        List<Account> acctList=[select id,Number_of_Contacts__c,(select id from contacts) from account where id in :acctIds];
    	for(Account acc:acctList)
        {
            acc.Number_of_Contacts__c=acc.contacts.size();
        }
        if(!acctList.isEmpty())
        {
            update acctList;
        }
    }
}

You can invoke this future method using Anonymous apex as shown below. You can pass list of ids of the Account object to the method.

List<Id> acctsIds=new List<Id> {'001Dm00000BPbMuIAL'};
FutureMethodExample.countNumberOfContacts(acctsIds);

How to write test class for future method in salesforce?

To test methods annotated with @future, you can call the class containing the method within a startTest() and stopTest() code block.

All asynchronous calls made after the startTest method are collected by the system, and when stopTest is executed, all asynchronous processes are run synchronously.

@isTest
public class FutureMethodExampleTest {
    
    @isTest
 private static void testDataSetup()
 {
     List<Account> acctList=new List<Account>();
     for(integer i=1;i<=5;i++)
     {
        
         acctList.add(new Account(Name='Test '+i));
     }
     insert acctList;
     List<Contact> contactList=new List<Contact>();
     List<Id> acctIds=new List<Id>();
     for(Account acc:acctList)
     {
         contactList.add(new Contact(FirstName='MyTutorialrack',LastName='Site '+acc.Name,accountId=acc.Id));
    	acctIds.add(acc.id);
     }
     insert ContactList;
     Test.startTest();
     FutureMethodExample.countNumberOfContacts(acctIds);

     Test.stopTest();

     List<Account> accs=[select id, Number_of_Contacts__c from Account where id in:acctIds ];
     System.assertEquals(1,accs[0].Number_of_Contacts__c);
 }
 
    
}

Can we call future method from trigger in salesforce ?

You can create an Apex Handler class and define a future method within it. This method can be called from a trigger as well.

Important Points to remember

  • A future method executes asynchronously in the background. It is useful for running long-running operations, such as making callouts to external web services or performing operations that need to run in their own thread, independent of the main execution flow. 
  • Future methods are queued and executed when system resources become available, allowing your code to continue its execution without waiting for the completion of the long-running operation.
  • Future methods have higher governor limits for certain operations, such as SOQL query limits and heap size limits.
  • Future methods must be declared as static methods.
  • They can only have a void return type.
  • The parameters of future methods must be primitive data types, arrays of primitive data types, or collections of primitive data types.
  • Future methods cannot accept sObjects or objects as arguments.
  • You can invoke future methods just like any other method. However, a future method cannot call another future method.
  • You are allowed to make up to 50 method calls per Apex invocation.
Enroll in our Salesforce Development Course

Share:

Recent Posts