What are Future Methods in Salesforce Apex, and what are their primary limitations regarding parameter types and chaining?
Answer
Basics: Use it to offload a callout or to avoid mixed DML errors after a trigger runs. Salesforce queues it and runs it when resources allow.
How it works: Declare @future (or @future(callout=true) for callouts) on a static void method. Pass record IDs, re-query inside the method to get fresh data, and do the work. Up to 50 future calls can be made per transaction. The calling transaction finishes first; the future runs later in a new transaction with async limits (200 SOQL, 60,000 ms CPU, 12 MB heap).
Advanced / deep dive: Limitations: parameters cannot be sObjects or custom Apex types; execution order is not guaranteed; you cannot call a future method from another future or from a batch job; no return values and no job ID, so monitoring is hard. Queueable is generally recommended today because it accepts complex types, returns a job ID, and supports chaining. Async executions across batch, future, queueable and scheduled count against a shared 24-hour limit (verify current figure). Use System.isFuture() and System.isBatch() to guard recursion. Future methods are ideal for the simple "fire-and-forget" callout or the setup/non-setup mixed DML separation.
Code / config example:
public class AccountSync {
@future(callout=true)
public static void push(Set<Id> accountIds) {
List<Account> accts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
// build one request for the whole set and call out here
}
}
Hidden gotchas & must-remember points:
- Cannot pass sObjects; pass IDs and re-query.
- Max 50 future calls per transaction.
- Not allowed from future or batch contexts.
- Order of execution is not guaranteed.
- Tests: wrap in Test.startTest()/stopTest() to force execution.
- Callouts require callout=true.
Best practice: Prefer Queueable for new development; use future only for simple fire-and-forget work.