Friday, April 02, 2010

04/02: Double-Checking Locking in .Net

 

The purpose of this mechanism is to improve performance  in Multithread environment.

  • Defer constructing a singleton object until an application requests it (sometimes called lazy initialization).If the application never requests the object, it never gets constructed, saving time and memory
  • If two threads request this singleton object at the same time . Need to use some thread synchronization to make sure thread safe

 

internal sealed class Singleton {
// s_lock is required for thread safety and having this object assumes that creating
// the singleton object is more expensive than creating a System.Object object and that
// creating the singleton object may not be necessary at all. Otherwise, it is more
// efficient and easier to just create the singleton object in a class constructor
private static readonly Object s_lock = new Object();
// This field will refer to the one Singleton object
private static Singleton s_value = null;
// Private constructor prevents any code outside this class from creating an instance
private Singleton() {
// Code to initialize the one Singleton object goes here...
}
// Public, static method that returns the Singleton object (creating it if necessary)
public static Singleton GetSingleton() {
// If the Singleton was already created, just return it (this is fast)
if (s_value != null) return s_value;
lock(s_lock)

{

if (s_value == null) {
// Still not created, create it
Singleton temp = new Singleton();
// Save the reference in s_value (see discussion for

details)

}

}

}
// Return a reference to the one Singleton object
return s_value;
}
}

 

 

According to expert, this way is not perfect

 

In my opinion, developers think it is cool, and they use it far more often than they should. In most scenarios, this technique actually hurts efficiency. Here is a much simpler version of the Singleton class that behaves the same as the previous version. This version does not use the double-check locking technique:

internal sealed class Singleton {
private static Singleton s_value = new Singleton();
// Private constructor prevents any code outside this class from creating an instance
private Singleton() {
// Code to initialize the one Singleton object goes here...
}
// Public, static method that returns the Singleton object (creating it if necessary)
public static Singleton GetSingleton() { return s_value; }
}

0 Comments:

Post a Comment

<< Home