0

When there are multiple requests to execute some code with a SOQL using For Update at same time, other Apex threads will wait the previous Lock released to execute the reminder code after the SOQL event though the previous thread SOQL does not return any records.

Is there a way to release all locks when a thread finds the lock is useless?

For example:

The SOQL:

Select Id from Account where Type = 'Customer' limit 1 For Update

Only 1 records in DB which matches the above SOQL. When 1K requests to execute this SOQL at same time, the first thread updates the Account.Type to another value, can I release the reminder 999 locks at once?

1
  • Locks are applied only on the records retrieved by the query. If your query returns just 1 record, other records of that Object won't be locked to begin with.
    – mritzi
    Jul 22, 2020 at 7:15

1 Answer 1

1

As per the documentation, FOR UPDATE locks specific records, not the entire table (though there can be additional locks once DML is applied). I am therefore unclear why you say "other apex threads will wait ... even though the previous thread ... does not return any records" since this doesn't align with expected behaviour.

If you have multiple FOR UPDATE queries that have any result set overlap then there is lock contention and the second thread is paused. The lock is automatically released when the locking thread terminates (because the request/session has completed). If there's no overlap then the locks are independent and the threads don't interact.

When multiple threads hit a FOR UPDATE query and have result set overlap all threads but the first are paused. When the lock is released the Salesforce system selects one of the paused threads, grants it the lock and unpauses it. Any request that performed a FOR UPDATE and then was paused for 10 elapsed seconds (or a bit more) is unpaused with a QueryException being thrown from the SOQL statement.

In essence there is no way to arbitrarily unpause any of your threads and you must wait for Salesforce to handle the locks in the expected manner.

You must log in to answer this question.

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