Lazy, thread-safe Singleton (using Double C# with Example



Lazy, thread-safe Singleton (using Double C# with Example

Checked Locking) 
This thread-safe version of a singleton was necessary in the early versions of .NET where static initialization was 
not guaranteed to be thread-safe. In more modern versions of the framework a statically initialized singleton is 
 

usually preferred because it is very easy to make implementation mistakes in the following pattern. 
public sealed class ThreadSafeSingleton 
{ 
private static volatile ThreadSafeSingleton instance; 
private static object lockObject = new Object(); 
private ThreadSafeSingleton() 
{ 
} 
public static ThreadSafeSingleton Instance 
{ 
get 
{ 
if (instance == null) 
{ 
lock (lockObject) 
{ 
if (instance == null) 
{ 
instance = new ThreadSafeSingleton(); 
} 
} 
} 
return instance; 
} 
} 
} 
Notice that the if (instance == null) check is done twice: once before the lock is acquired, and once afterwards. 
This implementation would still be thread-safe even without the first null check. However, that would mean that a 
lock would be acquired every time the instance is requested, and that would cause performance to suffer. The first 
null check is added so that the lock is not acquired unless it's necessary. The second null check makes sure that 
only the first thread to acquire the lock then creates the instance. The other threads will find the instance to be 
populated and skip ahead. 

0 Comment's

Comment Form