How to avoid row lock or race condition in Apex

Let me walk you through how to avoid row lock or race condition in Apex

When multiple users try to invoke a batch Apex class and when one record or same set of records are shared by multiple batch jobs we will potentially encounter a race condition.

The fix for that is very simple. We need to lock the records on which we are working such that other batches or threads will not be having any effect on them.

How can we lock a record, then?

We need to make use of FOR UPDATE keyword in the SOQL query.

Here is a sample SOQL query.

List<Account> accounts = [SELECT Id, Name FROM ACCOUNT LIMIT 10 FOR UPDATE];
Avoiding race condition in Apex

When we use a query like this the record on which specific business logic is being executed will be locked and it will not be shared by other entities/batches etc.