Sub topic 3
What a Future Method Can Accept
This chapter assumes you can write Apex classes and static methods, work with List, Set, and Map collections, run SOQL and DML, and know that governor limits exist. You have already seen how to declare and call a future method. Here you learn what you can and cannot pass into one, why those rules exist, and how to work within them.
The rules at a glance
A future method has three hard requirements on its signature:
- It must be
static. - It must return
void. - Its parameters must be primitive data types, arrays of primitives, or collections of primitives.
The compiler enforces the first two. The third is enforced at compile time for obvious violations (such as an Account parameter) and at runtime in some less obvious cases.
public class SignatureExamples {
// Valid: primitive parameter
@future
public static void withString(String note) { }
// Valid: collection of primitives
@future
public static void withIds(Set<Id> ids) { }
// Valid: list of primitives
@future
public static void withNumbers(List<Integer> values) { }
// Valid: map with primitive keys and values
@future
public static void withMap(Map<Id, String> notesById) { }
// Valid: no parameters at all
@future
public static void noArguments() { }
}Why the restrictions exist
When you call a future method, Salesforce does not run it immediately. It saves the method name and the argument values in a queue, and a separate process runs the method later in its own transaction. Two consequences follow.
First, the arguments must be easy to store and restore. Primitives and collections of primitives can be serialized into a simple, stable form. An sObject or an instance of your own class carries state that may be out of date by the time the method runs, or may not be serializable in this way.
Second, the method has no way to hand a result back. The caller has already finished by the time the future method starts, so a return value would have nowhere to go. That is why the return type must be void.
Allowed parameter types
The following table lists what you can pass.
| Parameter type | Allowed | Notes |
|---|---|---|
| `String`, `Integer`, `Long`, `Decimal`, `Double`, `Boolean` | Yes | Passed by value. |
| `Id` | Yes | The most common choice for pointing at a record. |
| `Date`, `Datetime`, `Time` | Yes | Primitive types in Apex. |
| `List<primitive>`, `Set<primitive>` | Yes | Elements must be primitives. |
| `Map<primitive, primitive>` | Yes | Both keys and values must be primitives. |
| Arrays such as `String[]` | Yes | Equivalent to a list. |
| `Account`, `Contact`, or any other sObject | No | Compile-time error. |
| `List<Account>`, `Set<Account>` | No | Collections of sObjects are not primitives. |
| Instances of your own classes | No | Not supported as parameters. |
| `Map<Id, List<String>>` | No | Nested collections are not collections of primitives. |
Nested collections trip people up. A Map<Id, Set<String>> looks harmless, but the value is a collection, not a primitive, so it is not a valid parameter.
What happens when you break the rules
An sObject parameter fails when you save the class:
public class BadFuture {
@future
public static void update(List<Account> accounts) {
// Does not compile: sObjects cannot be future method parameters
}
}The error reads along the lines of "Unsupported parameter type" and names the offending type. Fix it by changing the parameter to Set<Id> and re-querying inside the method.
A method that is not static, or that returns a value, also fails to save:
public class BadSignature {
// Fails: future methods must be static
@future
public void instanceMethod() { }
// Fails: future methods must return void
@future
public static Integer returnsValue() { return 1; }
}Workarounds when you need richer data
Sometimes the data you want to hand over is more than a few IDs. You have three common options.
Pass IDs and re-query
This is the default and the best choice. You send Set<Id> and query the current field values inside the method. The next chapter covers this in detail, including why fresh data matters.
Serialize into a String
You can convert a complex structure to JSON with JSON.serialize(), pass it as a String, and rebuild it with JSON.deserialize() inside the method. This is a legitimate technique, and it is how you pass values that are not records, such as a list of wrapper objects built during a calculation.
public class WrapperExample {
public class Payload {
public Id accountId;
public String newRating;
}
public static void queueRatings(List<Payload> payloads) {
sendRatings(JSON.serialize(payloads));
}
@future
public static void sendRatings(String payloadJson) {
List<Payload> payloads =
(List<Payload>) JSON.deserialize(payloadJson, List<Payload>.class);
Map<Id, String> ratingByAccount = new Map<Id, String>();
for (Payload p : payloads) {
ratingByAccount.put(p.accountId, p.newRating);
}
List<Account> accounts = [
SELECT Id, Rating FROM Account WHERE Id IN :ratingByAccount.keySet()
];
for (Account a : accounts) {
a.Rating = ratingByAccount.get(a.Id);
}
update accounts;
}
}Be careful with this approach. Serializing whole sObjects into a string brings back the stale data problem: the JSON holds the field values from the moment you called the method, and the future method may run minutes later. It also makes the string large, and long arguments count against limits on asynchronous requests. Use JSON for values that belong to your logic, not as a way to smuggle in full records.
Switch to Queueable Apex
If you keep needing complex parameters, a future method is the wrong tool. A Queueable class stores its inputs as member variables, so it can hold sObjects, lists of custom objects, and other non-primitive state. Chapter 13 compares the options in detail.
Primitive does not mean unlimited
Even with valid types, a few details affect what actually arrives.
- Values are copied at call time. The future method receives the value as it was when you queued it. If you change a variable after the call, the queued copy does not change.
- Order of a collection is not guaranteed. A
Set<Id>has no defined order, so do not depend on one. If order matters, pass aListand sort inside the method. - Nulls pass through. A
nullstring or an empty set is valid. Check for empty input at the top of the method so you do not run a pointless query. - The argument size is limited. Very large collections or long JSON strings can exceed the limit on asynchronous request size. Keep payloads small and pass identifiers instead of content.
A defensive start to a future method looks like this:
public class SafeFuture {
@future
public static void process(Set<Id> accountIds) {
if (accountIds == null || accountIds.isEmpty()) {
return;
}
List<Account> accounts = [
SELECT Id, Name FROM Account WHERE Id IN :accountIds
];
// Work with current data here
System.debug('Processing ' + accounts.size() + ' accounts');
}
}Choosing a parameter design
Use these questions to pick the shape of your signature.
- Is the data a record that lives in the database? Pass its
Idand re-query. - Is it a handful of simple values, such as a flag or a label? Pass them as primitives.
- Is it a calculated structure that is not stored anywhere? Serialize it to JSON, or consider Queueable.
- Do you need the callee to return something, or to hold live objects? Use Queueable.
Common mistakes
- Passing
Trigger.newdirectly. It is aList<sObject>, so it is rejected. Build aSet<Id>from it. - Declaring an overload with the same name. Keep each future method name distinct and clear, so the call sites show which method is queued.
- Expecting a result. There is no return value and no way to await completion from the caller. If the caller needs to know when work finishes, store a status on a record or switch to Queueable.
- Passing a
Map<Id, SObject>. The value type is an sObject, so it fails the same way as a list of sObjects.
Exercise
A developer writes @future public static void rate(Map<Id, Account> accountsById) and the class will not save. Explain why, and show a corrected signature and the first two lines of the body that give the method the data it needs.
Show answer
The map's value type is Account, an sObject, and future method parameters must be primitives or collections of primitives. Pass the IDs instead: @future public static void rate(Set<Id> accountIds). Inside, start with if (accountIds == null || accountIds.isEmpty()) { return; } and then query the current records with Map<Id, Account> accountsById = new Map<Id, Account>([SELECT Id, Rating FROM Account WHERE Id IN :accountIds]);.
Exercise
You need to send a future method a list of (accountId, newRating) pairs calculated earlier in the transaction. Future methods cannot take custom class instances. Describe one way to pass the pairs, and name one risk of the approach.
Show answer
Use a Map<Id, String> with the account ID as key and the rating as value, since both are primitives. Alternatively, serialize a list of wrapper objects with JSON.serialize() and rebuild it with JSON.deserialize() in the method. The risk with JSON is argument size, because a large string can exceed asynchronous request limits. The values are also a snapshot from call time, so they may be out of date if the logic depends on current record data.