[
Advertise | Submit Code | About us | Contact us | Link us
]
Go!
Membership Services
Login
Register

Home
C# General

General

C# Language

Design & Architecture

Algorithms

Database

Security

Active Directory

COM Interop

Remoting
C# Windows Forms

General

Combo and List boxes

Miscellaneous Controls

Button Controls

Edit Controls
Cutting Edge

ASP.NET 2.0

Visual Studio 2005

Windows Longhorn

SQL Server 2005
C# Multimedia and GDI+

General

DirectX

GDI+

Audio
Internet & Web

General

Images and multimedia

Database

Utilities

Security

ASP.NET Controls

Design and Architecture

Webservices
.NET

General

Design & Architecture

Algorithms

Database

Security

Active Directory

COM Interop

Remoting

ADO.NET

XML.NET

Tools

Enterprise

IDE
Visual Basic .NET

VB.NET General

VB.NET Controls
General Reading

.NET Books Review

Product Showcase

Book Chapters

Business Design & Strategy
Community

Discuss

Job Board

Discussion

CodeXchange
DeveloperLand

Advertise

Submit Code

About us

Contact us

Link us
Miscellaneous

Favorite Links

Downloads

Programming Sites

Top Stories
Regular Expressions

E-Mail

Date/Time
Home > C# General > Design & Architecture
Implementing the Singleton Pattern in C#
Posted by on Thursday, August 26, 2004 (EST)

A comparison of different singleton pattern implentations.

This article has been viewed: 7,915 times
Technology: Design & Architecture.

Contents

The singleton pattern 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 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 parameter could be problematic! (If the same instance should 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 various 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 performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should 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 would 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 could 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 could 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.

Top Go to Table of Contents

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 should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Top Go to Table of Contents

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 evidence. 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 should 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.

Top Go to Table of Contents

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:

 

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 method entirely. This makes the basic skeleton code absolutely tiny! Many 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.)

Top Go to Table of Contents

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 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.

Top Go to Table of Contents

Performance vs laziness

In many cases, you won't actually require full laziness - unless your class initialization does something particularly 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 should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class.

Top Go to Table of Contents

Conclusion

There are various 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 would 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.

Top Go to Table of Contents

About Jon Skeet

Click here if you want to know more about .

Other articles that may interest you

  • Write a Word Add-In – Part 0
  • Write a Word Add-In – Part I
  • Lengthy Operations on Single Thread in .NET Application
  • Learning Draughts
  • Exceptions and Performance
  • Average Rating :

    Discussion Forums
    Got a programming related question? Hopefully someone has the answer... Want to help out other developers? Visit our discussion forums.

    Comments: View: Order:

    why not static methods?
    By Andrei C on Tuesday, May 31, 2005 (EST)
    why do you need an instance of that class?... isn't it easier to use ONLY static methods?...

    Reply to Comment

    Singleton vs Class with static methods
    By J.Marc Piulachs on Friday, June 24, 2005 (EST)

    Well , using a Singleton approach would have the following benefits:

    1. You can control the number of instances. ie, it's not actually *Single*ton.
    2. You can sub-class a Singleton while it doesn't make sense to sub-class a class with only static methods.
    3. You can control the creation of the actual instance whereas a static approach wouldn't give that flexibility.

    Also , What if you want your singleton class to be initialized to some initial values ? With static method approach you are going to provide the arguments for each call?

    Reply to Comment

    Singleton vs Class with static methods
    By DeveloperLand Administrator on Friday, June 24, 2005 (EST)
    A Singleton will return you an object pointer or reference, that you can pass around.
    With static methods all you are doing is providing a namespace to encapsulate your functions. You don't actually have an object.
    So if you want objects, and you want polymorphism, then Singleton's your baby.

    Reply to Comment

    Singleton plymorph
    By Kolik Kolik on Monday, July 18, 2005 (EST)
    However, if one wants to use polymorphism, the class has not to be sealed, hasn't it. Thus I don't agree with the statement that Singleton class is to be sealed. Sealed singleton would have no sense.

    Reply to Comment

    It must be sealed
    By Jon Skeet on Wednesday, August 31, 2005 (EST)
    If a singleton isn't sealed and has a non-private constructor, it is no longer a singleton - it's possibly to construct more than one instance by creating more than one derived class instance. However, the sealed singleton class can still derive from another class, or implement an interface. For instance, you might have a singleton implementation of IComparer to make life easier. (I'm the original author of the article, by the way. See http://www.pobox.com/~skeet/csharp for similar articles.)

    Reply to Comment

    Add Your Comment

    Sponsored by:

    New Articles

  • Exceptions and Performance
    Almost every time exceptions are mentioned in mailing lists and newsgroups, people say they're really expensive.Let's examine that claim, shall we?

  • Creating multilingual websites - Part 1
    Extend the existing globalization capabilities of .NET to create flexible and powerful multilingual web sites. First, create a custom ResourceManager, and then create custom localized-capable server controls to easily deploy multilingual functionality.

  • Parameter passing in C#
    Many people have become fairly confused about how parameters are passed in C#, particularly with regard to reference types. This page should help to clear up some of that confusion

  • Most Popular Articles

  • LDAP, IIS and WinNT Directory Services
    This article explains how to use .NET Directory Services to retrieve and search directory objects, create new directory objects and edit or delete existing directory objects. Describes Active Directory Application Mode (ADAM) and how to use the IIS, WinNT and LDAP directory (ADSI) provider.

  • An in-depth look at WMI and instrumentation, Part II
    WMI stands for Windows Management Instrumentation and, as the name indicates, is about managing your IT infrastructure this article is the second part of a two-part series.

  • An in-depth look at WMI and instrumentation, Part I
    WMI stands for Windows Management Instrumentation and, as the name indicates, is about managing your IT infrastructure this article provides an in-depth look at WMI and MOM 2005

  • New Books

  • Murach's ASP.NET 2.0 Upgrader's Guide: VB Edition
    What’s new and how to use it! That’s what this book delivers if you’re a VB developer who’s interested in upgrading from ASP.NET 1.x to ASP.NET 2.0.

  • C# in easy steps
    Learn to program with Microsoft’s premier programming language. No previous programming knowledge is assumed. With numerous easy-to-follow examples, this title explains the essentials of object-oriented programming with C#.

  • Murach's ASP.NET web programming with VB.NET
    Murach's ASP.NET web programming with VB.NET by Doug Lowe and Anne Prince is a in depth training and reference book for ASP.NET programming using VB.NET. The book builds upon Murach's previous books and covers more advanced concepts for programming ASP.NET pages.

  • Got Code?

    if you have any article , source code , or anything else you'd like to share with this community that you think others might find useful, please submit it here and we will gladly make it available on this site. submit@developerland.com.
    Partners

    All articles are copyrighted by their individual authors unless otherwise specified , everything else Copyright ©2004-2006 DeveloperLand