Sub topic 11
Where Future Methods Cannot Be Called
This chapter covers the contexts where a future method call is not allowed, how to detect them, and what to use instead. It assumes you can write Apex classes and triggers, know the basic @future rules, and understand governor limits.
The core restriction
A future method cannot start another future method. Salesforce also blocks future calls from batch Apex. The platform throws a System.AsyncException at runtime when you break these rules. The compiler does not catch it.
| Calling context | Can call a future method? |
|---|---|
| Trigger, controller, or anonymous Apex | Yes |
| Another future method | No |
| `execute` method of a Batch Apex class | No |
| `Queueable` `execute` method | Yes, with limits |
The Batch Apex rule is the most surprising one. A batch job can easily update records that fire a trigger, and that trigger may call a future method. The trigger then fails inside the batch transaction.
How the error appears
Suppose a trigger calls a future method. If a future method updates records in the same object, the trigger runs again inside the future context. The second future call throws an exception like this:
System.AsyncException: Future method cannot be called from a future or batch method: AccountService.updateAccountRatings(SET<Id>)The same error appears when a batch job's DML fires the trigger.
Guarding with System.isFuture() and System.isBatch()
Apex gives you two static methods to check the current context. System.isFuture() returns true inside a future method. System.isBatch() returns true inside a batch job.
trigger AccountTrigger on Account (after insert) {
Set<Id> ids = new Set<Id>();
for (Account a : Trigger.new) {
ids.add(a.Id);
}
if (!System.isFuture() && !System.isBatch()) {
AccountService.updateAccountRatings(ids);
}
}The guard prevents the exception. It also means the work is skipped in those contexts. If the work must always happen, skipping it is a bug. In that case you need a different design, covered at the end of this chapter.
Other places to watch
Several other situations cause trouble, even though the call itself is legal.
- Loops. A future call inside a loop uses one of your 50 calls per transaction for every iteration. The 51st call throws a
LimitException. Collect IDs and call once, as the trigger above does. - Visualforce constructors and getters. Avoid future calls in code that runs on page load. It can run many times and gives no feedback to the user.
- Recursive triggers. A future method that updates the record that fired the trigger can cause the trigger to call the future method again. The
isFuture()guard stops this loop, but a static flag is a clearer way to control recursion. - Scheduled Apex. You can call a future method from a scheduled class. Remember that the future call is queued and runs after the
executemethod ends.
Alternatives when the guard is not enough
If a future method is not allowed and the work still must run, move to Queueable Apex. A Queueable job can be added from a future method or a batch job's execute method. A queueable can also chain to another queueable. You get a job ID back, and you can pass complex types such as List<Account> as member variables.
public class RatingJob implements Queueable {
private Set<Id> accountIds;
public RatingJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}A trigger can choose its path based on context:
trigger AccountTrigger on Account (after insert) {
Set<Id> ids = new Set<Id>();
for (Account a : Trigger.new) {
ids.add(a.Id);
}
if (System.isFuture() || System.isBatch()) {
System.enqueueJob(new RatingJob(ids));
} else {
AccountService.updateAccountRatings(ids);
}
}Queueable has its own limits. A transaction can enqueue up to 50 jobs, but a queueable that runs asynchronously can enqueue only one child job. Check the current Apex limits documentation before relying on these numbers.
Exercise
A batch job updates Account records. An after-update trigger on Account calls a future method. What happens, and how do you fix it?
Show answer
The future call throws a System.AsyncException because future methods cannot be called from batch context. Guard the call with System.isBatch() to avoid the error. If the work must still run, enqueue a Queueable job in the batch context instead.