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

Deadlock exceptions due to lock upgrades can be avoided by using update locks instead of exclusive locks, as an object gets unlocked before its lock is upgraded from shared to update (as mentioned in “Upgrading and Downgrading Locks”, earlier in this chapter). For example, you could change the above code sequence to the following.

using (System.Data.IDbTransaction tran = context.BeginTransaction())
{
    bool retry = false;
    do
    {
        if (!allPeople.Contains(person))
        {
            if (retry)
                retry = false;
            else
            {
                try
                {
                    context.Lock(allPeople, LockType.Update,
                                            LockDuration.Transaction,
                                            TimeSpan.FromSeconds(2));
                }
                catch (JoobInterveningUpdateException)
                {
                    retry = true;
                    continue;
                }
            }
            allPeople.Add(person);
        }
    }
    while (retry);

    tran.Commit();
}

A deadlock does not occur when two JADE sessions execute this code sequence at the same time. Even though both JADE sessions can end up with shared locks on the collection, because the collection gets temporarily unlocked, one of the sessions acquires the update lock, allowing it to proceed to transaction completion and unlock the collection, then followed by the other session.

Note that this code fragment has to deal with a JoobInterveningUpdateException, which can be thrown if another JADE session updates the collection before the update lock is acquired (while it is unlocked). To do this, the collection is explicitly locked and a catch block is used to indicate the operation should be retried. The JoobInterveningUpdateException is thrown after the update lock is acquired, so the object does not need to be locked again. An explicit lock is used, because if an exception is thrown while an implicit lock is being attempted for inverse maintenance, the transaction is rolled back before the catch block is executed. This avoids having to repeat the whole transaction.

For more details, see “Exceptions”, later in this chapter.