Implementing the Singleton pattern in C # [reprint]

Source: Internet
Author: User
View auther's website

The Singleton pattern is one of the best-known patterns in software engineering. essential, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. most commonly, Singletons don't allow any parameters to be specified when creating the instance-as otherwise a second request for an instance but with a different paramete R cocould be problematic! (If the same instance shocould be accessed for all requests with the same parameter, the factory pattern is more appropriate .) this article deals only with the situation where no parameters are required. typically a requirement of singletons is that they are created lazily-I. e. that the instance isn' t created until it is first needed.

There are varous different ways of implementing the Singleton pattern in C #. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly versions t version. note that in the code here, I omit the private modifier, as it is the default for class members. in our other versions ages such as Java, there is a different default, and private shoshould be used.

All these implementations share four common characteristics, however:

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

First 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 is not thread-safe. two different threads cocould both have evaluated the test if (instance = NULL) and found it to be true, then both create instances, which violates the Singleton pattern. note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

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 been created before creating the instance. this takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time-by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false ). unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof (Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. locking on objects which other classes can access and lock on (such as the type) Risks performance issues and even deadlocks. 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 be locked on for specific purposes (e.g. for waiting/pulsing a queue ). usually such objects shocould be private to the class they are used in. this 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 be 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 an odd thing to comment on, but it's worth knowing if you ever need the Singleton pattern in Java, and C # programmers may well also be Java programmers. the Java Memory Model doesn' t ensure that the constructor completes before the reference to the new object is assigned to instance. the Java memory model is going through a reworking for version 1.5, but double-check locking is anticipated to still be broken after this.
It almost certainly doesn' t work in. net either. claims have been made that it does, but without any convincing evicing. various people who are rather more 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, but that slows the pattern down more. (Of course, correct but slow is better than incorrect but broken, but when speed was one of the reasons for using this pattern in the first place, it looks even less attractive .) it can also be fixed using explicit memory barriers, but experts seem to find it hard to agree on just which memory barriers are required. I don't know about you, but when experts disagree about whether or not something shoshould work, I try to avoid it entirely.
It's easy to get wrong. The pattern needs to be pretty much exactly as above-any significant changes are likely to impact either performance or correctness.
It still doesn' t perform as well 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 see, this is really is extremely simple-but why is it thread-safe and how lazy is it? Well, static constructors in C # are specified to execute only when an instance of the class is created or a static member 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 will be faster than 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 particle, if you have static members other than getinstance, the first reference to those Members will involve creating the instance. this is corrected in the next implementation.
There are complications if one static constructor invokes another which invokes the first again. look in. 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 you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
The laziness of Type initializers is only guaranteed. net when the type isn' t marked with a special flag called beforefieldinit. unfortunately, the C # Compiler (as provided in. NET 1.1 runtime, at least) marks all types which don't have a static Constructor (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 that it affects performance, as discussed near the bottom of this article.

One could cut 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 method entirely. this makes the basic skeleton code absolutely tiny! Registrant people, however, prefer to have a method in case further action is needed in future, and JIT inlining is likely to make the performance identical. (note that the static constructor itself is still required if you require laziness .)

Th 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 is triggered by the first reference to the static member of the nested class, which only occurs in getinstance. this means the implementation is fully lazy, but has all the performance benefits of the previous ones. note that although Nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. that doesn't raise any other problems, though, as the class itself is private. the Code is a bit more complicated in order to make the instantiation lazy, however.

Performance vs laziness
In actual cases, you won't actually require full laziness-unless your class initialization does something particle ly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. this can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a Method) to ensure that the 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 difference. you shoshould decide whether or not fully lazy instantiation is required, and document this demo-appropriately within the class. conclusion
There are varous different ways of implementing the Singleton pattern in C #. the final two are generally best, as they are thread-safe, simple, and perform well. I wocould personally use the fourth implementation unless I had some other static members which really shouldn't trigger instantiation, simply because it's the simplest implementation, which means I'm more likely to get it right. the laziness of initialization can be chosen depending on the semantics of the class itself.

 

Related Article

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.