Product Information > JADE .NET Developer’s Reference > Chapter 2 - Object Management > Reserve Locks
Reserve Locks

Reserve locks can be a useful way to avoid single object deadlocks due to lock upgrade requests. For example, the following code fragment from an earlier example in this chapter can cause a JoobDeadlockException to be thrown if executed by two JADE sessions at the same time with the same object, due to both wanting to upgrade a lock on the allPeople collection from shared to exclusive:

using (System.Data.IDbTransaction tran = context.BeginTransaction())
{
    if (!allPeople.Contains(person))
        allPeople.Add(person);
    tran.Commit();
}

However, if the code initially locks the collection with a reserve lock instead of the implicit shared lock, the deadlock situation will not arise; for example:

using (System.Data.IDbTransaction tran = context.BeginTransaction())
{
    context.Lock(allPeople, LockType.Reserve, LockDuration.Transaction,
                 TimeSpan.FromSeconds(5));
    if (!allPeople.Contains(person))
        allPeople.Add(person);
    tran.Commit();
}

The first JADE session to execute this code sequence acquires the reserve lock. Other JADE sessions executing this sequence queue until the object is unlocked; that is, when the transaction is committed, as a reserve lock is not compatible with other reserve locks. The lock, therefore, can be readily upgraded to exclusive, and the single object deadlock will not occur.

Using an initial reserve lock as opposed to an exclusive lock has the benefit of not blocking other JADE sessions from obtaining shared locks. This could be significant in cases where there is a reasonable time gap between when the object is first locked and when it is updated. However, when that gap is very short, as in the above code example, an exclusive lock may be preferable, as it avoids the overhead of upgrading the lock.