sundar
sundar

Reputation: 235

Does this nested locking cause deadlock?

Method1 and Method2 are public methods. Both the methods are required to take in two locks in the same order. Am sure acquiring locks in the same order will not end up in deadlock. Are the locks in Common() unnecessary?

public void Method1()
{
    lock(LockObjA)
    lock(LockObjB)
    {
        //DoSomething
        Common();
    }
}

public void Method2()
{
    lock(LockObjA)
    lock(LockObjB)
    {
        //DoSomething else
        Common();
    }
}

private void Common()
{
    lock(LockObjA)
    lock(LockObjB)
    {
        //DoSomething else
    }
}

Upvotes: 2

Views: 720

Answers (1)

isaias-b
isaias-b

Reputation: 2289

I couldn't find a better reference on the rush but i can remember well my Operating System course with resource locking where the professor stated that always acquiring the resources in the same order doesn't raise the chances for deadlocks to happen.

always acquiring resources in same order

Edit: Found a stackoverflow question about this but still no article to this specific deadlock prevention mechanism...

Since c# locks are reentrant it should not do more harm when using your code.

Back to your qeustion

If all methods are private you have a really small scope within your class to check the lock conditions. So on public API it would be better to decorate all methods which are changing mutable state with locks. Even if that means that they might reenter on the same lock twice. In private API you can decide wether appropriate.

Edit: After Qestion Edit

If the three methods you have are the only one you have in your scope, or that three methods are the only critical ones (modifying/accessing mutable state). And since you can see nothing more to happen which can break the locking.

Then the answer is YES! In method Common the locking is not neccessary.

Note: Decorating methods

By decoration i mean decoration in the sense of the Decorator Pattern. Which means execute code before and after some piece of code. In this case i mean the code inside a method. In java there exist a synchronized key word which allows to use a short hand to decorate the code inside the method conveniently with a synchronized block using the enclosing instance object. This is called a synchronized method.

Upvotes: 5

Related Questions