5 Implementations of Singleton Pattern




This article introduces singleton design pattern and its 5 implementation variations (with C#).

Problem
At most one instance of a class must be created in an application.
Solution
That class (singleton) is defined including its own instance, and the constructor must be private.
Implementations
1. Lazy initialization, non-thread safe: This is the classical version, bot it's not thread safe. If more than one thread attempts to access instance at the same time, more than one instance may be created.
public class Singleton {
    private static Singleton instance = null;
    public static Singleton Instance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
    private Singleton() {}
}

2. Non-lazy initialization, thread safe: This is the simplest thread safe version, but it does not support lazy initialization.
public class Singleton {
    private readonly static Singleton instance = new Singleton();
    public static Singleton Instance() {
        return instance;
    }
    private Singleton() {}
}

3. Lazy initialization, thread safe: This version supports both properties, but has  performance problems. Once a thread uses singleton instance, the others have to wait because of lock.
public class Singleton {
    private static Singleton instance = null;
    private static readonly object lockObj = new object();
    public static Singleton Instance() {
        lock (lockObj) {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
    private Singleton() {}
}

4. Double-check locking: An improved version of the third solution. Two null controls prevent lock waits for most time, but not always. Also, it does not work properly for Java because of Java memory management approach.
public class Singleton {
    private static Singleton instance = null;
    private static object lockObj = new object();
    public static Singleton Instance() {
        if (instance == null) {
            lock (lockObj) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
    private Singleton() {}
}

5. Nested initialization: A nested class is used for lazy initialization. This version is also thread safe, but a bit complex. For most situations, solutions 2 or 4 will be suitable according to performance parameters.
public class Singleton {
    public static Singleton Instance() {
         return Nested.instance;
    }
    private Singleton() {}

    class Nested {
        static Nested() {}
        internal static readonly Singleton instance = new Singleton()
    }
}

Usage: 
public static void Main(string[] args)
{
    Singleton instance = Singleton.Instance();
}


This entry was posted in ,. Bookmark the permalink.

17 Responses to 5 Implementations of Singleton Pattern

  1. Anonymous says:

    FYI, this is the actual preferred way to do:
    http://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java/71399#71399

  2. Anonymous says:

    Can you talk about what benefit or harm each implementation does compared to one or other? Thanks

  3. CB says:

    @1: Actually, it's all about the "lazy initalization" and "thread safe" choices. If singleton object(s) is/are costly (for memory and/or processor), lazy initialization is preferred. And if there are threads which work simultaneously on the instance, thread safe creation is required.

    @2: Given link contains implementations 2 & 5 with exception throwing protection for threading problems. Thanks for sharing.

  4. Anonymous says:

    re: http://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java/71399#71399

    I think Josh Bloch's enum based Singleton covers only non-lazy initialization and he also points out cases where this approach will not work, e.g. per-thread Singletons

  5. Rajan says:

    You have missed one most important yet powerful approach of singleton, the enum type.

    Public enum Foo {
    INSTANCE;
    }

    ref: Effective Java, Joshua Bloch. (Item: ...).

  6. wekempf says:

    2. This version is lazy by some definition of lazy. That static construction won't be called until the first time the class is used. Given the very minimal definition of your Singleton, this version is as lazy as any of your other examples. Yes, there's corner cases where (5) is required, but those corner cases are neither illustrated nor explained.

    3. You should declare the instance field volatile or the DCL pattern is broken.

  7. CB says:

    Thanks for examples, viewpoints and suggestions. They will be considered in future posts.

  8. Anonymous says:

    If you are using Spring... that is your answer.

  9. Anonymous says:

    nice article. just for information, i translated your post into russian. ;)
    http://csharpdeveloper.ru/2010/09/21/5-implementations-of-singleton-pattern/

  10. CB says:

    Thanks for translating and referencing our page.

  11. Anonymous says:

    I don't see anywhere to instantiate Singleton class in No.5. How does it suppose to work?

  12. CB says:

    Fixed. Thank you for notification.

  13. Anonymous says:

    Why no reference to this canonical article written in 2006 on Singletons in C#?
    http://csharpindepth.com/Articles/General/Singleton.aspx

    --jeroen

  14. CB says:

    Although there are quite similarities with that article, it wasn't used while writing "5 Implementations of Singleton Pattern".

  15. Robert says:

    In .net 4 you can use the new Lazy type like explained in this blog post.

    http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx

    Robert

  16. Nice post , just to add
    While writing Singleton class we need to consider many points e.g.
    1) Serialization
    2) Many ClassLoaders
    3) Cloning

    to tackle all above problem best way is to use JAVA 5 Enum functionality and write Singleton using Enum like below.
    public enum Singleton {
    INSTANCE;

    public static void hi(){
    System.out.println("Hi");
    }
    }

    Thanks
    Javin
    Why String is immutable in Java

  17. pranav says:

    Very nice explanation and examples.
    I liked the double check locking example.

Leave a Reply