+ Start a Discussion
Rocio VivancoRocio Vivanco 

How to handle UNABLE_LOCK_ROW errors when this is caused by a batch APEX job

Hi all,

we are facing a serious issue.
We have a batch APEX job running daily which makes updates on records fulfilling certain conditions. There is another job running parallel to this, in some cases updating or accessing to the same records than the batch job and hence, causing the error:
​Update failed. First exception on row 400 with id XXX; first error: UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record or 200 records:

So, I had then read that in order to fix this kind of error you should use FOR_UPDATE in your select statement (records that have to be updated).
The problem is, that you can not use FOR UPDATE for batch jobs. We tested this and effectively, we get the error:
System.QueryException: Locking is implied for each batch execution and therefore FOR UPDATE should not be specified
It will however lock the records within each execution of execute. See QueryLocator.getQuery()usage:

You cannot use the FOR UPDATE keywords with a getQueryLocator query to lock a set of records. The start method automatically locks the set of records in the batch.

Could you find a solution to this?. We would like to handle this in the code itself, because we don't have the permission to schedule the batch job for another time as the another job.