function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ChristadChristad 

When are records released when using record Locking with SELECT FOR UPDATE

Hi

 

I am not sure when records are released following a SELECT FOR UPDATE lock in APEX and whether it locks the parent and child records. The link http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_locking_statements.htm suggests that a select for update operation releases the record at the end of the transaction and not after a DML operation for that sobject. The link http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_deadlocks.htm suggests that it locks the parent and its child records

 

1) Are the record released at the end of the transaction as in the example below or at the end of the first DML operation on that object ?

2) If the example class below is part of a chain of transactions, eg a trigger calls  s.doSomething() will the record be released at the end of the trigger script or immediately after the doSomething() method completes?

3) If the parent and its child records are locked, can other threads insert new child records ?

 

SomeClass s = new SomeClass();

s.doSomething();

 

public with sharing SomeClass {

     public Boolean doSomething(String x) {

                Case c = [Select CaseNumber, Status from Case limit 1 for update];    // Locks parent and child records

                c.status = ‘Closed’;

                update c;                        // DML Operation completes but does not yet release record lock

              

CaseComment cmt = new CaseComment( ParentId = c.id, IsPublished = false, CommentBody = ' some text \n');                 insert cmt;

 

      }         // DML record lock now released at end of transaction

}

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
Bhawani SharmaBhawani Sharma
1. Yes records will be released whenever the transaction completes.
2. Record will be release after doSomething.
3. I think yes, if Child doesn't update anything on parent

All Answers

Bhawani SharmaBhawani Sharma
1. Yes records will be released whenever the transaction completes.
2. Record will be release after doSomething.
3. I think yes, if Child doesn't update anything on parent
This was selected as the best answer
ChristadChristad
Yes that does seem logical. Thanks Bhawani