Why are SObjects prohibited as parameters in @future methods, and how should developers work around this?
Answer
Basics: A future method is a static void method annotated @future that runs asynchronously in its own transaction, typically to make callouts after DML or to move work off the user's thread. Salesforce restricts parameter types to primitives (Integer, String, Id, Boolean, Date and so on) and collections of them.
How it works: At call time the arguments are serialised and queued. At run time the platform invokes the method with those values. If an SObject were allowed, it would carry a snapshot of field values taken at enqueue time, and by the time the method runs another user or process may have changed the record; updating with the old copy would overwrite newer data. Passing Ids forces you to re-query the current state.
Advanced / deep dive: Workarounds: pass Set<Id> or List<Id>, then query inside the method; or pass a JSON string (JSON.serialize(records)) and deserialise, accepting that it is still a snapshot; or, better, use Queueable, which allows SObjects and custom types. Other future limits: maximum 50 future calls per transaction; the method cannot be called from another future or from batch; order of execution is not guaranteed; no return value, so no job Id to track; chaining is not possible; and the org-wide async cap (greater of 250,000 or licenses multiplied by 200 per 24 hours) is shared. Use @future(callout=true) for callouts. Future methods cannot be called in a loop for each record; pass the whole collection in one call. Because ordering is not guaranteed, do not rely on two futures running in sequence. In tests, calls run synchronously at Test.stopTest().
Code / config example:
public class {
{
List<Account> accts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
}
}
AccountService.syncAccounts( <Id, Account>(newAccounts).keySet());