0

In apex when we get UNABLE_TO_LOCK exception,most of the solutions are referring to use FOR UPDATE clause in the SOQL.

My questions are:

  1. My Doubt is what if Already some other record has lock before running the SOQL ,will the query return that record?
  2. And if UNABLE_TO_LOCK exception is coming for Parent record of the failed record, then if we use FOR UPDATE while fetching the child record will work?
  3. And what if that query is returning records where more than two records have same parent, how will FOR UPDATE will lock parent records at that time?

1 Answer 1

2

My Doubt is what if Already some other record has lock before running the SOQL ,will the query return that record?

The query will wait up to 10 seconds. If it does not acquire the lock within that time, an exception is thrown, and no results are returned. You will never get "incorrect" results when using a locking query. You can use this behavior to try again:

SObject[] records;
while(records == null) {
  try {
    records = [SELECT ... FROM ... WHERE ... FOR UPDATE];
  } catch(QueryException e) {
  }
}

And if UNABLE_TO_LOCK exception is coming for Parent record of the failed record, then if we use FOR UPDATE while fetching the child record will work?

See Avoiding Deadlocks. Parents are locked before their children, so if the parent can't be locked, the child can't be locked, and you'll get a QueryException.

And what if that query is returning records where more than two records have same parent, how will FOR UPDATE will lock parent records at that time?

Locks are per-transaction, so there's no problem. The locks occur atomically (so they either all pass, or an exception is thrown). It doesn't matter how many times a parent is referenced, it will only be "locked" once.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .