Implementing the Singleton pattern in C #

Source: Internet
Author: User
Tags constructor expression reference require thread
Implementing the Singleton pattern in C #
View Auther ' s website

The Singleton is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to being created, and usually gives simple Access to that instance. Most commonly, singletons don ' t allow any parameters to is specified when creating the Instance-as otherwise a second re Quest for a instance but with a different parameter could is problematic! (If the same instance should are accessed for all requests with the same parameter, the factory pattern are more appropriate .) This article deals is with the situation where no parameters are required. Typically a requirement of singletons is this they are created. That's lazily-i.e instance ' t isn created it is f Irst needed.

There are various different ways of implementing the Singleton in C #. I shall present them reverse order of elegance, starting with the most commonly, seen are not which, a D working up to a fully lazily-loaded, Thread-safe, simple and highly performant version. Note This in the code here, I omit the private modifier, as it's the default for class members. In many other languages such as Java, there are a different default, and private should be used.

All of these implementations share four common characteristics, however:

A single constructor, which is private and parameterless. This prevents is classes from instantiating it (which would is a violation of the pattern). Note This it also prevents subclassing-if a singleton can be subclassed once, it can is subclassed twice, and if each of Those subclasses can create an instance, which is violated. The factory pattern can is used if you need a single instance of a base type, but the exact type isn ' t known until .
The class is sealed. This is unnecessary, strictly speaking, due to the above point, and but may help the JIT to optimise things.
A static variable which holds a reference to the "single" created instance, if any.
A public static means of the getting the reference to the single created instance, creating one if necessary.
This all of those implementations also use a public static method getinstance as the means of accessing the instance. In all cases, the method could easily is converted to a property with a accessor, with no impact on thread-safety O R performance.

Version-not Thread-safe
public sealed class Singleton
{
Static Singleton Instance=null;
Singleton ()
{
}
public static Singleton getinstance ()
{
if (instance==null)
Instance = new Singleton ();
return instance;
}
}


As hinted at before, the above are not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to is true, then both create INS Tances, which violates the singleton pattern. Note this in fact the instance could already have been created before the expression is evaluated, but the memory model does N ' t guarantee that the new value of instance'll be seen by threads unless suitable memory barriers have been passe D.

Second Version-simple thread-safety
public sealed class Singleton
{
Static Singleton Instance=null;
Static ReadOnly Object padlock = new Object ();
Singleton ()
{
}
public static Singleton getinstance ()
{
Lock (Padlock)
{
if (instance==null)
Instance = new Singleton ();
return instance;
}
}
}


This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has the been created before Ng the instance. This takes care of the memory barrier issue (as locking makes sure then all reads occur after the lock logically and unlocking makes sure that all writes occur logically before the lock release) and ensures this only one thread would CR Eate an instance (as only one thread can is in, part of the code at a time-by the time the second thread enters it,t He-I thread would have created the instance, so the expression would evaluate to false. Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note So instead of locking on typeof (Singleton) as some versions of this implementation does, I lock on the value of a STA TIC variable which is private to the class. Locking on objects which, classes can access and lock on (such as the type) risks performance and issues even Ks. This is a general style preference of mine-wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to is locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should is private to the class they are, used in. This is helps to make writing thread-safe applications significantly easier.

Third version-attempted thread-safety using double-check locking
public sealed class Singleton
{
Static Singleton Instance=null;
Static ReadOnly Object padlock = new Object ();
Singleton ()
{
}
public static Singleton getinstance ()
{
if (instance==null)
{
Lock (Padlock)
{
if (instance==null)
Instance = new Singleton ();
}
}
return instance;
}
}


This implementation attempts to is thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

It doesn ' t work in Java. This may seem a odd thing to comment on, but it's worth knowing if you ever need the Singleton is in Java, and C # PR Ogrammers may, also be Java programmers. The Java memory model doesn ' t ensure that's constructor completes before the reference to the new object are assigned to Instance. The Java memory model is going through a reworking for version 1.5, but double-check locking are anticipated to still do BR Oken after this.
It almost certainly doesn ' t work in. NET either. Claims have been made that it does, but without the any convincing evidence. Various people who are rather trustworthy, however, such as Chris Brumme, have given convincing reasons-why it doesn ' T. Given the other disadvantages, why take the risk? I believe it can be fixed by making the instance variable volatile, and but that slows of the pattern. (Of course, correct but slow is better than incorrect but broken, but when speed were one of the reasons for using this pat Tern in the, it looks even less attractive.) It can also be fixed using explicit memory barriers but experts the to find it seem to agree just which memory RS are required. I don ' t know about you, but when experts disagree about whether or not something should, I try to work it avoid.
It ' s easy to get wrong. The pattern needs to is pretty much exactly as above-any significant changes are-likely to impact either performance or Correctness.
It still doesn ' t perform as as as the later implementations.

Fourth Version-not quite as lazy, but thread-safe without using locks
public sealed class Singleton
{
static readonly Singleton instance=new Singleton ();
Explicit Static constructor to tell C # compiler
Not to mark type as BeforeFieldInit
Static Singleton ()
{
}
Singleton ()
{
}
public static Singleton getinstance ()
{
return instance;
}
}


As you can the, this is really is extremely simple-but why are it thread-safe and how lazy is it? So, static constructors in C # are specified to execute ' when ' an instance the ' class is created or a static is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it would be faster t Han adding extra checking as in the previous examples. There are a couple of wrinkles, however:

It ' s not as lazy as the other implementations. In particular, if you are have static members of the other than getinstance, the the ' a ' reference to those members would involve Creati Ng the instance. This is corrected in the next implementation.
There are complications if one static constructor invokes another which invokes. Look at the. NET Specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type Initializers-they ' re unlikely to bite for you, but it ' s worth being aware of the consequences of static constructors which R Efer to each of the other in a cycle.
The laziness of type initializers is only guaranteed by. NET when the type isn ' t marked with a special flag called Ieldinit. Unfortunately, the C # compiler (as provided in the. NET 1.1 runtime, at least) marks all types which don ' t have a static C Onstructor (i.e. a block which looks like a constructor but is marked static) as BeforeFieldInit. I now have a discussion page with more details about this issue. Also Note which it affects performance, as discussed near the bottom of this article.

One shortcut can take with this implementation (and only this one) are to just make instance a public static readonly V Ariable, and get rids of the method entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a (case further) action is needed in future, and JIT inlining be likely to Ma Ke the performance identical. (Note that the static constructor itself are still required if you require laziness.)

Fifth version-fully Lazy instantiation
public sealed class Singleton
{
Singleton ()
{
}
public static Singleton getinstance ()
{
return nested.instance;
}
Class Nested
{
Explicit Static constructor to tell C # compiler
Not to mark type as BeforeFieldInit
Static Nested ()
{
}
Internal static readonly Singleton instance = new Singleton ();
}
}


Here, instantiation are triggered by the "the" the "the" the "reference", the nested class, which only occurs Instance. This means the implementation are fully lazy, but has all the performance benefits of the previous. Note This although nested classes have access to the enclosing class ' s private members, the reverse isn't true, hence the Need for instance to is internal here. That doesn ' t raise any other problems, though, as the class itself is private. The code is a bit more complicated the instantiation lazy, however.

Performance vs laziness
In many cases, your won ' t actually require full laziness-unless your class initialization does something particularly Tim E-consuming, or has some side-effect elsewhere, it ' probably fine to leave out the explicit static constructor shown E. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a meth OD) To ensure this type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a significant performance Differenc E. should decide whether or not fully lazy instantiation are required, and document this decision appropriately The class. Conclusion
There are various different ways of implementing the Singleton in C #. The final two are generally best, as they are thread-safe, simple, and perform. I would personally use the fourth implementation unless I had some other static members which really shouldn ' t trigger INS Tantiation, simply because it's simplest implementation, which means I ' m more likely to get it right. The laziness of initialization can is chosen depending on the semantics of the class itself.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.