Sub topic 2
Declaring and Calling a Future Method
This chapter covers the syntax and mechanics of a future method: how to declare one, how to call it, and what happens when you do. It assumes you can write Apex classes and static methods, run SOQL and DML, and know that governor limits apply per transaction. The chapter after this one covers parameter restrictions in more detail, so here we focus on the declaration itself and the call.
What a future method is
A future method is a static Apex method marked with the @future annotation. When you call it, Salesforce does not run its body right away. It places a request in a queue and returns control to your code. The method body runs later, in its own transaction, when system resources are available.
Two consequences follow from this:
- The caller cannot use a return value, because the method has not run when the call returns.
- The future method has its own set of governor limits, separate from the transaction that called it.
The declaration rules
A future method must follow four rules.
- It must be
static. - It must return
void. - It must carry the
@futureannotation. - Its parameters must be primitives, arrays of primitives, or collections of primitives.
Here is a minimal example.
public class AccountService {
@future
public static void updateAccountRatings(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}The method takes a Set<Id>. Id is a primitive type in Apex, so a set of them is allowed. The method then queries the records again instead of receiving them as objects. That detail has its own chapter, but you should notice it now. Passing the IDs and querying inside the method means the code works with the data as it exists when the method runs, not as it existed when the method was queued.
Why `static` and `void`
The method is static because Salesforce runs it without an instance of your class. There is no object whose state could be carried over to the later transaction.
The method returns void because there is nothing to return to. The calling transaction has finished, or at least moved on, by the time the body runs. If you need to pass a result back, write it to a record or a custom object that the caller can read later.
Parameter types in practice
Sobjects and custom Apex classes are not allowed as parameters. The compiler rejects them. Collections of primitives are fine, so these signatures are valid:
String nameSet<Id> idsList<String> namesMap<Id, String> notes
These are not valid:
Account accList<Account> accountsMyWrapper data
If you need to hand over richer data, serialize it to a JSON String with JSON.serialize() and deserialize it inside the method. Keep in mind that this copies the data at call time, so it can go stale before the method runs.
Calling a future method
You call a future method the way you call any static method.
Set<Id> ids = new Map<Id, Account>([SELECT Id FROM Account LIMIT 10]).keySet();
AccountService.updateAccountRatings(ids);Nothing in the call looks different from a synchronous call. The difference is in what happens next. Salesforce serializes the arguments, adds a request to the asynchronous queue, and returns. Your code continues. The body of updateAccountRatings runs after your current transaction finishes and the platform picks up the request.
Because the arguments are serialized at the call, later changes to the variables you passed have no effect on the queued request. If you add an ID to the set after the call, the future method will not see it.
Set<Id> ids = new Set<Id>{ firstId };
AccountService.updateAccountRatings(ids);
ids.add(secondId); // not seen by the future methodThe call sequence
The diagram shows how a call moves from the caller to the future method.
Notice that the request is accepted before the caller finishes. The future method starts only after the calling transaction ends.
Adding options to the annotation
The @future annotation takes one optional parameter, callout. The default is false, which means the method cannot make HTTP or web service callouts. Set it to true to allow them.
public class BillingCallout {
@future(callout=true)
public static void sendAccounts(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(accounts));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + res.getStatus());
}
}
}Billing_API here is a placeholder for a Named Credential you would create in Setup. If you leave out callout=true, the platform throws a System.CalloutException when the method tries to send the request. A later chapter covers callouts in detail. For now, remember that the flag is part of the declaration, not something you can decide at run time.
What you can rely on, and what you cannot
Future methods look simple, so it is easy to assume more than the platform promises. The table lists the common assumptions.
| Assumption | Reality |
|---|---|
| The method runs right after I call it | It runs when resources are available. The delay is usually short but is not guaranteed. |
| Two future calls run in the order I made them | The platform does not guarantee order. |
| I can use the result in my code | The method returns `void`, and it has not run yet when your code continues. |
| Static variables are shared with the caller | The future method runs in a new transaction, so static state is not carried over. |
| If the caller rolls back, the future call is cancelled | The behavior depends on when the failure happens. Do not rely on the queue being rolled back. Design the method to cope with records that no longer exist. |
The last row deserves care. If the calling transaction fails and rolls back, the queued request is not sent, because queueing is part of the transaction. But if the caller commits and a later change deletes a record, the future method may receive an ID that no longer matches a row. A query with WHERE Id IN :accountIds returns only the records that still exist, so the code above handles that case without an error.
Checking whether you are already in a future method
Apex gives you two static checks that matter when a method might be reached from several places.
System.isFuture()returnstruewhen the current code is running inside a future method.System.isBatch()returnstruewhen the current code is running inside a Batch Apex execution.
A future method cannot call another future method. A guard prevents an exception when shared code, such as a trigger handler, runs in both contexts.
public class RatingDispatcher {
public static void requestRatingUpdate(Set<Id> ids) {
if (System.isFuture() || System.isBatch()) {
// Already asynchronous: do the work directly instead of queueing it.
AccountService.updateAccountRatings(ids);
} else {
AccountService.updateAccountRatings(ids);
}
}
}This example has a flaw that you should understand. In the isFuture() branch, the code calls the future method, which is the very thing the guard exists to avoid. Calling a future method from inside a future method throws an exception. To fix it, move the logic into a plain static method and make the future method a thin wrapper around it.
public class AccountService {
public static void applyRatings(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
@future
public static void applyRatingsAsync(Set<Id> accountIds) {
applyRatings(accountIds);
}
}
public class RatingDispatcher {
public static void requestRatingUpdate(Set<Id> ids) {
if (System.isFuture() || System.isBatch()) {
AccountService.applyRatings(ids);
} else {
AccountService.applyRatingsAsync(ids);
}
}
}This pattern keeps the business logic in one place. It also lets you unit test the logic without involving the queue.
Common errors at declaration and call time
- Non-static method.
@future public void run()fails to compile. Addstatic. - Non-void return type.
@future public static Boolean run()fails to compile. Change the return type tovoid. - Sobject parameter.
@future public static void run(Account a)fails to compile. Pass the ID instead. - Missing
callout=true. The method compiles but throwsSystem.CalloutExceptionat run time when it sends a request. - Future call from a future method. This throws
System.AsyncExceptionat run time. Use the wrapper pattern above. - Overloaded future methods. Avoid giving two future methods the same name in one class. Distinct names make debug logs and the Setup monitoring page easier to read.
Summary of the declaration checklist
Before you commit a future method, confirm each item:
- The method is
staticand returnsvoid. - Every parameter is a primitive or a collection of primitives.
- The method queries the data it needs instead of trusting stale values.
callout=trueis set if the method sends an HTTP or web service request.- The business logic lives in a separate method that other contexts can call directly.
Exercise
A developer writes @future public static void sync(List<Contact> contacts) { update contacts; } and calls it from a trigger. The class does not compile. List two changes that fix it, and explain why the new version is safer with respect to data that changes before the method runs.
Show answer
First, replace the parameter with a collection of primitives, such as Set<Id> contactIds, because sobjects are not allowed as future method parameters. Second, query the contacts inside the method with SELECT ... FROM Contact WHERE Id IN :contactIds before updating them. The method now works with the field values as they exist when it runs, not the copy taken at call time, and it skips records that were deleted in the meantime.
Exercise
A trigger handler calls AccountService.updateAccountRatings(ids), which is a future method. A Batch Apex class later reuses the handler, and the run fails. Why does it fail, and how do you restructure the code so both contexts work?
Show answer
A future method cannot be called from a Batch Apex execution, so the call throws an exception at run time. Move the logic into a plain static method, make the future method a thin wrapper that calls it, and have the handler check System.isFuture() || System.isBatch(). In those contexts it calls the plain method directly. Otherwise it calls the future wrapper.