Pessimistic Locking

Pessimistic locking is an approach when an entity is locked in the database for the entire time that it is in application memory. This means that an object should be locked as soon as it is retrieved from the database and released after commit.

PessimisticThread.cs: run
01public void Run() 02 { 03 try { 04 IObjectSet result = _db.Get(typeof(Pilot)); 05 while (result.HasNext()){ 06 Pilot pilot = (Pilot)result.Next(); 07 /* with pessimistic approach the object is locked as soon 08 * as we get it 09 */ 10 if (!_db.Ext().SetSemaphore("LOCK_"+_db.Ext().GetID(pilot), 0)){ 11 Console.WriteLine("Error. The object is locked"); 12 } 13 14 Console.WriteLine(Name + "Updating pilot: " + pilot); 15 pilot.AddPoints(1); 16 _db.Set(pilot); 17 /* The changes should be committed to be 18 * visible to the other clients 19 */ 20 _db.Commit(); 21 _db.Ext().ReleaseSemaphore("LOCK_"+_db.Ext().GetID(pilot)); 22 Console.WriteLine(Name + "Updated pilot: " + pilot); 23 Console.WriteLine(); 24 } 25 } finally { 26 _db.Close(); 27 } 28 29 }
 

PessimisticThread.vb: run
01Public Sub Run() 02 Try 03 Dim result As IObjectSet = _db.Get(GetType(Pilot)) 04 While result.HasNext 05 Dim pilot As Pilot = CType(result.Next, Pilot) 06 ' with pessimistic approach the object is locked as soon 07 ' as we get it 08 If Not _db.Ext.SetSemaphore("LOCK_" + _db.Ext.GetID(pilot).ToString(), 0) Then 09 Console.WriteLine("Error. The object is locked") 10 End If 11 Console.WriteLine(Name + "Updating pilot: " + pilot.ToString()) 12 pilot.AddPoints(1) 13 _db.Set(pilot) 14 ' The changes should be committed to be 15 ' visible to the other clients 16 _db.Commit() 17 _db.Ext.ReleaseSemaphore("LOCK_" + _db.Ext.GetID(pilot).ToString()) 18 Console.WriteLine(Name + "Updated pilot: " + pilot.ToString()) 19 Console.WriteLine() 20 End While 21 Finally 22 _db.Close() 23 End Try 24 End Sub
 

As you see this approach is considerably easier to implement. Another advantage is that it guarantees that your changes to the database are made consistently and safely.

The main disadvantage is the lack of scalability. Time waiting for the lock to be released can become unacceptable for a system with many users or long transactions. This limits the practical implementations of pessimistic locking.

You may want to select pessimistic locking in cases when the cost of loosing the transaction results due to a collision is too high.