How To Prevent Row lock Or Race Condition Issues In Apex

Allow me to guide you on preventing row lock or race condition issues 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];

When employing a query of this nature, the record upon which specific business logic is executed becomes locked, preventing its sharing with other entities or batches.