I have a class which will only ever have a single instance at a time. It's essentially a singleton that is destroyed when no external references are held and re-instantiated when you need a new reference later.
private static readonly WeakReference<Foo> weakInstance = new WeakReference<Foo>(null);
The reason for the above code is because I have native iOS callbacks (which must be static functions) but which need to pass data to the current instance.
tl;dr Is it safe to initialise a WeakReference to null and set the target later? Is this a code smell?
Edit:
As #smolchanovsky pointed out, I could just instantiate the weak reference when I need to set it. This results in:
if (weakInstance == null)
{
weakInstance = new WeakReference<Foo>(this);
}
else
{
weakInstance.SetTarget(this);
}
or
// Overwrite the existing WeakReference object
weakInstance = new WeakReference<Foo>(this);
Is there a reason to pick one of these over the other?
Why not use this?
public sealed class Singleton
{
private static WeakReference<Singleton> weakInstance;
public WeakReference<Singleton> Instance
{
get
{
if (weakInstance == null)
weakInstance = new WeakReference<Singleton>(this);
else
weakInstance.SetTarget(this);
return weakInstance;
}
}
}
Note that this isn't a thread safe solution.
Related
I'm developing a multithread application in C#.
I've a resource I want to initialize when a first thread needs it.
This resource is able to be used by as many threads as it's necessary.
I need to detect, when this resource is free (there is any thread using it) in order to destroy it, and later, when another thread requests it, initialize it again.
Any ideas?
You could do something like the following:
public class SomeClass // basic class for example
{
public void foo() { }
public void Close()
{
// release any resources you might have open
}
}
public static class SingletonInstance
{
private static object m_lock = new object();
private static SomeClass m_instance = null;
private static int m_counter = 0;
public static SomeClass Instance
{
get
{
lock (m_lock) {
if (m_instance == null) {
m_instance = new SomeClass();
}
++m_counter;
}
return m_instance;
}
set
{
lock (m_lock) {
if (m_counter > 0 && --m_counter == 0) {
m_instance.Close();
m_instance = null;
}
}
}
}
}
And then in some other initialization code you could simply say SingletonInstance.Instance = null; to have the SingletonInstance be statically initialized (since static classes are initialized on the first call to them). Calling SingletonInstance.Instance = null; before any thread code will ensure no race conditions happen on the static init of the class; that is, if 2 threads call SingletonInstance.Instance.foo();, you can still have a race condition as to who initialized the class first.
Then in your thread code you could do something like the following:
void MyThreadFunction()
{
SingletonInstance.Instance.foo();
// ... more thread code ...
SingletonInstance.Instance = null;
}
This is a very basic example though, more to illustrate the point and your needs might be slightly different, but the idea is the same.
Hope that can help.
You could wrap your resource in a singleton handler which will destroy it when it is not referenced any longer by any threads.
You can look here for example for how to create such multi-threaded singleton objects. Initialize the resource when the object is created and liberate it in its destructor.
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'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.
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.
In a C# app, suppose I have a single global class that contains some configuration items, like so :
public class Options
{
int myConfigInt;
string myConfigString;
..etc.
}
static Options GlobalOptions;
the members of this class will be uses across different threads :
Thread1: GlobalOptions.myConfigString = blah;
while
Thread2: string thingie = GlobalOptions.myConfigString;
Using a lock for access to the GlobalOptions object would also unnecessary block when 2 threads are accessing different members, but on the other hand creating a sync-object for every member seems a bit over the top too.
Also, using a lock on the global options would make my code less nice I think;
if I have to write
string stringiwanttouse;
lock(GlobalOptions)
{
stringiwanttouse = GlobalOptions.myConfigString;
}
everywhere (and is this thread-safe or is stringiwanttouse now just a pointer to myConfigString ? Yeah, I'm new to C#....) instead of
string stringiwanttouse = GlobalOptions.myConfigString;
it makes the code look horrible.
So...
What is the best (and simplest!) way to ensure thread-safety ?
You could wrap the field in question (myConfigString in this case) in a Property, and have code in the Get/Set that uses either a Monitor.Lock or a Mutex. Then, accessing the property only locks that single field, and doesn't lock the whole class.
Edit: adding code
private static object obj = new object(); // only used for locking
public static string MyConfigString {
get {
lock(obj)
{
return myConfigstring;
}
}
set {
lock(obj)
{
myConfigstring = value;
}
}
}
The following was written before the OP's edit:
public static class Options
{
private static int _myConfigInt;
private static string _myConfigString;
private static bool _initialized = false;
private static object _locker = new object();
private static void InitializeIfNeeded()
{
if (!_initialized) {
lock (_locker) {
if (!_initialized) {
ReadConfiguration();
_initalized = true;
}
}
}
}
private static void ReadConfiguration() { // ... }
public static int MyConfigInt {
get {
InitializeIfNeeded();
return _myConfigInt;
}
}
public static string MyConfigString {
get {
InitializeIfNeeded();
return _myConfigstring;
}
}
//..etc.
}
After that edit, I can say that you should do something like the above, and only set configuration in one place - the configuration class. That way, it will be the only class modifying the configuration at runtime, and only when a configuration option is to be retrieved.
Your configurations may be 'global', but they should not be exposed as a global variable. If configurations don't change, they should be used to construct the objects that need the information - either manually or through a factory object. If they can change, then an object that watches the configuration file/database/whatever and implements the Observer pattern should be used.
Global variables (even those that happen to be a class instance) are a Bad Thing™
What do you mean by thread safety here? It's not the global object that needs to be thread safe, it is the accessing code. If two threads write to a member variable near the same instant, one of them will "win", but is that a problem? If your client code depends on the global value staying constant until it is done with some unit of processing, then you will need to create a synchronization object for each property that needs to be locked. There isn't any great way around that. You could just cache a local copy of the value to avoid problems, but the applicability of that fix will depend on your circumstances. Also, I wouldn't create a synch object for each property by default, but instead as you realize you will need it.