Lock Records Using Apex in Salesforce
Locking Statements
In Apex, you can use FOR UPDATE to lock sObject records while they’re being updated to prevent race conditions and other thread safety problems.
Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];
Locking Consideration
When records are locked by a client, that client can modify the record's field values in the database within the same transaction. Other clients must wait until the transaction is completed and the records are no longer locked before they can update the same records. However, other clients can still query the locked records. If a record is already locked by another client, a process will wait for a maximum of 10 seconds for the lock to be released before acquiring a new lock. If the wait exceeds 10 seconds, a QueryException is thrown. Similarly, if a record is locked by another client and the lock is not released within 10 seconds, a DmlException is thrown. If a client tries to modify a locked record, the update can succeed if the lock is released shortly after the update call. If this happens, the updates may overwrite any changes made by the locking client. To prevent this, the second client must lock the record first and obtain a fresh copy of the record from the database through a SELECT statement, which can be used to make new updates. When using the FOR UPDATE clause in Apex, record locks are automatically released when making callouts. This is logged in the debug log, which includes the most recently locked entity type. It is important to be cautious when making callouts in contexts where FOR UPDATE queries may have been previously executed. Additionally, when performing a DML operation on one record, related records are also locked.
Locking in a SOQL For Loop
for (Account[] accts : [SELECT Id FROM Account
FOR UPDATE]) {
// Your code
}
Note that there is no commit statement. If your Apex trigger completes successfully, any database changes are automatically committed. If your Apex trigger does not complete successfully, any changes made to the database are rolled back.
Avoiding Deadlocks
Apex has the possibility of deadlocks, as does any other procedural logic language involving updates to multiple database tables or rows. To avoid such deadlocks, the Apex runtime engine:
First locks sObject parent records, then children.
Locks sObject records in order of ID when multiple records of the same type are being edited.
Comments
Post a Comment