Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7525117
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T03:27:00+00:00 2026-05-30T03:27:00+00:00

Isn’t this a simpler as well as safe (and hence better) way to implement

  • 0

Isn’t this a simpler as well as safe (and hence better) way to implement a singleton instead of doing double-checked locking mambo-jambo? Any drawbacks of this approach?


public class Singleton
{
    private static Singleton _instance;
    private Singleton() { Console.WriteLine("Instance created"); }

    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                Interlocked.CompareExchange(ref _instance, new Singleton(), null);
            }
            return _instance;
        }
    }
    public void DoStuff() { }
}

EDIT: the test for thread-safety failed, can anyone explain why? How come Interlocked.CompareExchange isn’t truly atomic?


public class Program
{
   static void Main(string[] args)
   {
      Parallel.For(0, 1000000, delegate(int i) { Singleton.Instance.DoStuff(); });
   }
} 

Result (4 cores, 4 logical processors)
Instance created
Instance created
Instance created
Instance created
Instance created
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T03:27:02+00:00Added an answer on May 30, 2026 at 3:27 am

    You may well be creating multiple instances, but these will get garbage collected because they are not used anywhere. In no case does the static _instance field variable change its value more than once, the single time that it goes from null to a valid value. Hence consumers of this code will only ever see the same instance, despite the fact that multiple instances have been created.

    Lock free programming

    Joe Duffy, in his book entitled Concurrent Programming on Windows actually analyses this very pattern that you are trying to use on chapter 10, Memory models and Lock Freedom, page 526.

    He refers to this pattern as a Lazy initialization of a relaxed reference:

    public class LazyInitRelaxedRef<T> where T : class
    {
        private volatile T m_value;
        private Func<T> m_factory;
    
        public LazyInitRelaxedRef(Func<T> factory) { m_factory = factory; }
    
    
        public T Value
        {
            get
            {
                if (m_value == null) 
                  Interlocked.CompareExchange(ref m_value, m_factory(), null);
                return m_value;
            }
        }
    
        /// <summary>
        /// An alternative version of the above Value accessor that disposes
        /// of garbage if it loses the race to publish a new value.  (Page 527.)
        /// </summary>
        public T ValueWithDisposalOfGarbage
        {
            get
            {
                if (m_value == null)
                {
                    T obj = m_factory();
                    if (Interlocked.CompareExchange(ref m_value, obj, null) != null && obj is IDisposable)
                        ((IDisposable)obj).Dispose();
                }
                return m_value;
            }
        }
    }
    

    As we can see, in the above sample methods are lock free at the price of creating throw-away objects. In any case the Value property will not change for consumers of such an API.

    Balancing Trade-offs

    Lock Freedom comes at a price and is a matter of choosing your trade-offs carefully. In this case the price of lock freedom is that you have to create instances of objects that you are not going to use. This may be an acceptable price to pay since you know that by being lock free, there is a lower risk of deadlocks and also thread contention.

    In this particular instance however, the semantics of a singleton are in essence to Create a single instance of an object, so I would much rather opt for Lazy<T> as @Centro has quoted in his answer.

    Nevertheless, it still begs the question, when should we use Interlocked.CompareExchange? I liked your example, it is quite thought provoking and many people are very quick to diss it as wrong when it is not horribly wrong as @Blindy quotes.

    It all boils down to whether you have calculated the tradeoffs and decided:

    • How important is it that you produce one and only one instance?
    • How important is it to be lock free?

    As long as you are aware of the trade-offs and make it a conscious decision to create new objects for the benefit of being lock free, then your example could also be an acceptable answer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Isn't there a better way to accomplish this?: (RegionID is a Flex ComboBox) RegionID.selectedItem=value.Region;
This isn't a holy war, this isn't a question of which is better. What
This isn't exactly a singleton, but it's close, so I imagine it's common. I
Isn't there a better looking statement (or way) to keep the console from disappearing
This isn't working the way I expect it to. Sample input will include an
Isn't there a way with Hibernate to return a list of (primitive) values from
Isn't there a CSS way of having the page to get a border around
Isn't visual studio supposed to automatically generate this file for each webservice creation ?
This isn't legal: public class MyBaseClass { public MyBaseClass() {} public MyBaseClass(object arg) {}
Isn't there some way to re-write the following code, such that I don't need

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.