TransWikia.com

SOQL For Update to Release Locks

Salesforce Asked by Jair on November 19, 2021

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?

One Answer

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.

Answered by Phil W on November 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP