Interview Question on Future Method

 

 

What is the use of the Future Method?

Future methods are typically used for:

Callouts to external Web services. If you are making callouts from a trigger you must use a future or queueable method.

Operations you want to run in their own thread, when time permits such as some sort of resource-intensive calculation or processing of records.

Prevent the mixed DML error.

What are the considerations while using future methods?

Future methods must be static methods,

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.

Notably, future methods can’t take standard or custom objects as arguments.  You can pass the List of record IDs that you want to process asynchronously.

Why don’t we pass sobjects in future methods?

objects can’t be passed as arguments to future methods is because the object can change between the time you call the method and the time that it actually executes. Remember, future methods are executed when system resources become available. In this case, the future method may have an old object value when it actually executes, which can cause all sorts of bad things to happen.

Can we fix the order in which future methods will run?

Future methods are not guaranteed to execute in the same order as they are called. When using future methods, it’s also possible that two future methods could run concurrently, which could result in record locking.

How to call Future methods from Process Builder?

To call Future methods from Process Builder, call the future method from the invocable method.

How to test future methods?

To test future methods, enclose your test code between the startTest and stopTest test methods. The system collects all asynchronous calls made after the startTest. When stopTest is executed, all these collected asynchronous processes are then run synchronously. You can then assert that the asynchronous call operated properly.

What is the best approach for making callouts to external web services?

Future method invoked through triggers allowed to do apex callouts and invoke external web service provided the future method is annotated with @future(callout=true).This provides lot of flexibility and one of the best approaches

What are the best practices for future methods?

Best Practices

If using Web service callouts, try to bundle all callouts together from the 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 a large number of records asynchronously.

Can we use future methods in Visualforce Controllers or constructors?

Future methods can’t be used in Visualforce controllers in getMethodName(), setMethodName(), nor in the constructor.

Can you call a future method from another future method?

You can’t call a future method from a future method.

What are governor limits for future methods?

You’re limited to 50 future calls per Apex invocation, and there’s an additional limit on the number of calls in a 24-hour period.

How to monitor future methods?

Future jobs show up on the Apex Jobs page like any other jobs.

You can query AsyncApexJob to find your future job. Since running future job does not return an ID, you have to filter on some other field such as MethodName, or JobType, to find your job.

What are use cases of future methods?

Make a callout to external web services

 Avoid MIXED_DML_OPERATION exception

Q. Is it possible to call future method from apex scheduler or not?

Yes it is possible to call future method from apex scheduler

//Scheduled Apex 
public class DemoScheduler1 implements Schedulable{
    public void execute(SchedulableContext sc){
        system.debug('*******Going to call future method ');
        DemoAsynchronousTest.futureMethodCallFromScheduler();
    }
}
//apex class containing future method
public class DemoAsynchronousTest{
    @future
    public static void futureMethodCallFromScheduler(){
        system.debug('******futureMethodCallFromScheduler get called');
    }
    
}

Why future method is static and void?

Future methods will run in the future. You don’t want your synchronous code waiting an unknown period of time for an asynchronous bit of code to finish working. By only returning void, you can’t have code that waits for a result.

Future method by definition is static so that variables with this method is associated to the class and not the instance and you can access them without instantiating the class.

Q. Can we call future method from process builder?

To call Future methods from Process Builder, call the future method from the invocable method.

Q. What could be the workaround for sobject types in future method?

To work with sObjects, pass the sObject ID instead (or collection of IDs) and use the ID to perform a query for the most up-to-date record.

global class FutureMethodRecordProcessing
{
    @future
    public static void processRecords(List<ID> recordIds)
    {  
         // Get those records based on the IDs
         // Process records
    }
}

Q. If I want to call a future method from a future method, what could be the solution?

Workaround could be calling a web service that has future invocation.

Q. From which places we can call future method?

  • Trigger
  • Apex Class
  • Schedulable Class

Q. Explain How to avoid Mixed DML Error?

public class Util {

    @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;

    }

}
public class MixedDMLFuture {

    public static void useFutureMethod() {

        // First DML operation

        Account a = new Account(Name='Acme');

        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.

        Util.insertUserWithRole(

            'mruiz@awcomputing.com', 'mruiz',

            'mruiz@awcomputing.com', 'Ruiz');       

    }

}

Q. Can we pass wrapper to future method?

You can pass wrapper, but for that, you’ll need to serialize/deserialize that parameter. You can convert the Wrapper to a String which is a primitive.

Once converted into a String you can them pass that string as a parameter to the future method in consideration.

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes