Salesforce Interview Questions & Answers Book is now available!

Grab Now

Apex

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.

By Teja, ex-Salesforce engineer · Updated April 1, 2021 · 1 min read

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.

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts