Product Information > JADE .NET Developer’s Reference > Chapter 2 - Object Management > Lock Order
Lock Order

For deadlocks involving multiple JADE objects, the classic technique for avoiding deadlocks is that each JADE session should lock the objects in the same order. The direct and indirect examples described earlier in this chapter could not arise if this principle is used. For example, the following two code fragments cause a deadlock, if executed by different JADE sessions at the same time.

context.Lock(obj1, LockType.Shared, LockDuration.Transaction,
                    TimeSpan.FromSeconds(5));
//...
context.Lock(obj2, LockType.Exclusive, LockDuration.Transaction,
                    TimeSpan.FromSeconds(5));
//...
context.Unlock(obj2);
context.Unlock(obj1);


context.Lock(obj2, LockType.Shared, LockDuration.Transaction,
             TimeSpan.FromSeconds(5));
//...
context.Lock(obj1, LockType.Exclusive, LockDuration.Transaction,
             TimeSpan.FromSeconds(5));
//...
context.Unlock(obj1);
context.Unlock(obj2);

The first JADE session cannot get the exclusive lock on obj2 because the second session has a shared lock on it. The second JADE session cannot get the exclusive lock on obj1 because the first session has a shared lock on it.

The deadlock cannot occur if the second code sequence locks the objects in the same order as the first, as follows.

context.Lock(obj1, LockType.Exclusive, LockDuration.Transaction,
             TimeSpan.FromSeconds(5));
//...
context.Lock(obj2, LockType.Shared, LockDuration.Transaction,
             TimeSpan.FromSeconds(5));
//...
context.Unlock(obj2);
context.Unlock(obj1);

The first JADE session to lock obj1 blocks the other, preventing it from locking obj2 and setting up the deadlock.

Lock ordering issues are not always obvious, as locks are commonly implicitly acquired. For example, accessing a JADE collection implicitly acquires a shared lock, and updating an object implicitly acquires an update or exclusive lock.