Im trying to test my singleton object in C# but somehow not satisfied on how I brute force instantiating the object(using parallel foreach).
Is there a right way/better way to test it?
I don't understand what you mean with "parallel foreach". A singleton is implemented like this:
public class MyClass
{
private static MyClass _instance;
private MyClass()
{
//Do Stuff
}
public static MyClass GetInstance()
{
if(_instance == null)
_instance = new MyClass();
return _instance;
}
}
Another way, instead of a Method is a Property:
private static readonly object LockObject = new object();
private static MyClass _instance;
public static MyClass Instance
{
get
{
lock (LockObject)
{
return _instance ?? (_instance = new MyClass());
}
}
}
While I prefer the first Method, cause it's much easier to implement, even for beginners, the Property is also a good way
Singleton class can have only one instance, If it is initialized multiple times then that means you have not correctly implemented the Singleton Design.
You can check the instance.Hashcode() value, it must remain same wherever you are using the instance of that Singleton class.
Related
I was asked to write Singleton in the interview today. I wrote the below, please note, I used "property set" method to set and then I returned the instance using "get" method. But I see in internet that most places they use only get, meaning, what I did below is wrong? Sorry I dont have VS ide with me to verify it now, so posting it here.
Also, some used sealed class including with private constructor. Why sealed with private cons?
public class Singleton
{
private static readonly Singleton instance;
private Singleton() {}
public static Singleton Instance
{
set
{
if(instance == null){
instance = new Singleton();
}
}
get
{
return instance;
}
}
}
My advice is to try to compile and run the code yourself. It's by far the easiest way to understand how it works.
If you would try to build your code you would get the following error :
Error CS0198 A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
In other words, you should instantiate your instance inside the constructor.
Regarding your question, a private constructor is needed to prevent access from outside your class and also it is enough to make sure that other classes cannot inherit from your class. You don't really need the sealed.
You can find a really good summary regarding the singleton pattern # https://csharpindepth.com/articles/singleton
#Learner Since its a interview question and mostly in India they ask to write to Psuedo code to evaluate the candidate coding skills, I try to fit myself in the candidate shoes to give the answer.
Well design patterns has evolved over a period of time with advancements in the programming language and Singleton is not a exception. There are many ways that we can create a Singleton class using C#. I would like to showcase few of the flavors that I can able to recollect
1. Plain vanilla Singleton without Thread-Safety
public sealed class Singleton
{
private Singleton()
{
}
private static Singleton instance = null;
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
2. Singleton with Thread Saftey
public sealed class Singleton_ThreadLock
{
Singleton_ThreadLock()
{
}
private static readonly object padlock = new object();
private static Singleton_ThreadLock instance = null;
public static Singleton_ThreadLock Instance
{
get
{
// Uses the lock to avoid another resource to create the instance in parallel
lock (padlock)
{
if (instance == null)
{
instance = new Singleton_ThreadLock();
}
return instance;
}
}
}
}
3. Singleton - Double Thread Safe
public sealed class Singleton_DoubleThreadSafe
{
Singleton_DoubleThreadSafe()
{
}
private static readonly object padlock = new object();
private static Singleton_DoubleThreadSafe instance = null;
public static Singleton_DoubleThreadSafe Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton_DoubleThreadSafe();
}
}
}
return instance;
}
}
}
4. Singleton - Early Initialization
public sealed class Singleton_EarlyInitialization
{
private static readonly Singleton_EarlyInitialization instance = new Singleton_EarlyInitialization();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton_EarlyInitialization()
{
}
private Singleton_EarlyInitialization()
{
}
public static Singleton_EarlyInitialization Instance
{
get
{
return instance;
}
}
}
5. Singleton - Lazy Initialization using .Net 4.0+ Framework
public sealed class Singleton
{
private Singleton()
{
}
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
{
get
{
return lazy.Value;
}
}
}
Caveats:
Well there are few people who create instance of the class using reflection (I did in one of my framework) but his can also be avoided. There are few samples in net that can show how to avoid it
Its always best practice to make the Singleton class as sealed as it will restrict developers from inheriting the class.
There are lots of IOC's in the market that can create Singleton instance of a normal class without following the above Singleton implementation.
I've seen many people write singleton like this
public class Singleton
{
private static Singleton _instance = null;
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
What is the difference from this code
public class Singleton
{
private static Singleton _instance = new Singleton();
public static Singleton Instance
{
get { return _instance; }
}
}
Nowaday(C# 6), we have Getter-only auto-properties, is this difference from above(I prefer to write it like this)
public class Singleton
{
public static Singleton Instance { get; } = new Singleton();
}
From what I've known, static field is guaranteed to be ready before I access it for the first time, so it's nothing different, only thing that different is in the first case, I will know when instance is created.
Is there anything more than this or I misunderstand everything?
It is called "Lazy" which postpones the creation of value to first request.
Create the object at the very beginning.
Simplified version of 2.
Or, you can simply use "Lazy" class which many people neglect.
public class Singleton
{
private static Lazy<Singleton> instance = new Lazy<Singleton>();
public static Singleton Instance => instance.Value;
}
"Lazy" is good for large programs.
Reduce startup time since creation is postponed.
Save resource if eventually class is not used.
I always see singletons implemented like this:
public class Singleton
{
static Singleton instance;
static object obj = new object();
public static Singleton Instance
{
get
{
lock (obj)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
protected Singleton() { }
}
Is there's something wrong with implementing it like this:
public class Singleton
{
static readonly Singleton instance = new Singleton();
public static Singleton Instance
{
get { return instance; }
}
protected Singleton() { }
}
? It gets lazy initialized on the very same moment as in the first implementation so I wonder why this isn't a popular solution?
It should be also faster because there's no need for a condition, locking and the field is marked as readonly which will let the compiler to do some optimisations
Let's not talk about the singleton (anti)pattern itself, please
The CLR will initialize the field upon the first use of that (or any other static) field. It promises to do so in a thread-safe manner.
The difference between your code is that the first bit of code supports thread-safe lazy initialization where the second doesn't. This means that when your code never accesses Singleton.Instance of the first code, no new Singleton() will ever be created. For the second class it will, as soon as you access Instance or (directly or indirect) any other static member of that class. Worse even - it may be initialized before that because you lack a static constructor.
Favoring shorter and more readable code, since .NET 4 you can use Lazy<T> to significantly shorten the first code block:
public class Singleton
{
static readonly Lazy<Singleton> instance =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
{
get { return instance.Value; }
}
static Singleton() { }
private Singleton() { }
}
As Lazy<T> also promises thread-safety. This will ensure new Singleton() is only called once, and only when Singleton.Instance is actually used.
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.
Does it make sense to make a System.Timers.Timer member of a singleton volatile static?
Would it make any difference if I make the _fooTimer static and or volatile in singleton instance context?
Would it make any difference if I dont make _instance static?
EDIT2: I corrected the codesample and made it now ba better Singleton without unecessary static or volatile fields and changed to Interlock.Increment
public sealed class Foo
{
private static readonly object _syncRoot;
private int _counter;
private Timer _fooTimer;
private static Foo _instance;
private Foo()
{
_counter = 0;
_syncRoot = new object();
_fooTimer = new new Timer();
_fooTimer.Intervall = 3600000;
_fooTimer.Elapsed += new ElapsedEventHandler(LogFoo);
}
public static Foo Instance
{
get
{
lock(_syncRoot)
{
if (_instance == null)
{
_instance = new Foo();
}
}
return _instance;
}
}
private void LogFoo()
{
// write a logfile with _counter - then restart timer and set _counter to 0
}
public void Increment()
{
Interlocked.Increment(_counter);
}
}
public class UseTheFoo
{
// Foo.Instance.Increment()
...
}
Typically the only static variable in a singleton class is a reference to the single instance. You'd then use instance variables for the remaining state of the type. If you make it static then you don't even need to create a single instance of the class to use the timer - but I would expect that you'd want to do so anyway.
I'd be nervous of using volatile, too... it almost certainly doesn't mean exactly what you think it means. I'd probably use Interlocked instead to achieve atomic updates to the variable.
(Note that there are plenty of better ways of implementing it, as per my article on the topic.)
EDIT: Now that the code has changed to show more members, it's a bit confusing. There's a static method which would use _counter (an instance variable) - presumably via the singleton instance. Basically, the class doesn't seem to have made up its mind about whether it wants to be a bunch of static methods, or a singleton instance. I suggest you decide and make everything accessible one way or the other, but not a mixture.
By making the whole class static, you can push any thread synchronization worries during the creation of the instance to the CLR:
public static class Foo
{
private static Timer _fooTimer;
static Foo()
{
_fooTimer = new Timer();
}
}