In this article, we will explore some of the important future method related interview questions and answers.
Q.1: What is Future Method and Why it is used?
Ans: Future method is a form of asynchronous apex. It is run in separate thread when resources are available.It is used to run long running operations like external web service callouts or any task that can be completed in near future.We can only pass primitive data types, arrays of primitive data types, or collections of primitive data types as parameters.
Q.2: Why we can’t pass sObject as parameters in future methods?
Ans: We can not pass sObject as parameter in future methods because the sObject might change between the time you call the method and the time it executes. In this case, the future method will get the old sObject values and might overwrite them.
Q.3: Is there any work around to pass sObject as parameter in future method.
Ans: We can serialize a list of sObject data and pass it as Json String or we can send a list of record ids and use it to query the respected records.
Q.4: Can we perform callouts from future methods?
Ans: Yes, we can perform callouts from future methods. We have to annotate the method as callout=true.
Q.5: Can we call a future method from batch Apex?
Ans: No it is not allowed
Q.6: Can we call a future method from trigger.
Ans : Yes
Q.7: If a future call is included in an Account trigger’s update operation and a batch job is running on Account records performing DML, will the future call be executed after the DML operation?
Ans : No, the trigger would throw an exception saying “Future method cannot be called from a future or batch method”.
Q.8: How can we handle the above error?
Ans: The trigger logic can be updated to use System.isFuture() and System.isBatch() calls. These can be used to check if the current execution context is a future or batch, and the future method invocation can be avoided in such cases.
Trigger SampleTrigger on Contact (after insert, after update) { if(!System.isFuture() && !System.isBatch()) // code for future call }
Q.9: What is mixed DML Error and how can we resolve it?
Ans: If you are performing DML operation on Setup objects(Account,Contact or any standard or custom object) and Non-Setup Objects like User,Groups in single transaction then we get the error “Mixed DML Operation”. We can use future method to change the transaction of both the DML operations.
Q.10: How can we test a future method?
Ans: To test methods with the @future annotation, wrap the class containing the method within a startTest() and stopTest() block. The system collects all asynchronous calls made after the startTest method. When the stopTest is executed, all asynchronous processes run synchronously.