Stuart Blackler
Stuart Blackler

Reputation: 3772

Multiple lock objects necessary?

Given the following class:

class x
{
    Object lockOne = new Object();
    Object lockTwo = new Object();

    List<Something> listOne = new List<Something>();
    List<Something> listTwo = new List<Something>();

    void MethodOne()
    {
        lock(lockOne)
        {
            // some operation on listOne
        }
    }

    void MethodTwo()
    {
        lock(lockTwo)
        {
            // some operation on listTwo
        }
    }
}

Is it correct to use two locking objects assuming that MethodOne() and MethodTwo() can be called from different threads concurrently noting that listOne and listTwo are not related in anyway. The only operations involved in the locks are those specified in the comments above.

Upvotes: 16

Views: 4572

Answers (2)

svick
svick

Reputation: 244767

There is no need for the separate lock objects here. The following code will work just as well, with less code, less overhead and less chance of mistakenly using incorrect lock:

class x
{
    List<Something> listOne = new List<Something>();
    List<Something> listTwo = new List<Something>();

    void MethodOne()
    {
        lock (listOne)
        {
            // some operation on listOne
        }
    }

    void MethodTwo()
    {
        lock (listTwo)
        {
            // some operation on listTwo
        }
    }
}

Upvotes: 10

Matthew Watson
Matthew Watson

Reputation: 109567

Yes, it is correct. It avoids needlessly locking one list just because the other list is being worked on.

Upvotes: 10

Related Questions