Sub topic 5
When a Future Method Runs and in What Order
This chapter assumes you can write basic Apex classes and static methods, run SOQL and DML, and recognize governor limits. It also assumes you have read the earlier chapter on declaring and calling a future method. Here you will learn when the platform actually runs your future method and what that means for your code.
The call only queues a request
When Apex reaches a line that calls a future method, the method does not run. The platform adds a request to an internal queue and your code continues. The queued request holds the method name and the argument values you passed.
The future method starts only after the current transaction has finished. The platform runs it later in a new transaction. Each future call gets its own set of governor limits.
public class QueueDemo {
@future
public static void logLater(String label) {
System.debug('Future ran: ' + label);
}
public static void run() {
System.debug('Before call');
logLater('first');
System.debug('After call');
}
}In the debug log for QueueDemo.run(), "Before call" and "After call" appear together. "Future ran: first" appears in a separate log, written by a separate transaction.
No timing guarantee
The platform starts a future method when system resources are available. That can be a second later or much longer during busy periods. Do not write code that depends on a specific start time.
Two practical points follow:
- The user who triggered the work will not see the result at once. A page that reloads right after the call may show old data.
- Your code cannot wait for the future method and then read its result. Future methods return
void, and the caller never gets a handle to the job.
No ordering guarantee
If you queue several future calls, they are not guaranteed to run in the order you called them. Two future methods may even run at the same time. This is the most common source of surprising bugs.
Consider this code:
public class OrderingRisk {
public static void process(Set<Id> accountIds) {
AccountService.updateAccountRatings(accountIds);
BillingCallout.sendAccounts(accountIds);
}
}You might expect the rating update to finish before the billing callout reads the accounts. That is not guaranteed. The callout may read the accounts before the ratings change, or the two may overlap and compete for the same rows.
Design each future method so it works in any order:
- Do not make one future method depend on the output of another.
- Re-query data inside the method, so it works from the current state at run time.
- If two steps must run in sequence, put both in one method, or use Queueable Apex, which can chain jobs (covered in a later chapter).
Data can change before the method runs
The gap between the call and the run is a window in which other transactions can change your records. A user may edit an account, or another process may delete it. The values you passed in are a snapshot taken at call time. Records you read in the future method are the current state.
This is why the earlier chapter recommends passing IDs and re-querying. Defensive code also handles the missing-record case:
public class SafeFutureService {
@future
public static void markReviewed(Set<Id> accountIds) {
List<Account> accounts = [
SELECT Id, Description FROM Account WHERE Id IN :accountIds
];
if (accounts.isEmpty()) {
return;
}
for (Account a : accounts) {
a.Description = 'Reviewed';
}
update accounts;
}
}If the query returns fewer rows than you passed IDs, some records were deleted in the meantime. The loop simply skips them.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Test assertion sees old values | The future method has not run yet | Call it between `Test.startTest()` and `Test.stopTest()` |
| Second future method reads stale data | Assumed the first one finished | Merge the steps or use Queueable chaining |
| Future method updates wrong values | Used values passed at call time | Re-query records inside the method |
| Result is missing on screen right after save | Method runs after the transaction | Refresh later or show a pending status |
Exercise
A trigger calls future method A, then future method B. Method B needs the field value that method A writes. Why is this unreliable, and what is one way to fix it?
Show answer
The platform does not guarantee that future methods run in call order, and they may overlap, so B can read the record before A has written the field. Fix it by doing both steps in a single future method in the required order, or by using Queueable Apex to chain the second job from the first.
Exercise
Your code calls a future method and then immediately queries the record the method updates. The query shows the old value. Why?
Show answer
The future method has only been queued. It runs in a separate transaction after the current one finishes, so the update has not happened when the query runs.