Explain about future method in salesforce?

Future method in salesforce: Future methods are used to run the process in a separate thread, at later time when system resources are available. We can use future methods for any operation we would like to run asynchronously in its own thread.

Future methods provide the benefits of not blocking the users from performing other operations and providing higher governor and execution limits for the processes.

Future method syntax:

  • Use @future annotation before method declaration.
  • Future methods must be static methods, and can only return a void type.
  • The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types.
  • Future methods can’t take standard or custom objects as arguments.
  • A common pattern is to pass the method a list of record IDs that you want to process asynchronously.
global class YourClassName {

  @future

  public static void yourFutureMethodName(List<Id> recordIds) {

    List<Account> acc = [Select Id, Name from Account Where Id IN :recordIds];

    // process account records to do awesome stuff

  }

}

 

Best practices to implement future methods:

  • Ensure that future method execute as fast as possible.
  • If using webservice callouts, try to bundle all callouts together from same future method, rather than using a separate future method for each callout.
  • Conduct thorough testing at scale. 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.

 Consider using Batch Apex instead of future methods to process large number of records asynchronously. This is more efficient than creating a future request for each record.

To know more,  refer below Salesforce Trailhead URL.

https://trailhead.salesforce.com/trails/force_com_dev_intermediate/modules/asynchronous_apex/units/async_apex_future_methods