Is there any issue with creating singleton following way in .Net ? [duplicate] - c#

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

If your singleton is ever in danger of initializing itself multiple times, you have a lot worse problems. Why not just use:
public class Singleton
{
private static Singleton instance=new Singleton();
private Singleton() {}
public static Singleton Instance{get{return instance;}}
}
Absolutely thread-safe in regards to initialization.
Edit: in case I wasn't clear, your code is horribly wrong. Both the if check and the new are not thread-safe! You need to use a proper singleton class.

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.

In order not to use 'double-checked locking mambo-jambo' or simply not to implement an own singleton reinventing the wheel, use a ready solution included into .NET 4.0 - Lazy<T>.

public class Singleton
{
private static Singleton _instance = new Singleton();
private Singleton() {}
public static Singleton Instance
{
get
{
return _instance;
}
}
}

I am not convinced you can completely trust that. Yes, Interlocked.CompareExchanger is atomic, but new Singleton() is in not going to be atomic in any non-trivial case. Since it would have to evaluated before exchanging values, this would not be a thread-safe implementation in general.

what about this?
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
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();
}
}
It's the fifth version on this page:
http://www.yoda.arachsys.com/csharp/singleton.html
I'm not sure, but the author seems to think its both thread-safe and lazy loading.

Your singleton initializer is behaving exactly as it should. See Raymond Chen's Lock-free algorithms: The singleton constructor:
This is a double-check lock, but without the locking. Instead of taking lock when doing the initial construction, we just let it be a free-for-all over who gets to create the object. If five threads all reach this code at the same time, sure, let's create five objects. After everybody creates what they think is the winning object, they called Interlocked­Compare­Exchange­Pointer­Release to attempt to update the global pointer.
This technique is suitable when it's okay to let multiple threads try to create the singleton (and have all the losers destroy their copy). If creating the singleton is expensive or has unwanted side-effects, then you don't want to use the free-for-all algorithm.
Each thread creates the object; as it thinks nobody has created it yet. But then during the InterlockedCompareExchange, only one thread will really be able to set the global singleton.
Bonus reading
One-Time Initialization helper functions save you from having to write all this code yourself. They deal with all the synchronization and memory barrier issues, and support both the one-person-gets-to-initialize and the free-for-all-initialization models.
A lazy initialization primitive for .NET provides a C# version of the same.

This is not thread-safe.
You would need a lock to hold the if() and the Interlocked.CompareExchange() together, and then you wouldn't need the CompareExchange anymore.

You still have the issue that you're quite possibly creating and throwing away instances of your singleton. When you execute Interlocked.CompareExchange(), the Singleton constructor will always be executed, regardless of whether the assignment will succeed. So you're no better off (or worse off, IMHO) than if you said:
if ( _instance == null )
{
lock(latch)
{
_instance = new Singleton() ;
}
}
Better performance vis-a-vis thread contention than if you swapped the position of the lock and the test for null, but at the risk of an extra instance being constructed.

An obvious singleton implementation for .NET?

Auto-Property initialization (C# 6.0) does not seem to cause the multiple instantiations of Singleton you are seeing.
public class Singleton
{
static public Singleton Instance { get; } = new Singleton();
private Singleton();
}

I think the simplest way after .NET 4.0 is using System.Lazy<T>:
public class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton() { }
}
Jon Skeet has a nice article here that covers a lot of ways of implementing singleton and the problems of each one.

Don't use locking. Use your language environment
Mostly simple Thread-safe implementation is:
public class Singleton
{
private static readonly Singleton _instance;
private Singleton() { }
static Singleton()
{
_instance = new Singleton();
}
public static Singleton Instance
{
get { return _instance; }
}
}

Related

Do two instances of a singleton class have the same property value?

I am new to design patterns in C#. Can anyone please give me some instructions about the implementation of a Singleton class. I just implemented a tutorial but I am not able to understand use of singleton class with this "singleton means we can create only one instance of a class". Then why we don't access property which is written in the singleton class using two different instance of the class.
Please look at my code and give me instructions about the mistake I made.
static void Main(string[] args)
{
Singleton instance = Singleton.getInstance();
instance.Message = "Text Message";
Singleton instance1 = Singleton.getInstance();
Console.WriteLine(instance.Message);
Console.WriteLine(instance1.Message);
Console.ReadKey();
}
class Singleton
{
private static Singleton singleton=null;
private Singleton(){}
public static Singleton getInstance()
{
if (singleton!=null)
{
return singleton;
}
return new Singleton();
}
public string Message{get; set;}
}
Your singleton is incorrect.
More correct version:
class Singleton
{
private static Singleton singleton = null;
private Singleton(){}
public static Singleton getInstance()
{
if (singleton!=null)
{
return singleton;
}
return (singleton = new Singleton()); //here is
}
public string Message{get; set;}
}
And very good solution:
class Singleton
{
private static Lazy<Singleton> singleton = new Lazy<Singleton>(()=> new Singleton());
private Singleton() { }
public static Singleton getInstance()
{
return singleton.Value;
}
public string Message { get; set; }
}
It has no problems with thread-safity and lazy initialization.
By default, all public and protected members of the Lazy class are
thread safe and may be used concurrently from multiple threads. These
thread-safety guarantees may be removed optionally and per instance,
using parameters to the type's constructors.
Your Singleton implementation is incorrect.
A Singleton is designed to only allow none or a single instance at all times.
This is where you went wrong:
public static Singleton getInstance()
{
// "singleton" will always be null.
if (singleton != null)
{
return singleton;
}
// Always returns new instance rather than existing one.
return new Singleton();
}
To fix it you should write:
public static Singleton getInstance()
{
// Return the instance we might have stored earlier.
if (singleton != null)
return singleton;
// Now we store the only instance that will ever be created.
singleton = new Singleton();
return singleton;
}
Note that this is not thread safe if called multiple times in parallel.
As a resource I can recommend Jon Skeet's post:
http://csharpindepth.com/Articles/General/Singleton.aspx
He explaines six different solutions (including thread-safety and the Lazy(T)) to the Singleton Pattern and how to code them.
Does two instance of singleton class has a same property value?
The answer to your question is yes, they has the same property value.
Important thing is understand why, and the reason is the core of what a singleton is. So, why?:
Because you are confusing two references with two instance.
There are no two instances, there are always one none or one instance of the singleton class.
In your code, singleton variable and singleton1 variable are pointing both to the same object, the singleton, and the reason is because of the implementation of the method getInstance(), is simple to understand :
If method is called for the very first time, then it creates for unique time the singleton object with method new.
If method is called after a first time, it will return the singleton object created in the first call of method.
So, no matter how many variables of type Singleton you have, you will always have only one Singleton created with the new method, the instance, the singleton instance.

What is mean by thread safe

I've been going through the singleton pattern, but I'm not understanding how the below code is thread safe:
public class ThreadSafeSingleton
{
private ThreadSafeSingleton()
{
}
public static ThreadSafeSingleton Instance
{
get { return Nested.instance; }
}
private class Nested
{
static Nested()
{
}
internal static readonly ThreadSafeSingleton instance = new ThreadSafeSingleton();
}
}
Why is this thread-safe?
The CLR executes static constructors only once. It is specified to do so. Therefore, instance is being initialized exactly once. That makes this thread-safe.
How the thread-safety is achieved is an implementation detail.
Please find below implementation for thread safe singleton implementation.
Also, you can use this question useful. It provides double locking thread safety which doesn't hurt performance.
Find reference for static here
Find the reference here
The below code 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.
Not thread safe singleton
// Bad code! Do not use!
public sealed class Singleton
{
private static Singleton instance=null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
Thread safe implementation:
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
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.

Static constructor in Singleton design pattern

On MSDN I found two approaches to creating a singleton class:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton Instance {
get {
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
and
public sealed class Singleton {
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance {
get { return instance; }
}
}
My question is: can we just use a static constructor that will make for us this object before first use?
Can you use the static constructor, sure. I don't know why you'd want to use it over just using the second example you've shown, but you certainly could. It would be functionally identical to your second example, but just requiring more typing to get there.
Note that your first example cannot be safely used if the property is accessed from multiple threads, while the second is safe. Your first example would need to use a lock or other synchronization mechanism to prevent the possibility of multiple instances being created.

Is this singleton instance member thread safe? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have this code:
public class Singleton
{
private static Singleton m_instance;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (m_instance == null)
{
m_instance = new Singleton();
}
return m_instance;
}
}
public void CallMe()
{
// is this function thread safe ?
}
}
Is the CallMe method is thread safe, as every instance member function is thread safe? Or will anything generate an exception here? I saw one sample singleton code using locks, do I really need that?
You've got multiple issues here...
Firstly the Instance property is not necessarily thread safe.
if two threads simultaneously request the property then they could both feasibly find m_instance == nullto betrue` at the same time, return two different instances of Singleton but only one would end up being assigned for future calls.
You would need your implementation to be
private static lockObject lock = new Object();
public static Singleton Instance
{
get
{
if (m_instance != null) return m_instance;
lock (lockObject)
{
if(m_instance != null) return m_instance;
return m_instance = new Singleton();
}
}
}
Alternatively simply instanciate m_instance in the static constructor.
Secondly even after the first issue is resolved you can't say CallMe() is thread safe, we have no idea what it is doing.
First of all, your Instance method is not thread-safe. If it's called twice at the same time, it will return two different instances (and therefore break the singleton pattern).
Without seeing its code, it is impossible to know whether CallMe is thread-safe or not.
That code without any synchronization, is not thread safe without any locking mechanism. The only thread-safe code is one that has a synchronization mechanism.
There are singletone variants with double locking or nested classes. But the easiest solution in .NET 4.0 and above is to use Lazy property:
public class Singleton
{
private static Lazy<Singleton> m_instance = new Lazy = new Lazy<Singleton>();
private Singleton()
{
}
public static Singleton Instance
{
get
{
return m_instance.Value;
}
}
public void CallMe()
{
// now its threadsafe
}
}
The Lazy constructor takes optionally also creating function, or a LazyThreadSafetyMode enum
The Singleton.Instance is now thread safe but not CallMe() itself. It can be still called from differend threads and e.g. access the fields and properties of other classes. It doesn't matter whethere the method is in in the singleton instance or not. You should use other mechanisms to ensure thread safety here.
This is how I would make CallMe Thread Safe:
public class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton()
{
}
public static Singleton Instance { get { return instance; } }
public void CallMe()
{
// Thread Safe
}
}
In other words - let the core framework manage the locking, mutex and volatile stuff for you.
Expanding on Daniel's answer:
private readonly object _threadLock = new Object();
public void CallMe() {
// whatever happens here is not thread-safe
lock(_threadLock) {
// this is the simplest form of a locking mechanism
// code within the lock-block will be thread-safe
// beware of race conditions ...
}
}
Jon Skeet is an authority in .Net and focuses on C#. Here is a link to his analysis of thread-safe singleton instantiation: C# in Depth: Implementing Singleton ...

Singleton Alternative - is it equivalent?

I know that the standard singleton pattern is as follows:
Original
public class Singleton1
{
public static Singleton1 _Instance;
public static Singleton1 Instance
{
get
{
if (_Instance == null)
{
_Instance = new Singleton1();
}
return _Instance;
}
}
private Singleton1()
{
}
}
But it seems like this code is unnecessary. To me, you could accomplish the same thing with either of the following simple design patterns:
Version 2
public class Singleton2
{
public static readonly Singleton2 Instance = new Singleton2();
private Singleton2()
{
}
}
Version 3
public class Singleton3
{
static Singleton3()
{
}
}
To me, it seems like version 2 is the superior method of doing this because it allows you to pass in parameters (or not) yet still have a finite number of instance. My application is fairly latency/performance sensitive - do any of these patterns have a performance gain?
It would seem that while it will longer to access each one the first time because the object is being created. Also, it would seem that the original one is ever so slightly slower because it must check to see whether its backing field is null every time something else accesses it.
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
Fast, clean, thread-safe.
One problem with singletons implemented as static instances is that they make testing and mocking more difficult.
See this scenario:
public void BusinessLogicMethod()
{
var initialValue = MySingleton.Instance.GetInitialValue();
var processedValue = initialValue + specialSomething + businessLogic;
MySingleton.Instance.SaveProcessedValue(processedValue);
}
Now, let's say I want to write a unit-test for this method. Ideally, I want to write a test that specifies input and output and tests only the business logic. But with a static singleton, the method's implementation is tied to the singleton's implementation. Can I set the InitialValue easily at the beginning of the test, or is it dependent on other factors/DB access/whatever?
However, if I use a non-static singleton, coupled with some dependency injection or service locator pattern, I can build my function like this:
public void BusinessLogicMethod()
{
var singleton = ServiceLocator.Resolve<MySingleton>();
var processedValue = singleton.InitialValue + specialSomething + businessLogic;
singleton.SaveProcessedValue(processedValue);
}
and my test can go like this, using vaguely Moq-like mock syntax:
public void TestBusinessLogic()
{
MySingleton fakeSingleton = new Mock<MySingleton>();
fakeSingleton.Setup(s => s.InitialValue).Returns(5);
// Register the fake in the ServiceLocator
ServiceLocator.Register<MySingleton>(fakeSingleton.Object);
// Run
MyBusinessMethod();
// Assert
fakeSingleton.Verify (s => s.SaveProcessedValue()).Called(Exactly.Once);
}
without worrying about the REAL singleton implementation.
Singleton2 is not the same as Singleton1 as the Instance is not "lazy" evaluated. In Singleton1, Instance is created only when it is accessed and from then on the same one is used. In SingleTon2, the Instance is initialized with the class and before being actually accessed.
My favourite singleton implementation is this one:
http://www.codeproject.com/Articles/14026/Generic-Singleton-Pattern-using-Reflection-in-C
Make sure your .ctor is not public, which is the most common mistake, then, it is safely/fully reusable.
(I need to have a close look at Peter Kiss' one which looks nice too)
To answer your performance question, the time it takes to check whether the private field is null is negligible. Therefore I wouldn't be worrying about how it is implemented with regards to performance here.

Categories