Skip to content

Shared Object Lock

Lock on a dedicated object instance

What does this mean ?

Shared resources should not be used for locking as it increases the chance of deadlocks. Any other thread could acquire (or attempt to acquire) the same lock for another unrelated purpose. Instead, a dedicated object instance should be used for each shared resource, to avoid deadlocks or lock contention.

What can happen ?

Deadlock can occur if shared resources is used for locking.

Recommendation

The following objects are considered as shared resources: this: - a Type object - a string literal - a string instance

Sample Code

Vulnerable :

public void MyLockingMethod()
{
    lock (this) // Noncompliant
    {
        // ...
    }
}

Non Vulnerable :

private readonly object lockObj = new object();

public void MyLockingMethod()
{
    lock (lockObj)
    {
        // ...
    }
}

References