double check locking in singleton pattern - c#

it may be basic question
to have a singleton in multi-threaded environment we can use a lock. Please refer the code snippet. But why do we need double-checked locking in singleton pattern? And more what does double-checked locking means?
class singleton
{
private static singleton instance = null;
private static singleton() { }
private static object objectlock = new object();
public static singleton Instance
{
get
{
lock (objectlock) //single - check lock
{
if (instance == null)
{
instance = new singleton();
}
return instance;
}
}
}
}

Jon Skeet explains this in detail.
Locks are expensive.
If the object already exists, there's no point in taking out a lock.
Thus, you have a first check outside the lock.
However, even if the object didn't exist before you took the look, another thread may have created it between the if condition and the lock statement.
Therefore, you need to check again inside the lock.
However, the best way to write a singleton is to use a static constructor:
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}

And with .Net 4.x and newer you should defer to the Lazy class when possible as this pattern is used with the Initialization And Publication option. (note: the inverse is available as well where creation isn't thread safe but the publication of the instance is via the Publication option)

Multithreaded Singleton : The best approach to use double check locking
public sealed class Singleton
{
private static volatile Singleton _instance;
private static readonly object InstanceLoker= new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (_instance == null)
{
lock (InstanceLoker)
{
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
}

The "best" way I know is this:
public class MySingleton {
// object for synchronization
private static readonly object syncRoot = new object();
// the singleton instance
private static MySingleton #default;
public static MySingleton Default {
get {
// geting singleton instance without locking
var result = #default;
// if result is NOT null, no additional action is required
if ( object.ReferenceEquals(result, null) ){
// lock the synchronization object
lock(syncRoot) {
// geting singleton instanc in lock - because
// the value of #default field could be changed
result = #default;
// checking for NULL
if ( object.ReferenceEquals(result, null) ) {
// if result is NULL, create new singleton instance
result = new MySingleton();
// set the default instance
#default = result;
}
}
}
// return singleton instance
return result;
}
}
}

If you create the object in the field initialiser, you don't need the lock:
class singleton
{
private static singleton instance = new singleton();
private static singleton() { }
public static singleton Instance
{
get { return instance; }
}
}
Also - bear in mind that the lock is only controlling the creation of the object, the object would still need to be thread-safe if you're using it in multiple threads.

When we try to execute the method of the singleton class using Parallel libraries. It doesn’t recognize the singleton behavior because of multi threading is executing in TPL which causes to failure of concept Singleton Pattern . To overcome this problem there is concept of the locking of the object so that at a time only one thread can access it.
But this is not efficient approach because involvement of lock checking creates unnecessary watches to the object. To avoid it we make use “Double locking checking”

Related

Make a 'new' object/class global in C# [duplicate]

What is a Singleton and when should I use it?
A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. The singleton premise is a pattern across software development.
There is a C# implementation "Implementing the Singleton Pattern in C#" covering most of what you need to know - including some good advice regarding thread safety.
To be honest, It's very rare that you need to implement a singleton - in my opinion it should be one of those things you should be aware of, even if it's not used too often.
You asked for C#. Trivial example:
public class Singleton
{
private Singleton()
{
// Prevent outside instantiation
}
private static readonly Singleton _singleton = new Singleton();
public static Singleton GetSingleton()
{
return _singleton;
}
}
What it is: A class for which there is just one, persistent instance across the lifetime of an application. See Singleton Pattern.
When you should use it: As little as possible. Only when you are absolutely certain that you need it. I'm reluctant to say "never", but there is usually a better alternative, such as Dependency Injection or simply a static class.
another way to implement singleton in c#, i personally prefer this way because you can access the instance of the singeton class as a property instead of a method.
public class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
//instance methods
}
but well, as far as i know both ways are considered 'right' so it's just a thing of personal flavor.
using System;
using System.Collections.Generic;
class MainApp
{
static void Main()
{
LoadBalancer oldbalancer = null;
for (int i = 0; i < 15; i++)
{
LoadBalancer balancerNew = LoadBalancer.GetLoadBalancer();
if (oldbalancer == balancerNew && oldbalancer != null)
{
Console.WriteLine("{0} SameInstance {1}", oldbalancer.Server, balancerNew.Server);
}
oldbalancer = balancerNew;
}
Console.ReadKey();
}
}
class LoadBalancer
{
private static LoadBalancer _instance;
private List<string> _servers = new List<string>();
private Random _random = new Random();
private static object syncLock = new object();
private LoadBalancer()
{
_servers.Add("ServerI");
_servers.Add("ServerII");
_servers.Add("ServerIII");
_servers.Add("ServerIV");
_servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
{
_instance = new LoadBalancer();
}
}
}
return _instance;
}
public string Server
{
get
{
int r = _random.Next(_servers.Count);
return _servers[r].ToString();
}
}
}
I took code from dofactory.com, nothing so fancy but I find this far good than examples with Foo and Bar additionally book from Judith Bishop on C# 3.0 Design Patterns has example about active application in mac dock.
If you look at code we are actually building new objects on for loop, so that creates new object but reuses instance as a result of which the oldbalancer and newbalancer has same instance, How? its due to static keyword used on function GetLoadBalancer(), despite of having different server value which is random list, static on GetLoadBalancer() belongs to the type itself rather than to a specific object.
Additionally there is double check locking here
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
since from MSDN
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
so every-time mutual-exclusion lock is issued, even if it don't need to which is unnecessary so we have null check.
Hopefully it helps in clearing more.
And please comment if I my understanding is directing wrong ways.
A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.
Whilst the there can only ever be one instance of a singleton, it is not the same as a static class. A static class can only contain static methods and can never be instantiated, whereas the instance of a singleton may be used in the same way as any other object.
It's a design pattern and it's not specific to c#. More about it all over the internet and SO, like on this wikipedia article.
In software engineering, the singleton
pattern is a design pattern that is
used to restrict instantiation of a
class to one object. This is useful
when exactly one object is needed to
coordinate actions across the system.
The concept is sometimes generalized
to systems that operate more
efficiently when only one object
exists, or that restrict the
instantiation to a certain number of
objects (say, five). Some consider it
an anti-pattern, judging that it is
overused, introduces unnecessary
limitations in situations where a sole
instance of a class is not actually
required, and introduces global state
into an application.
You should use it if you want a class that can only be instanciated once.
I use it for lookup data. Load once from DB.
public sealed class APILookup
{
private static readonly APILookup _instance = new APILookup();
private Dictionary<string, int> _lookup;
private APILookup()
{
try
{
_lookup = Utility.GetLookup();
}
catch { }
}
static APILookup()
{
}
public static APILookup Instance
{
get
{
return _instance;
}
}
public Dictionary<string, int> GetLookup()
{
return _lookup;
}
}
What is a singleton :
It is a class which only allows one instance of itself to be created, and usually gives simple access to that instance.
When should you use :
It depends on the situation.
Note : please do not use on db connection, for a detailed answer please refer to the answer of #Chad Grant
Here is a simple example of a Singleton:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
You can also use Lazy<T> to create your Singleton.
See here for a more detailed example using Lazy<T>
Here's what singleton is: http://en.wikipedia.org/wiki/Singleton_pattern
I don't know C#, but it's actually the same thing in all languages, only implementation differs.
You should generally avoid singleton when it's possible, but in some situations it's very convenient.
Sorry for my English ;)
I know it's very late to answer the question but with Auto-Property you can do something like that:
public static Singleton Instance { get; } = new Singleton();
Where Singleton is you class and can be via, in this case the readonly property Instance.
Thread Safe Singleton without using locks and no lazy instantiation.
This implementation has a static constructor, so it executes only once per Application Domain.
public sealed class Singleton
{
static Singleton(){}
private Singleton(){}
public static Singleton Instance { get; } = new Singleton();
}
E.X You can use Singleton for global information that needs to be injected.
In my case, I was keeping the Logged user detail(username, permissions etc.) in Global Static Class. And when I tried to implement the Unit Test, there was no way I could inject dependency into Controller classes. Thus I have changed my Static Class to Singleton pattern.
public class SysManager
{
private static readonly SysManager_instance = new SysManager();
static SysManager() {}
private SysManager(){}
public static SysManager Instance
{
get {return _instance;}
}
}
http://csharpindepth.com/Articles/General/Singleton.aspx#cctor
Fourth version from Implementing the Singleton Pattern in C#
One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny!
public sealed class Singleton
{
public static readonly Singleton Instance = new Singleton();
static Singleton()
{
}
private Singleton()
{
}
}

Singleton design pattern with double-check lock

Consider you have the following code:
1. Why do we use double check lock, why single lock is not good enough, please provide detailed example.
2. What are the main drawbacks with this implementation? and how should I prove it?
Thanks.
public sealed class SomeSingleton5
{
private static SomeSingleton5 s_Instance = null;
private static object s_LockObj = new Object();
private SomeSingleton5() { }
public static SomeSingleton5 Instance
{
get
{
if (s_Instance == null)
{
lock (s_LockObj)
{
if (s_Instance == null)
{
s_Instance = new SomeSingleton5();
}
}
}
return s_Instance;
}
}
}
I think the best implementation of singleton class is provided by Jon Skeet.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
static Singleton() {}
private Singleton() {}
}
Singleton by Jon Skeet Clarification
Aquiring a lock is expensive. Without the first if(s_Instance == null) check, a lock would be aquired each time someone accesses the singleton. But a lock actually only needs to be there during instance creation. So the first if(s_Instance == null) prevents the unnecessary locking. The second if(s_Instance == null) needs to be there because initially two threads might have evaluated the first if(s_Instance == null) as true and the two threads would thereafter instanciate s_Instance after each other inside the lock.
I don't see any real drawbacks in your implementation but with the alternative (static constructor, see below) we have a solution that is simpler and involves less code. So it is more maintainable and less errorprone. Also it doesn't require locking at all. As mentioned earlier, locking is expensive.
you can improve it by using a static constructor:
public sealed class SomeSingleton5
{
// the compiler will generate a static constructor containing the following code
// and the CLR will call it (once) before SomeSingleton5 is first acccessed
private static SomeSingleton5 s_Instance = new SomeSingleton5();
private SomeSingleton5() { }
public static SomeSingleton5 Instance
{
get
{
return s_Instance;
}
}
}

C# ASP .NET MVC 3 singleton constructor called twice

I have a project consisting of three projects,
WCF service
Asp.net MVC 3 application
Class library.
The one in the class library is my singleton, which I have made like this;
public sealed class Singleton
{
public static Singleton Instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (Instance == null)
Instance = new Singleton();
return Instance;
}
}
}
The thing is, I put a Debug.WriteLinein the constructor, and it gets called twice.
What I am trying to do is use the singleton from the mvc 3 application and from the WCF service, but they make different instances. Why?
EDIT: I tried a treadsafe singleton earlier. It made no difference.
There's a couple of things that could be going on here.
The most likely is that your MVC application and your WCF service are running in different AppDomains. It will be impossible for the code to 'share' the same instance if this is the case.
An alternative and less likely cause, is that because your code is not thread safe multiple instances are created. If the Singleton constructor takes a long time to return then this could be the issue. Since your using MVC3, I'll assume .Net 4, in which case the Lazy class is your friend:
private static readonly Lazy<Singleton> _singleton = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return _singleton.Value; } }
I guess your implementation is not thread safe. check the article: Implementing Singleton in C#
here a thread-safe example: (there are many other ways to do this, more complex and safer, this is just a reference...)
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
I have no experience with WCF, but maybe you should implement a thread safe singleton, see: http://www.yoda.arachsys.com/csharp/singleton.html
If the WCF Service is running as a separate application, it will have it's own instance of the singleton as the two applications do not share memory.
Does the WCF Service run on a different IP Address/port number to the MVC application?
You can use the lazy pattern in .Net 4.0
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
Source: http://csharpindepth.com/Articles/General/Singleton.aspx
First, your exact code as posted is not working. It is not syntactically correct (the curly braces are not balanced), and there are two public Singleton.Instance members. I assume your original code was like that:
public sealed class Singleton
{
private static Singleton _instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (_instance == null)
Instance = new Singleton();
return _instance;
}
}
}
The problem is probably related to a multi-threading environment. That is, while one of threads is calling new Singleton(), another tried to get Singleton.Instance, which, in turn, called another new Singleton().
You should either use double-checked locking there:
public sealed class Singleton
{
private static Singleton _instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (_instance == null)
lock (typeof(Singleton))
if (_instance == null)
{
var instance = new Singleton();
_instance = instance;
}
return _instance;
}
}
}
or, much easier,
public sealed class Singleton
{
public static readonly Singleton _instance = new Singleton();
private Singleton()
{
}
}

Possible to use a singleton with a non-default constructor in C#?

This is a slight variance of this question: Possible to use a singleton with a non-default constructor in C#?
I have a class that takes parameters for it's constructor. I would like to make this singleton such that the parameters are taken upon initialising the singleton and thus would not need to be passed in each time the instance is retrieved.
My solution (which is not elegant) for this is to have a CreateInstance() static method that takes the parameters and constructs the singleton instance. I would then have another static method GetInstance() which would be parameterless to obtain the singleton instance. In code, I would then need to ensure the logic calls CreateInstance before any calls to GetInstance. However, I cannot enforce this at compile time. I can, however, check at runtime by throwing an exception in GetInstance if it is called before CreateInstance.
Is there anyway I can achieve this behaviour with compile time enforcement? Or at the very least, is there a better way of doing the same thing?
There is no way to do it at compile time, because that would be like asking the compiler "can you prove that code X is never executed before code Y is executed, in the presence of multiple threads?". It cannot be done.
As for the runtime behavior of your design, I think this is as good as it can ever be.
You can make it slightly better by exposing a Func<SingletonType> property in your singleton class. When someone asks for the singleton instance and the instance has not already been created, your class would call this "factory method" to construct the singleton. If the factory method is null, then you either throw an exception or (if applicable) construct using some default parameters.
What this does is essentially defer the construction of the singleton until it's actually needed for the first time, so it's some improvement. But the underlying principle is the same.
Update:
As LukeH points out, this is pretty much what Lazy<T> does (.NET 4 only). If possible, use that one instead of writing your own.
In a classic singleton, the real magic happens in static readonly which creates the instance as soon as it is used:
public class MySingleton
{
private static readonly _instance = new MySingleton();
private MySingleton() {}
public static MySingleton Instance
{
get
{
return _instance;
}
}
}
If you have parameters to pass to constructor, you have to implement locking yourself (note the double if sandwitching the lock):
public class MySingletonWithConstructor
{
private static _instance;
private static object _lock = new Object();
private MySingletonWithConstructor(string myArg)
{
// ... do whatever necessary
}
public static MySingletonWithConstructor Instance
{
get
{
if(_instance==null)
{
lock(_lock)
{
if(_instance==null) // double if to prevent race condition
{
_instance = new MySingletonWithConstructor("Something");
}
}
}
return _instance;
}
}
}
You could just have GetInstance() call the CreateInstance() method if the singleton object doesn't exist already.
I would do it similar to this. You may have to add locks or other things to ensure:
public class ClassA {
private static ClassA instance;
private int param;
private ClassA(int param) {
this.param = param;
}
public static ClassA getInstance() {
if (instance == null) {
throw new CustomException("Not yet initialised");
} else {
return instance;
}
}
public static void createInstance(int param) {
if (instance == null) {
instance = new ClassA(param);
}
}
}
In your GetInstance() method, why dont you just call CreateInstance if your value is null, then you have lazy initialisation..
Use CreateInstance() to be the loader of a Lazy<T> and have GetInstance return the Lazy.Value (you might want to create a static readonly field that is set to = thelazy.Value to ensure a single entry into CreateInstance())

Locking the Static object inside the static property in the HTTPModule

We have a custom DLL implemented IHttpModule to handle the httpApplication_EndRequest, what I want to know is
The DLL has a class (not a static class) which has a static property is used to create an instance for a static variables/object reference defined inside the class.
Now, should I need to lock inside static property before creating an instance for the static object/variable?
Eg:-
public class SPEnvironment : IEnvironment
{
private static SPEnvironment _instance;
private static object _syncRoot = new object();
private SPEnvironment()
{
try {
.....
}
finally {
......
}
}
public static SPEnvironment Instance
{
get
{
if (_instance == null)
{
lock (_syncRoot)
{
if (_instance == null)
{
_instance = new SPEnvironment();
}
}
}
return _instance;
}
}
}
I will calling this from an another class, like below
SPEnvironment.Instance;
Is it the right way? or the lock should be removed?
The double null check with a lock in the middle is a good, thread-safe way of instantiating a singleton. However, you could save yourself a lot of code by just saying
public class SPEnvironment : IEnvironment
{
public static SPEnvironment Instance = new SPEnvironment();
private SPEnvironment()
{
try {
.....
}
finally {
......
}
}
}
The difference between the two is that this code instantiates the singleton the first time an object of that type is created where your code instantiates the singleton the first time SPEnvironment.Instance is accessed. In almost all cases, those are the same thing; in most of the remaining cases, it doesn't matter; but it is a subtle distinction that is worth understanding for that very rare edge case.

Categories

Resources