Shared Object Lock
Lock on a certain object instance
What does this mean ?
Locking should not be done with shared resources since it raises the likelihood of deadlocks. Any other thread might obtain (or seek to obtain) the same lock for an unrelated reason. To avoid deadlocks or lock contention, each shared resource should have its own object instance.
What can happen ?
If shared resources are used for locking, deadlock might develop.
Recommendation
The following items are regarded as shared resources:
- 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)
{
// ...
}
}