I'm writing a wrapper around a class library that I have no control over. In this library is a class (let's call it Target) that I want to ensure is only instantiated once, but it is not, in itself, a singleton. I thought of using the Singleton-Factory pattern like so:
internal sealed class SingletonFactory
{
private static readonly SingletonFactory manager = new SingletonFactory();
private readonly Target target;
private static SingletonFactory() { }
private SingletonFactory()
{
target = new Target();
target.Init("foo");
}
internal static SingletonFactory Instance
{
get { return manager; }
}
internal Target Target
{
get { return target; }
}
}
I can then do:
var targetInstance = SingletonFactory.Instance.Target;
I then thought of simplifying this by making the Factory completely static like this:
internal static class StaticFactory
{
private static readonly Target target;
private static StaticFactory()
{
target = new Target();
target.Init("foo");
}
internal static Target Target
{
get { return target; }
}
}
and access to the target instance becomes:
var targetInstance StaticFactory.Target;
I'm pretty sure this StaticFactory is thread-safe, and provides global access to a single instance of the target class. Is there anything wrong with this that I haven't thought of?
I'm not certain that your constructor is really thread-safe, since it technically could be accessed from different threads at the same time. You could lock on a private static readonly object Lock = new object(); to enforce thread safety there.
If we are talking about C# 4, you might also want to look at Lazy<T> here http://msdn.microsoft.com/de-de/library/ee792409.aspx. It supports a thread-safe creation mode LazyThreadSafetyMode that allows you to find a tradeoff between safety and performance.
Sidenote:
In the end, not using a static class might be a better design decision as you prevent an architecturally invisible dependency and gain the ability to swap implementations. Working with abstract factories addresses that (and also allows a nice unit testing experience).
Same thing really, except yours had the private keyword on the static constructor, which is disallowed.
internal static class StaticFactory
{
public static Target Target = new Target();
static StaticFactory()
{
Target.Init("foo");
}
}
You could get fancy, and shove it all into a Lazy:
public static Lazy<Target> Target =
new Lazy<Target>(() => { var t = new Target(); t.Init(""); return t; });
You could also establish a facade, which would give you the same semantics as Target, but keep it as a single instance. It also gives you room to play with where and when you initialize the Target object.
public class TargetFacade
{
private static Target _target = new Target();
static StaticFactory()
{
_target.Init("foo");
}
//Wrap Target's methods here.
public int Score { get { return _target.Score } };
}
Related
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.
I'm implementing a singleton pattern, and need the initialization to be thread safe.
I've seen several ways to do it, like using the double check lock implementation, or other techniques (i.e.: http://csharpindepth.com/articles/general/singleton.aspx)
I wanted to know if the following approach, which is similar to the fourth version in the article, is thread safe. I'm basically calling a method in the static field initializer, which creates the instance. I don't care about the lazyness. Thanks!
public static class SharedTracerMock
{
private static Mock<ITracer> tracerMock = CreateTracerMock();
private static Mock<ITracer> CreateTracerMock()
{
tracerMock = new Mock<ITracer>();
return tracerMock;
}
public static Mock<ITracer> TracerMock
{
get
{
return tracerMock;
}
}
}
Yes, that's thread-safe - although it's not the normal singleton pattern, as there are no instances of your class itself. It's more of a "single-value factory pattern". The class will be initialized exactly once (assuming nothing calls the type initializer with reflection) and while it's being initialized in one thread, any other thread requesting TracerMock will have to wait.
Your code can also be simplified by removing the method though:
public static class SharedTracerMock
{
private static readonly Mock<ITracer> tracerMock = new Mock<ITracer>();
public static Mock<ITracer> TracerMock { get { return tracerMock; } }
}
Note that I've made the field readonly as well, which helps in terms of clarity. I generally stick trivial getters all on one line like this too, to avoid the bulk of lots of lines with just braces on (7 lines of code for one return statement feels like overkill).
In C# 6, this can be simplified even more using a readonly automatically implemented property:
public static class SharedTracerMock
{
public static Mock<ITracer> TracerMock { get; } = new Mock<ITracer>();
}
Of course, just because this property is thread-safe doesn't mean that the object it returns a reference to will be thread-safe... without knowing about Mock<T>, we can't really tell that.
I have my singleton as below:
public class CurrentSingleton
{
private static CurrentSingleton uniqueInstance = null;
private static object syncRoot = new Object();
private CurrentSingleton() { }
public static CurrentSingleton getInstance()
{
if (uniqueInstance == null)
{
lock (syncRoot)
{
if (uniqueInstance == null)
uniqueInstance = new CurrentSingleton();
}
}
return uniqueInstance;
}
}
I would like check, if I will have two thread, are there two different singletons? I think, I shall have two different singletons (with different references), so what I'm doing:
class Program
{
static void Main(string[] args)
{
int currentCounter = 0;
for (int i = 0; i < 100; i++)
{
cs1 = null;
cs2 = null;
Thread ct1 = new Thread(cfun1);
Thread ct2 = new Thread(cfun2);
ct1.Start();
ct2.Start();
if (cs1 == cs2) currentCounter++;
}
Console.WriteLine(currentCounter);
Console.Read();
}
static CurrentSingleton cs1;
static CurrentSingleton cs2;
static void cfun1()
{
cs1 = CurrentSingleton.getInstance();
}
static void cfun2()
{
cs2 = CurrentSingleton.getInstance();
}
}
I suppose that I should got currentCounter = 0 (in this case every two singleton are different - because are creating by other threrad). Unfortunately, I got for example currentCounter = 70 so in 70 cases I have the same singletons... Could you tell me why?
I would like check, if I will have two thread, are there two different singletons
No, there are not. A static field is shared across each entire AppDomain, not each thread.
If you want to have separate values per thread, I'd recommend using ThreadLocal<T> to store the backing data, as this will provide a nice wrapper for per-thread data.
Also, in C#, it's typically better to implement a lazy singleton via Lazy<T> instead of via double checked locking. This would look like:
public sealed class CurrentSingleton // Seal your singletons if possible
{
private static Lazy<CurrentSingleton> uniqueInstance = new Lazy<CurrentSingleton>(() => new CurrentSingleton());
private CurrentSingleton() { }
public static CurrentSingleton Instance // use a property, since this is C#...
{
get { return uniqueInstance.Value; }
}
}
To make a class that provides one instance per thread, you could use:
public sealed class InstancePerThread
{
private static ThreadLocal<InstancePerThread> instances = new ThreadLocal<InstancePerThread>(() => new InstancePerThread());
private InstancePerThread() {}
public static InstancePerThread Instance
{
get { return instances.Value; }
}
}
By default, a static field is a single instance shared by all threads that access it.
You should take a look at the [ThreadStatic] attribute. Apply it to a static field to make it have a distinct instance for each thread that accesses it.
Use of a locking object ensures that only one value gets created; you can verify this by putting some logging in your CurrentSingleton constructor.
However, I think there's a small gap in your logic: imagine that two threads simultaneously call this method, while uniqueInstance is null. Both will evaluate the = null clause, and advance to the locking. One will win, lock on syncRoot, and initialize uniqueInstance. When the lock block ends, the other will get its own lock, and initialize uniqueInstance again.
You need to lock on syncRoot before even testing whether uniqueInstance is null.
No matter what you do you are never going to get currentCounter = 0.
Because we are forgetting the the fact that application/C# code is also running in some thread and there are some priorities set by C# to run the code. If you debug the code by putting break points in Main method and CurrentSingleton you will notice that. By the time you reach and create the new Object for CurrentSingleton, for loop may be iteration 3 or 4 or any number. Iterations are fast and code is comparing null values and Object or Object and null value. And I think this is the catch.
Reed has got point static will always be shared hence you need to change your code in following way
public class CurrentSingleton
{
[ThreadStatic]
private static CurrentSingleton uniqueInstance = null;
private static object syncRoot = new Object();
private CurrentSingleton() { }
public static CurrentSingleton getInstance()
{
if (uniqueInstance == null)
uniqueInstance = new CurrentSingleton();
return uniqueInstance;
}
}
And as per analysis you are getting two different objects at 70th iteration but, that is something just mismatch may be null and Object or Object and null. To get successful two different object you need to use [ThreadStatic]
I am working on some code which is something like this:
class A
{
static SomeClass a = new Someclass("asfae");
}
Someclass contains the required constructor.
The code for this compiles fine without any warning. But I get a code hazard in system:
"The Someclass ctor has been called from static constructor and/or
static initialiser"
This code hazard part of system just to make it better by warning about possible flaws in the system or if system can get into bad state because of this.
I read somewhere on the web that static constructor/initialiser can get into deadlock in c# if they wait for a thread to finish. Does that have something to do with this?
I need to get rid of this warning how can i do this.
I can't make the member unstatic as it's used by a static function.
What should I do in this case , Need help.
You could hide it behind a property and initialize it on first use (not thread-safe);
class A
{
static SomeClass aField;
static SomeClass aProperty
{
get
{
if (aField == null) { aField = new Someclass("asfae"); }
return aField;
}
}
}
or use Lazy (thread-safe):
class A
{
static Lazy<SomeClass> a = new Lazy<SomeClass>(() => new Someclass("asfae"));
}
...or this very verbose thread safe version :)
class A
{
static SomeClass aField;
static object aFieldLock = new object();
static SomeClass aProperty
{
get
{
lock (aFieldLock)
{
if (aField == null) { aField = new Someclass("asfae"); }
return aField;
}
}
}
}
By initialising it as a static field, it behaves as it would in a static constructor, i.e. it probably gets initialised the first time an instance of your class is instantiated, but might happen earlier. If you want more control over exactly when the field is initialised, you could use Lazy<T>, e.g.:
{
static Lazy<SomeClass> a = new Lazy<SomeClass>(() => new Someclass("asfae"));
}
This way, you know that the initialisation of SomeClass will only happen the first time the field is accessed and its Value property called.
I think to understand your problem you need to know the difference between static constructors and type initializers, there is a great article from Jon Skeet about this issue:
http://csharpindepth.com/Articles/General/Beforefieldinit.aspx
The point is that following constructions are not the same, and there are difference in the behavior:
class Test
{
static object o = new object();
}
class Test
{
static object o;
static Test()
{
o = new object();
}
}
In any case, you could try to create a static constructor for your class to be able to have more control on this initialization, and maybe the warning will disappear.
If the member is only used by a static method, and only by this one, I would recommend you to put it in the scope if this static method and not as class member.
I've following piece of code which implements the singleton class (Double-Check Locking)
public sealed class Plugin
{
#region Private Fields
private static volatile Plugin _instance;
private static object syncRoot = new Object();
private Dictionary<int, string> myMap;
#endregion
private Plugin()
{
myMap = MapInit(GetMainModuleName());
}
static Plugin()
{ }
public static Plugin Instance
{
get
{
if (_instance == null)
{
lock (syncRoot)
{
if (_instance == null)
_instance = new Plugin();
}
}
return _instance;
}
}
}
The singleton instance is constructed properly in the debug mode, and everything seems to be working fine. But in the release mode, the instance is returned before it is constructed properly i.e., the myMap is not initialized.
Also it is to be noted that following code takes around 10 -15 secs to be executed completely in debug mode
myMap = MapInit(GetMainModuleName());
Is this the problem with some compiler optimization? Please help
You don't need Singleton, in fact you don't do Singleton. Why is people doing singleton these days?
Look, this simply works:
public sealed class Plugin
{
private static readonly Plugin _instance;
private /*readonly?*/ Dictionary<int, string> myMap;
private Plugin()
{
myMap = MapInit(GetMainModuleName());
}
static Plugin()
{
_instance = new Plugin();
}
public static Plugin Instance
{
get
{
return _instance;
}
}
}
Static constructors are guaranteed to run only once per application domain, this is part of the C# language specification.
To address your question, there is a problem with the double check pattern as you has shown it doesn't work with compiler optimization when the machine has more than one thread in hardware. The reason for this is that...
[from http://blogs.msdn.com/b/brada/archive/2004/05/12/130935.aspx ]
the memory model allows for non-volatile reads\writes to be reordered
as long as that change can not be noticed from the point of view of a
single thread.
Even with volatile. The volatile keyword is telling the compiler that writing to the field _instance must be done after reading the field _instance. And yet nothing prevents it from initilizing the new Plugin object before reading the value of _instance in first place.
Aside from that you said you are facing another problem:
the instance is returned before it is constructed properly
Then you need to wait for the initialization to complete, and not just check if it has started. Aparently the field _instance has been set before the constructor of the class Plugin ends, if that is the case, it means that you need to wait until its complete. Also if have some asynchonous calls there you may need to add a "ready" property or some other way to wait [It would be your fault to allow an object to be in an invalid state].
*: This is often solved introducing a temporal variable, to which you set the new instance and the you assing that variable to your field. That technique also allows to make the field non-volatile by adding a memory barrier... and yet, it increases the risk of having your constructor run more than once. So, I've skipped all that.
To address both problems you can use this combination of Interlocked and ManualResetEvent [Without knowing the internals of the constructor I doubt I can do more]:
public sealed class Plugin
{
private static readonly Plugin _instance;
private static int _initializing;
private static ManualReserEvent _done;
private Dictionary<int, string> myMap;
private Plugin()
{
myMap = MapInit(GetMainModuleName());
}
static Plugin()
{
_done = new ManualResetEvent(false);
}
public static Plugin Instance
{
get
{
if (Interlocked.CompareExchance(ref _initializing, 1, 0) == 0)
{
_instance = new Plugin();
_done.Set();
}
else
{
_done.WaitOne();
}
return _instance;
}
}
}
Even though... just use the static constructor.
Ok, here's the actual problem which may sound naive. The dll with the above code was loaded into the main application which had a exe.config which was invalid. And since my dll had seperate dll.config(which is valid) the application was working fine when run through the debugger, but when run in deployment enviroment(without debugger attached), it was encountering the invalid config file exception.
I've made the main exe.config as valid config file and it works now.
So basically , the solution is as naive as checking if there is exception in the construction process.