In singleton pattern, we have a private constructor and a public static method like below -
public class MyClass
{
private static MyClass _uniqueInstance;
private MyClass()
{
}
public static MyClass GetInstance()
{
if(_uniqueInstance==null)
{
_uniqueInstance = new MyClass();
}
return _uniqueInstance;
}
}
And we can create ONE and Only ONE instance of this Class by invoking the static method whenever we need the object of this class like -
var myObject = MyClass.GetInstance();
But I am confused why we check for null in the GetInstance() method as the "_uniqueInstance" is already a static variable, so it will be initailized and allocated memory only once . Even if we do not check for null and still initialize the object with "new", memory will not be allocated again for this object as it is a static variable. So, what is the use of this null check ?
Please clear my doubt.
I sense confusion between initializers, factories, and singletons.
A field initializer:
static readonly object Value = new object();
A factory method:
static object CreateValue()
{
return new object();
}
A singleton pattern:
static object _value;
static object Value
{
get
{
return _value ?? (_value = new object());
}
}
Initializers are removed to the static constructor upon compilation, which runs once like you guessed. Except for order, the initialization of static fields is uncontrollable. When any static field initializes, then all static fields initialize. A singleton pattern prevents this.
The factory method is intended as an abstraction of an instance constructor.
A singleton pattern can be considered an abstraction of a field initializer, assuring that a resource is not introduced until necessary. However, for resources which are most certainly referenced, like String.Empty, it is wiser to use a static field instead to avoid clutter.
If you use the following code:
public static MyClass GetInstance()
{
_uniqueInstance = new MyClass();
return _uniqueInstance;
}
then every time someone calls this GetInstance you will get a different instance of the class which contradicts with what a Singleton is. The idea of the Singleton pattern is to always get the same instance of the class, no matter how many times you call it in your application. And this instance should be constructed only once.
So basically the null check will return true only the first time GetInstance is called in order to instantiate the private static field (which is null by default) and on subsequent calls the same instance will be returned.
Bare in mind though that this singleton pattern implementation that you have shown here is not thread safe. If 2 threads call the GetInstance method at the beginning at the same time, potentially they could get 2 different instances.
You can read more about the Singleton pattern and the various C# implementations in this article.
We use Singleton pattern to get only one instance of an object and use this instance everywhere.
If we remove the null checking if(_uniqueInstance==null) then every time GetInstance is called a new instance will be created and it will be stored in _uniqueInstance variable.
Even if we do not check for null and still initialize the object with
"new", memory will not be allocated again for this object as it is a
static variable.
Memory is allocated to _uniqueInstance as a reference type just once because it is static. but you can assign many references to this static variable and those objects can be created as many time as needed in the memory.
So, what is the use of this null check
The null check ensures that _uniqueInstance is assigned just once with an instance of MyClass and it is never changed trough the life time of application domain. So every one call GetInstance will get the same instance of MyClass.
Read more about singleton
This is wrong:
Even if we do not check for null and still initialize the object with
"new", memory will not be allocated again for this object as it is a
static variable.
Calling new will allocate new memory and _uniqueInstance will have a new pointer. So, you'll have different instance on every call of the method - it's not a singleton.
Related
In the following code:
public sealed class Switch
{
public static MyObj s_object = new MyObj();
private readonly SomeObject m_object = new SomeObject();
~Switch()
{
m_object?.Dispose();
}
}
public class Test()
{
Test()
{
Switch switch = new Switch();
switch = null;
...
}
}
When the Test ctor executes, a new Switch object is created then immediately set to null. At some point the GC will dispose of it, calling the ~Switch() destructor in the process. But will that happen when a class contains a static field like s_object and the calling app has not terminated (app domain still loaded)? Static objects persist for the lifetime of the application; does that mean the non-static class containing it will too?
This should be not a problem. Static fields are not related this way to the instance of the defining type in terms of memory representation.
Check this post for more detailed info: How exactly do static fields work internally?
Presence of static fields has no impact on timing when object will be garbage collected (and hence finalized). The instance will be finalized just fine at moment comparable to time it happens without static field.
The only impact static fields have on instances is that static initialization happens before first instance is created thus potentially making creation of first instance slower than the rest.
Note: code in the post shows invalid implementation of finalizer because it refers to other manged object and tries to call method on it. It results in undefined behavior for both cases (with/without static field).
I have a class which has 3 static members. Each of static member is not thread-safe singleton.
I need to provide a thread safe implementation for their use.Is it ok?Or I need to provide thread-safe wrapper for each of them? If I should - how can I do it using Lazy<T>?
Additional question : Measure() and Do() of SingeltonClass1/2/3 are not thread-safe is func1() thread-safe?
public class MyLazySingleton
{
// static holder for instance, need to use lambda to construct since constructor private
private static readonly Lazy<MyLazySingleton> _instance
= new Lazy<MyLazySingleton>(() => new MyLazySingleton());
// private to prevent direct instantiation.
private MyLazySingleton()
{
s_c1 = SingletonClass1.Instance();
s_c2 = SingletonClass2.Instance();
s_c3 = SingletonClass3.Instance();
}
// accessor for instance
public static MyLazySingletonInstance
{
get
{
return _instance.Value;
}
}
public void func1()
{
if (s_s1.Measure() || s_c2.Measure())
{
c_c3.Do();
}
}
static SingletonClass1 s_c1 = null;
static SingletonClass1 s_c2 = null;
static SingletonClass1 s_c3 = null;
}
How should I re-implement MyLazySingleton if its constructor should get 2 arguments? string str and int i
I have asked a follow up question Thread-safe methods in the singleton class
It's thread-safe as it is.
The default value for Lazy<T>'s LazyThreadSafetyMode is ExecutionAndPublication.
From the MSDN page on the new Lazy<T>(Func<T>) constructor:
An instance that is created with this constructor may be used
concurrently from multiple threads.
The thread safety mode of a Lazy instance that is initialized with
this constructor is LazyThreadSafetyMode.ExecutionAndPublication.
If you were to use another overload where you could pass a different LazyThreadSafetyMode value it wouldn't be thread safe. But using the constructor as you are now, it is thread safe.
EDIT: Regarding your additional edited question, if those methods on your SingletonClass1 type are not thread safe: then no, func1 is not thread safe either.
From the Lazy<T> MSDN Page:
Making the Lazy object thread safe does not protect the lazily
initialized object. If multiple threads can access the lazily
initialized object, you must make its properties and methods safe for
multithreaded access.
You will need to make sure that those methods/interactions between those classes are thread safe. This might be as simple as wrapping the func1 body with a lock statement, but I can't say for certain depending on how your 3 instances of SingletonClass1 interact with each other or how calling code may access them.
To ensure Thread-safety you have to set the LazyThreadSafetyMode parameter of the Lazy<T> constructor. There are 3 available values:
None: not thread-safe
PublicationOnly: many MyLazySingleton instance may be created, but only one will be published/returned by the Value property. Internally it uses Interlocked.CompareExchange
ExecutionAndPublication: The value is create only once
Here's an example:
new Lazy<Test>(() => new Test(), LazyThreadSafetyMode.ExecutionAndPublication)
Static members are not regarding the instance but the type itself.
But I was wondering :
If I have this class :
public class A
{
...
public static int MyInt{get;set;}
...
}
I can create of course new A()
But my question is :
Does the static member which is "stucked" to the type itself , prevents the instance from being GC'ed ?
Not necessarily. The static member belongs to the class itself, which CLR keeps as a Type object. If the static member was an object of type A, then the static member could keep that particular instance of A from being garbage collected.
public class Example
{
// this particular instance of Example will not be collected
private static readonly Example Default = new Example();
public void Foo()
{
// this instance *can* be collected after Foo returns
Example anotherInstance = new Example();
}
}
This behavior is useful for certain classes which aren't necessarily singletons but do have a "default" behavior that is stateless. One example where I use this is the ParseTreeWalker.Default field in the C# runtime library for the ANTLR 4 project. If you need the default behavior, you can use that instance without creating new objects, but you also have the option of creating your own instances of a class extending ParseTreeWalker to add your own behavior.
No, it does not. This can be easily shown by overwriting the finalizer.
A colleague of mine told me that I should never use static variables because if you change them in one place, they are changed everywhere. He told me that instead of using static variables I should use Singleton.
I know that Singleton is for limitation of the number of instances of one class to one.
How can Singleton help me with static variables?
Let's address your statements one at a time:
A colleague of mine told me that I should never use static variables because if you change them in one place, they are changed everywhere.
It seems fairly clear that your colleague means the basic feature of static variables: there is only one instance of a static variable. No matter how many instances of any class you create, any access to a static variable is to the same variable. There is not a separate variable for each instance.
He told me that instead of using static variables I should use Singleton.
This is not good global advice. Static variables and singletons aren't in competition with each other and aren't really substitutes for each other. A singleton is an instance of a class, managed in such a way that only one instance is possible to create. A static variable is similarly tied to exactly one (static) instance of a class, but could be assigned with not only a class instance but any data type such as a scalar. In actuality, to effectively use the singleton pattern, you must store it in a static variable. There is no way to "use a singleton instead of a static variable".
On the other hand, perhaps he meant something slightly different: perhaps he was trying to say that instead of your static class having many different static variables, methods, properties, and fields (altogether, members) that function as if they were a class, you should make those fields non-static, and then expose the wrapping class as a Singleton instance. You would still need a private static field with a method or property (or perhaps just use a get-only property) to expose the singleton.
I know that Singleton is for limitation of the number of instances of one class to one. How can Singleton help me with static variables?
A static class's variables and a singleton are alike in that they both are instantiated once (the former enforced by the compiler and the latter enforced by your implementation). The reason you'd want to use a singleton instead of a static variable inside of a class is when your singleton needs to be a true instance of a class, and not consist simply of the collected static members of a static class. This singleton then gets assigned to a static variable so that all callers can acquire a copy of that same instance. As I said above, you can convert all the different static members of your static class to be instance members of your new non-static class which you will expose as a singleton.
I would also like to mention that the other answers given so far all have issues around thread safety. Below are some correct patterns for managing Singletons.
Below, you can see that an instance of the Singleton class, which has instance (or non-static) members, is created either by static initialization or within the static constructor, and is assigned to the variable _singleton.. We use this pattern to ensure that it is instantiated only once. Then, the static method Instance provides read-only access to the backing field variable, which contains our one, and only one, instance of Singleton.
public class Singleton {
// static members
private static readonly Singleton _singleton = new Singleton();
public static Singleton Instance => _singleton
// instance members
private Singleton() { } // private so no one else can accidentally create an instance
public string Gorp { get; set; }
}
or, the exact same thing but with an explicit static constructor:
public class Singleton {
// static members
private static readonly Singleton _singleton; // instead of here, you can...
static Singleton() {
_singleton = new Singleton(); // do it here
}
public static Singleton Instance => _singleton;
// instance members
private Singleton() { } // private so no one else can accidentally create an instance
public string Gorp { get; set; }
}
You could also use a property default without an explicit backing field (below) or in a static constructor can assign the get-only property (not shown).
public class Singleton {
// static members
public static Singleton Instance { get; } = new Singleton();
// instance members
private Singleton() { } // private so no one else can accidentally create an instance
public string Gorp { get; set; }
}
Since static constructors are guaranteed to run exactly once, whether implicit or explicit, then there are no thread safety issues. Note that any access to the Singleton class can trigger static initialization, even reflection-type access.
You can think of static members of a class as almost like a separate, though conjoined, class:
Instance (non-static) members function like a normal class. They don't live until you perform new Class() on them. Each time you do new, you get a new instance. Instance members have access to all static members, including private members (in the same class).
Static members are like members of a separate, special instance of the class that you cannot explicitly create using new. Inside this class, only static members can be accessed or set. There is an implicit or explicit static constructor which .Net runs at the time of first access (just like the class instance, only you don't explicitly create it, it's created when needed). Static members of a class can be accessed by any other class at any time, in or out of an instance, though respecting access modifiers such as internal or private.
EDIT #ErikE's response is the correct approach.
For thread safety, the field should be initialized thusly:
private static readonly Singleton instance = new Singleton();
One way to use a singleton (lifted from http://msdn.microsoft.com/en-us/library/ff650316.aspx)
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
/// non-static members
public string Foo { get; set; }
}
Then,
var foo = Singleton.Instance.Foo;
Singleton.Instance.Foo = "Potential thread collision here.";
Note that the instance member is a static field. You can't implement a singleton without using a static variable, and (I seem to recall - it's been awhile) this instance will be shared across all requests. Because of that, it's inherently not thread safe.
Instead, consider putting these values in a database or other persistent store that's more thread-friendly, and creating a class that interfaces with that portion of your database to provide transparent access.
public static class Foo
{
public static string Bar
{
get { /// retrieve Bar from the db }
set { /// update Bar in the db }
}
}
The whole point of the static modifier is to ensure that the object thus modified is the same wherever it is used as it requires no instantiation. The name originally came about as a static variable has a fixed location in memory and all items referring to it will reference the same memory location.
Now you may wish to use a static field within a class, in which case it exists before the class is instantiated (constructed). There may be instances where you would want this.
A singleton is a different beast. It is a class that is limited to a single instantiation by use of a private constructor and a static property. So in that regard you still can't avoid statics by using a singleton.
To answer the stated question:
It is incredibly stupid (but possible) to create a singleton without a static field.
To do it, you need to use someone else's static field, such as AppDomain.GetData or (in ASP.Net) HttpContext.Application.
Just to answer your question (I hope): Instead of using a static class containing static members like Class1 you can implement the Singleton pattern like in Class2 (please don't begin a discussion about lazy initialization at this point):
public static class Class1
{
public static void DoSomething ()
{
}
}
public static class Class2
{
private Class2() {
}
private Class2 instance;
public Class2 GetInstance(){
if (instance == null)
instance = new Class2();
return instance;
}
public void DoSomething ()
{
}
}
Instead of calling Class1.DoSomething() you can use Class2.GetInstance().DoSomething().
Edit: As you can see there's still a (private) static field inside Class2 holding it's instance.
Edit2 in answer to user966638's comment:
Do I understand you correct that you have code like this:
public class Foo {
private static Bar bar;
}
And your collegue suggests to replace it by this?
public class Foo {
private BarSingleton bar;
}
This could be the case if you want to have different Foo instances where each instance's bar attribute could be set to null for example. But I'm not sure if he meant this what exactly is the use case he is talking about.
Both singleton and static variables give you one instance of a class. Why you should prefer singleton over static is
With Singleton you can manage the lifetime of the instance yourself, they way you want
With Singleton, you have greater control over the initialization of the instance. This useful when initializing an instance of a class is complicated affair.
It's challenging to make static variables thread-safe, with singleton, that task becomes very easy
Hope this helps
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
I think even on removing readonly keyword from the instance member instantiation, the singleton would still work equally well.
Its static, only one instance would exist.
The value cant change, as it has no setter.
Its a sealed class, cant be subclassed.
Please help me correct my understanding of the concepts here.
Because if the field were not marked readonly it could be modified within the Singleton class. Of course, it still could not be modified by the outside world, but a singleton really isn't a singleton if there is more than one instance of it during the lifetime of your program, and the readonly specifier enforces the semantics that you want in a singleton class.
EDIT in response to:
Its static, only one instance would exist.
The value cant change, as it has no setter.
Static variables can certainly be set to reference different objects at runtime. The value can change, if only within the class due to it being private. If the class were implemented such that the field was only ever assigned to once, it wouldn't be a problem in practice. However, since the assumed intention is that the singleton instance will never change, the readonly modifier guarantees those semantics outside of the constructor. It's not essential because clients of the class cannot change the reference, but it is preferred because it a) makes the intent of the code clear, and b) prevents the reference from being changed even within the class.
Using readonly is not essential in this case but it is something that enforces the semantics of the code by indicating the nature of the field. Personally I always use the readonly keyword for all field declarations whose value is going to be initialized only once. It also might help the compiler perform some optimizations under certain circumstances.
I don't think readonly must present here - it makes sense only for lazy initialization. If you static field marked as readonly - it could be initialized only during declaration or in static constructor. If instance is not marked as readonly - you can initalize it during first call to Instance property.
BTW I think it's better to use singleton with double-check locking:
public sealed class Singleton
{
private Singleton()
{
// Initialize here
}
private static volatile Singleton _singletonInstance;
private static readonly Object syncRoot = new Object();
public static Singleton Instance
{
get
{
if(_singletonInstance == null)
{
lock(syncRoot))
{
if(_singletonInstance == null)
{
_singletonInstance = new Singleton();
}
}
}
return _singletonInstance;
}
}
}
I removed the readonly in a class because I wanted to make a OneAtaTimeleton (instead of a Singleton).
Why? Well, the class contained some configuration that I wanted the user (administrator) to be able to change while the app was running. So, I added a static Reload() method to the class, which has:
instance = new Configuration();
hence the need to remove the readonly.
The private version of the constructor loads the config (via a non-static method).