-
Notifications
You must be signed in to change notification settings - Fork 4
Gendarme.Rules.Concurrency.DoubleCheckLockingRule(git)
Assembly: Gendarme.Rules.Concurrency
Version: git
This rule is used to check for the double-check pattern, often used when implementing the singleton pattern (1), and warns of potential incorrect usage. The original CLR (1.x) could not guarantee that a double-check would work correctly in multithreaded applications. However the technique does work on the x86 architecture, the most common architecture, so the problem is seldom seen (e.g. IA64). The CLR 2 and later introduce a strong memory model (2) where a double check for a lock is correct (as long as you assign to a volatile variable). This rule won't report a defect for assemblies targetting the 2.0 (and later) runtime.
- 1. Implementing Singleton in C# : http://msdn.microsoft.com/en-us/library/ms998558.aspx
- 2. Understand the Impact of Low-Lock Techniques in Multithreaded Apps : http://msdn.microsoft.com/en-ca/magazine/cc163715.aspx#S5
Bad example:
public class Singleton {
private static Singleton instance;
private static object syncRoot = new object ();
public static Singleton Instance {
get {
if (instance == null) {
lock (syncRoot) {
if (instance == null) {
instance = new Singleton ();
}
}
}
return instance;
}
}
}
Good example (for 1.x code avoid using double check):
public class Singleton {
private static Singleton instance;
private static object syncRoot = new object ();
public static Singleton Instance {
get {
// do not check instance before the lock
// this will work on all CLRs but will affect
// performance since the lock is always acquired
lock (syncRoot) {
if (instance == null) {
instance = new Singleton ();
}
}
return instance;
}
}
}
Good example (for 2.x and later):
public class Singleton {
// by using 'volatile' the double check will work under CLR 2.x
private static volatile Singleton instance;
private static object syncRoot = new object ();
public static Singleton Instance {
get {
if (instance == null) {
lock (syncRoot) {
if (instance == null) {
instance = new Singleton ();
}
}
}
return instance;
}
}
}
You can browse the latest source code of this rule on github.com
Note that this page was autogenerated (3/17/2011 1:55:44 PM) based on the xmldoc
comments inside the rules source code and cannot be edited from this wiki.
Please report any documentation errors, typos or suggestions to the
Gendarme Mailing List. Thanks!