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.
01public void run() { 02
try { 03
ObjectSet result = _db.get(Pilot.class); 04
while (result.hasNext()){ 05
Pilot pilot = (Pilot)result.next(); 06
/* with pessimistic approach the object is locked as soon 07
* as we get it 08
*/ 09
if (!_db.ext().setSemaphore("LOCK_"+_db.ext().getID(pilot), 0)){ 10
System.out.println("Error. The object is locked"); 11
} 12
13
System.out.println(getName() + "Updating pilot: " + pilot); 14
pilot.addPoints(1); 15
_db.set(pilot); 16
/* The changes should be committed to be 17
* visible to the other clients 18
*/ 19
_db.commit(); 20
_db.ext().releaseSemaphore("LOCK_"+_db.ext().getID(pilot)); 21
System.out.println(getName() + "Updated pilot: " + pilot); 22
System.out.println(); 23
} 24
} finally { 25
_db.close(); 26
} 27
}
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.