+ Start a Discussion
Ken_KoellnerKen_Koellner 

FOR UPDATE, how does it help if it doesn't also read lock?

Documenation says -- Apex allows developers to lock sObject records while they are being updated in order to prevent race conditions and other thread safety problems. While an sObject record is locked, no other program or user is allowed to make updates.

 

Is this how it would work--

 

Scenerio 1:

 

Thread A reads with FOR UPDATE.

Thread B reads with FOR UPDATE, read succeeds as lock only blocks the update DML.

Thread A tries to update but fails with an Exception as thread B has a lock.

Thread B tries to update and it works because the thread A no longer has lock.

 

Scenerio 2:

 

Thread A reads with FOR UPDATE.

Thread B reads with FOR UPDATE, read succeeds has lock only blocks the update DML.

Thread B tries to update but fails with an Exception as thread A has a lock.

Thread A tries to update and it works because the thread B no longer has lock.

 

 

 

Ken_KoellnerKen_Koellner

I did a little test with some apex that reads a record for update, wastes some time, and then tries to update the record.

Account acct = [select id from account where id = '0014000000NeYAz' for update];

integer i = 0;
for (Opportunity opp : [select id from Opportunity limit 40000] ) {
  i++;
}

update acct;

 

I ran that code as ad-hoc Apex in two browsers starting them simultaneously.  One succeeds and the other fails. The log for the one that fails shows an exception on the select, not the update.  So the documentation doesn't appear to be exactly correct.  It's not the other update that is prevented, it's the other select.

 

Below is a portion of the log showing the exception.

 

12:42:57.031 (31040000)|VARIABLE_SCOPE_BEGIN|[1]|acct|Account|true|false
12:42:57.031 (31123000)|SOQL_EXECUTE_BEGIN|[1]|Aggregations:0|select id from account where id = '0014000000NeYAz' for update
12:43:06.784 (9784145000)|EXCEPTION_THROWN|[1]|System.QueryException: Record Currently Unavailable: The record you are attempting to edit, or one of its related records, is currently being modified by another user. Please try again.
12:43:06.784 (9784243000)|FATAL_ERROR|System.QueryException: Record Currently Unavailable: The record you are attempting to edit, or one of its related records, is currently being modified by another user. Please try again.