none
Is this a thread-safe singleton pattern? RRS feed

  • Question

  • I am told that the following can be used as a simplified thread-safe Singleton, but am not sure why it is thread-safe. Does anyone know if it is, in fact, thread-safe and, if so, why? I am also wondering how the constructor is being called.

     

    public sealed class Singleton

    {

        public static Singleton Instance { get; private set; }

        static Singleton() { Instance = new Singleton(); }

    }

     

    Tuesday, May 4, 2010 6:23 PM

Answers

  • This is basically a variation on the 4th singleton option presented by Jon Skeet here.

     

    This is a thread-safe option for creating a simple Singleton.  Just be aware that it's not necessarily fully lazy (any access of the type in the AppDomain will cause the "instance" to be created).  Also, in order to be a true singleton, you should add a private constructor (which prevents you from creating a second instance):

     

    public sealed class Singleton
    {
      public static Singleton Instance { get; private set; }
      static Singleton() { Instance = new Singleton(); }
    
      // This prevents you from doing new Singleton() outside of the class
      private Singleton() {}
    }

    That being said, the basic premise will work.  It is threadsafe because the C# language specification requires that the static constructor be run only one time in the AppDomain, sometime prior to the first access of the type.  This will cause the Instance to generated and set a single time prior to the first access (by any thread).  For details, see section 10.12 (Static Constructors) in the C# language specification, which states:

     

    "The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

    ·         An instance of the class type is created.

    Any of the static members of the class type are referenced"

     



    Reed Copsey, Jr. - http://reedcopsey.com
    • Marked as answer by Bill2010 Tuesday, May 4, 2010 8:19 PM
    Tuesday, May 4, 2010 7:44 PM
    Moderator

All replies

  • Tuesday, May 4, 2010 6:27 PM
  • better you read: http://msdn.microsoft.com/en-us/library/ff650316.aspx
    NOUS INFOSYSTEMS
    This link didn't address my question. If the example I provided provides the same type of thread-safety as, for example, Double-Check Locking, then it strikes me as simpler and more eloquent.
    Tuesday, May 4, 2010 7:09 PM
  • I see your code creating only one static variable of type Singleton.  All threads would reference that same variable.  You have a static constructor and a static variable. Static objects are generally thread-safe.

    What type of safety are you looking for?  Did you want each thread to have its' own instance to work with?  Thread safe from other threads?

    Or did you want to make sure that each thread does not collide with others when they each reference a single common object?


    Mark the best replies as answers. "Fooling computers since 1971."
    Tuesday, May 4, 2010 7:18 PM
    Moderator
  • What type of safety are you looking for?  Did you want each thread to have its' own instance to work with?  Thread safe from other threads?

    Or did you want to make sure that each thread does not collide with others when they each reference a single common object?


    Mark the best replies as answers. "Fooling computers since 1971."

    What would be the point of creating a separate singleton instance in multiple threads? Would it still be a singleton?

    Most of the examples for creating a thread-safe singleton deal with the potential for inadvertently creating multiple instances, which I believe you are asking in your last question... correct? I am also not sure about your second question. It sounds like you are making a reference to using the lock(object) keyword. Is that what you meant?

    • Edited by Bill2010 Tuesday, May 4, 2010 7:47 PM
    Tuesday, May 4, 2010 7:32 PM
  • Yes, that is sort of what I meant. 

    I have sometimes found it useful for threads to create their own instance of a Singleton for their own exclusive use.  But, I see no reason to go into details over what exactly I meant.  The real question is what type of thread safety performance are you looking for it to achieve.

    I already pointed out that your original sample is nothing more than a static variable.  It is not a true Singleton.  Can you see the subtle differences between your code and that at the link provided by anishmarokey .


    Mark the best replies as answers. "Fooling computers since 1971."
    Tuesday, May 4, 2010 7:41 PM
    Moderator
  • This is basically a variation on the 4th singleton option presented by Jon Skeet here.

     

    This is a thread-safe option for creating a simple Singleton.  Just be aware that it's not necessarily fully lazy (any access of the type in the AppDomain will cause the "instance" to be created).  Also, in order to be a true singleton, you should add a private constructor (which prevents you from creating a second instance):

     

    public sealed class Singleton
    {
      public static Singleton Instance { get; private set; }
      static Singleton() { Instance = new Singleton(); }
    
      // This prevents you from doing new Singleton() outside of the class
      private Singleton() {}
    }

    That being said, the basic premise will work.  It is threadsafe because the C# language specification requires that the static constructor be run only one time in the AppDomain, sometime prior to the first access of the type.  This will cause the Instance to generated and set a single time prior to the first access (by any thread).  For details, see section 10.12 (Static Constructors) in the C# language specification, which states:

     

    "The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

    ·         An instance of the class type is created.

    Any of the static members of the class type are referenced"

     



    Reed Copsey, Jr. - http://reedcopsey.com
    • Marked as answer by Bill2010 Tuesday, May 4, 2010 8:19 PM
    Tuesday, May 4, 2010 7:44 PM
    Moderator
  • This is basically a variation on the 4th singleton option presented by Jon Skeet here.

     

    You're right. I see the resemblance, especially after adding "private Singleton() {}" to prevent newing from outside the class.

    The example I gave actually appears to be a variation on his recommendation for using a shortcut to make the code skeleton absolutely minimal by dropping the property and making the instance variable "public static readonly". By using automatic properties instead, it is still possible to have a minimal (and easy to remember) skeleton and STILL use properties.

     

    Tuesday, May 4, 2010 9:32 PM