Salesforce Developer Interview Questions – Asynchronous Apex – Future Method Continue..
Future Method Continue..
Table of Contents
95. Can we call a future method from another future method?
No, we cannot call a future method from another future method.
96. Can we call future methods from a batch job?
No, we cannot call future methods from a batch job.
97. Can we call future methods from a Trigger?
Yes, we can call future methods from a trigger.
98. Given a scenario where we have written a future call in the Opportunity Trigger update operation. And we have a batch job running on opportunity records and updates the records, Does the future call be invoked after the update?
Since we are in batch context, the trigger will run in the same context (i.e batch context). So as soon as the opportunity records get updated though the batch process and then the future method gets called from the trigger then the trigger would throw an exception saying “Future method cannot be called from a future or batch method” as future method cannot be invoked from future or batch method execution context.
99. How can we avoid the above exception?
The best way to avoid this exception is to write a code in such a way that the future method does not gets executed from the batch job call or another future method call.
100. What if we want to call a future method from a future method, is there any workaround?
As the future method cannot be called from another future method then as a work around we can call a webservice that has future invocation.
Like future method → web service → future method.
101. Can we trace or track the execution of future methods?
We can trace the future method from setup → apex Jobs
But if it is in the queue and resources are not available then it wont show up in the apex jobs. So we can query the asyncApexJob object to get the status.
However, future methods do not have an ID, so we can’t trace it directly. We can use another filter such as MethodName , or JobType to find the required job.
102. How to write the test class for a future method?
To test methods defined with the future annotation, call the class containing the method in a StartTest(), stopTest() code block.
All asynchronous calls made after the startTest() method are collected by the system, When stopTest() is executed , all asynchronous processes are run synchronously.
103. What are some limitations of future methods?
- It is not recommended to process a large number of records.
- It supports only primitive data types.
- Tracing a future job is not straightforward.
- We cannot call future methods from a batch and future context. However one call from a queueable context is allowed.