C# Singleton "GetInstance" Method or "Instance" Property? - c#

From the perspective of an API end-user who needs to "get an the instance" of a Singleton class, do you prefer to "get" an the .Instance property or "call" a .GetInstance() Method?
public class Bar
{
private Bar() { }
// Do you prefer a Property?
public static Bar Instance
{
get
{
return new Bar();
}
}
// or, a Method?
public static Bar GetInstance()
{
return new Bar();
}
}

In C#, I would far prefer .Instance, as it fits in with the general guidelines.

If you want to create singleton you cannot just return new object on every GetInstance call or Instance property getter. You should do something like this:
public sealed class Bar
{
private Bar() { }
// this will be initialized only once
private static Bar instance = new Bar();
// Do you prefer a Property?
public static Bar Instance
{
get
{
return instance;
}
}
// or, a Method?
public static Bar GetInstance()
{
return instance;
}
}
And it doesn't really matter which way of doing that you choose. If you prefer working with properties choose it, if you prefer methods it will be ok as well.

As with just about everything, it depends :)
If the singleton is lazy-loaded and represents more than a trivial amount of work to instantiate, then GetInstance() is more appropriate, as a method invocation indicates work is being done.
If we're simply masking to protect the singleton instance, a property is preferable.

Depends. Do you need to pass parameters? If so, I'd do GetInstance(). If not, probably doesn't matter (at least from a calling standpoint, since they're really both methods anyway; however, it does matter if you're trying to be more standards-based and, in that case, an instance appears to be better).

public class Singleton
{
private volatile static Singleton uniqueInstance;
private static readonly object padlock = new object();
private Singleton() { }
public static Singleton getInstance()
{
if (uniqueInstance == null)
{
lock (padlock)
{
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
In the above code double checking is implemented ,first it is checked if an instance is is created and if not lock has been established .Once in this block
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
if the instance is null then create it.
Also, the uniqueInstance variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed.

I prefer property, these are standard patterns.

As #Rex said, it depends on the semantic you want to convey.
GetInstance() does not necessarily imply a singleton instance. So, I would use GetInstance() in the case where the instance creation happens on demand, direct new is not desireable and the instance could be, but is not guaranteed to be the same. Object pools fit these criteria as well. (In fact, a singleton is a specialization of an object pool with state preservation :-))
Static Instance property on the other hand implies a singleton and preserved instance identity.
Btw, as #RaYell mentioned your sample code is not a singleton, so you shouldn't be using Instance property. You can still use the GetInstance() method in this case, as it would serve as an instance factory.

Related

Is there anyway I can intercept a new call?

I have a type that I would like to be cached, in that, since it's immutable, if you call new Foo(1), it creates it but also adds that instance to a cache, and if you do it again, you'll just end up with the cached Foo with a value of 1.
Somehow this means I need to intercept the call new <Type>(), and instead use custom logic.
Is this possible, and if so, how is its performance?
You would have to modify the compiled IL. It would be hard to implement and unreadable. Anyone who sees new expects a new instance to be created.
Better use a static factory method:
public class Foo
{
public static Foo GetInstance(int parameter)
{
if (FooCache.IsCached(parameter))
{
// return instance from cache
}
else
{
Foo instance = new Foo(parameter);
// add to cache
return instance;
}
}
private Foo(int parameter)
{
}
}
Notice that the constructor is private. The only way to get an instance of this class is to use the factory method.
The standard way to do this is to use the Factory Pattern and a private constructor. The private constructor means no code outside of the class can use new Foo(1), but instead you will write something like Foo.newFoo(1);, which will hold the logic to create a new Foo or return a cached value.

Is Lazy<T> a good solution for a thread safe lazy loaded singleton?

We implemented a lazy loaded singleton using double locking on get to make sure the instance is only initialized once (and not twice due to thread race conditions).
I was wondering if simply using Lazy<T> is a good solution for this problem?
I.E.
private static Lazy<MyClass> _instance = new Lazy<MyClass>(() => return new MyClass());
public static MyClass Instance
{
get
{
return _instance.Value;
}
}
I suggest you to read referenced articles from comments:
Lazy Class
Implementing the Singleton Pattern in C#
In all cases the Lazy<T> class is thread-safe, but you need to remember that the Value of this type can be thread-unsafe, and can be corrupted in multithreading environment:
private static Lazy<MyClass> _instance = new Lazy<MyClass>(() => return new MyClass());
public static MyClass Instance
{
get {
return _instance.Value;
}
}
public void MyConsumerMethod()
{
lock (Instance)
{
// this is safe usage
Instance.SomeMethod();
}
// this can be unsafe operation
Instance.SomeMethod();
}
Also you can use any constructor you like depending on the environment of your application.

Thread Safe C# Singleton Pattern

I have some questions regarding the the singleton pattern as documented here:
http://msdn.microsoft.com/en-us/library/ff650316.aspx
The following code is an extract from the article:
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
Specifically, in the above example, is there a need to compare instance to null twice, before and after the lock? Is this necessary? Why not perform the lock first and make the comparison?
Is there a problem in simplifying to the following?
public static Singleton Instance
{
get
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
return instance;
}
}
Is the performing the lock expensive?
Performing the lock is terribly expensive when compared to the simple pointer check instance != null.
The pattern you see here is called double-checked locking. Its purpose is to avoid the expensive lock operation which is only going to be needed once (when the singleton is first accessed). The implementation is such because it also has to ensure that when the singleton is initialized there will be no bugs resulting from thread race conditions.
Think of it this way: a bare null check (without a lock) is guaranteed to give you a correct usable answer only when that answer is "yes, the object is already constructed". But if the answer is "not constructed yet" then you don't have enough information because what you really wanted to know is that it's "not constructed yet and no other thread is intending to construct it shortly". So you use the outer check as a very quick initial test and you initiate the proper, bug-free but "expensive" procedure (lock then check) only if the answer is "no".
The above implementation is good enough for most cases, but at this point it's a good idea to go and read Jon Skeet's article on singletons in C# which also evaluates other alternatives.
The Lazy<T> version:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy
= new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
=> lazy.Value;
private Singleton() { }
}
Requires .NET 4 and C# 6.0 (VS2015) or newer.
Performing a lock: Quite cheap (still more expensive than a null test).
Performing a lock when another thread has it: You get the cost of whatever they've still to do while locking, added to your own time.
Performing a lock when another thread has it, and dozens of other threads are also waiting on it: Crippling.
For performance reasons, you always want to have locks that another thread wants, for the shortest period of time at all possible.
Of course it's easier to reason about "broad" locks than narrow, so it's worth starting with them broad and optimising as needed, but there are some cases that we learn from experience and familiarity where a narrower fits the pattern.
(Incidentally, if you can possibly just use private static volatile Singleton instance = new Singleton() or if you can possibly just not use singletons but use a static class instead, both are better in regards to these concerns).
The reason is performance. If instance != null (which will always be the case except the very first time), there is no need to do a costly lock: Two threads accessing the initialized singleton simultaneously would be synchronized unneccessarily.
In almost every case (that is: all cases except the very first ones), instance won't be null. Acquiring a lock is more costly than a simple check, so checking once the value of instance before locking is a nice and free optimization.
This pattern is called double-checked locking: http://en.wikipedia.org/wiki/Double-checked_locking
This is called Double checked locking mechanism, first, we will check whether the instance is created or not. If not then only we will synchronize the method and create the instance. It will drastically improve the performance of the application. Performing lock is heavy. So to avoid the lock first we need to check the null value. This is also thread safe and it is the best way to achieve the best performance. Please have a look at the following code.
public sealed class Singleton
{
private static readonly object Instancelock = new object();
private Singleton()
{
}
private static Singleton instance = null;
public static Singleton GetInstance
{
get
{
if (instance == null)
{
lock (Instancelock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
Jeffrey Richter recommends following:
public sealed class Singleton
{
private static readonly Object s_lock = new Object();
private static Singleton instance = null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if(instance != null) return instance;
Monitor.Enter(s_lock);
Singleton temp = new Singleton();
Interlocked.Exchange(ref instance, temp);
Monitor.Exit(s_lock);
return instance;
}
}
}
You could eagerly create the a thread-safe Singleton instance, depending on your application needs, this is succinct code, though I would prefer #andasa's lazy version.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance()
{
return instance;
}
}
Another version of Singleton where the following line of code creates the Singleton instance at the time of application startup.
private static readonly Singleton singleInstance = new Singleton();
Here CLR (Common Language Runtime) will take care of object initialization and thread safety. That means we will not require to write any code explicitly for handling the thread safety for a multithreaded environment.
"The Eager loading in singleton design pattern is nothing a process in
which we need to initialize the singleton object at the time of
application start-up rather than on demand and keep it ready in memory
to be used in future."
public sealed class Singleton
{
private static int counter = 0;
private Singleton()
{
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
private static readonly Singleton singleInstance = new Singleton();
public static Singleton GetInstance
{
get
{
return singleInstance;
}
}
public void PrintDetails(string message)
{
Console.WriteLine(message);
}
}
from main :
static void Main(string[] args)
{
Parallel.Invoke(
() => PrintTeacherDetails(),
() => PrintStudentdetails()
);
Console.ReadLine();
}
private static void PrintTeacherDetails()
{
Singleton fromTeacher = Singleton.GetInstance;
fromTeacher.PrintDetails("From Teacher");
}
private static void PrintStudentdetails()
{
Singleton fromStudent = Singleton.GetInstance;
fromStudent.PrintDetails("From Student");
}
Reflection resistant Singleton pattern:
public sealed class Singleton
{
public static Singleton Instance => _lazy.Value;
private static Lazy<Singleton, Func<int>> _lazy { get; }
static Singleton()
{
var i = 0;
_lazy = new Lazy<Singleton, Func<int>>(() =>
{
i++;
return new Singleton();
}, () => i);
}
private Singleton()
{
if (_lazy.Metadata() == 0 || _lazy.IsValueCreated)
throw new Exception("Singleton creation exception");
}
public void Run()
{
Console.WriteLine("Singleton called");
}
}

A simple implementation of a Singleton

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; }
}
}

Static property references non-static method

How can a static property reference a nonstatic method?
Example:
public static int UserID
{
get
{
return GetUserID();
}
}
private int GetUserID()
{
return 1;
}
When I try to compile this, I get the error: "An object reference is required for he non-static field, method or property "GetUserID()"
This doesn't work.
When you define a static property (or static method), you're defining a property that works on the class type, not on an instance of the class.
Instance properties and methods, on the other hand, work upon a specific, constructed, instance of a class. In order to use them, you need to have a reference to that specific instance. (The other way around, however, is fine.)
As an example, think of Fruit, and an "Apple" class. Say the apple class has an instance property that is how ripe the Apple is at this point in time.
You wouldn't as "Apple" to describe how ripe it is, but rather a specific "Apple" (instance). On the other hand, you could have an instance of an apple, and ask it whether it contains seeds (which might be defined on the Apple class itself (static)).
You'll just have to create a new instance:
public static int UserID
{
get
{
return new MyClass().GetUserID()
}
}
Well, you don't have to create a new instance every time UserId is called -- you can have a static field containing an instance of MyClass instead (which of course would be an approach toward implementing the Singleton pattern).
Although you can read that your static property is calling a method that could be made static, the other method isn't static. Thus, you must call the method on an instance.
You need somehow to get an instance. Without an instance, it's impossible to call an instance method.
For your case, are you sure that you need GetUserID() to be an instance method? It returns anyway the same value. Or, if your code is just dummy, and you require more logic in GetUserID(), maybe you can tell us what you intend to do?
An easy way to think about it is the following: a non-static method (or property, because properties are just wrapped-up methods) receives, as a first hidden parameter, a reference to the instance on which they operate (the "this" instance within the called method). A static method has no such instance, hence nothing to give as first hidden parameter to the non-static method.
Simply it can't.
If you need to call a static method to invoke an instance method, probably you want a Singleton
Try look at:
http://en.wikipedia.org/wiki/Singleton_pattern
Example:
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
private Singleton() { }
public static Singleton Instance
{
get
{
return _instance;
}
}
public static int UserID
{
get
{
return _instance.GetUserID();
}
}
private int GetUserID()
{
return 1;
}
}

Categories

Resources