(C#) Class member initializing thread-safety issue - c#

Comparing 2 ways of class property defenition (A & B):
// implemention A
public class Cache {
private object m_syncRoot = null;
public object SyncRoot {
get {
if (m_syncRoot == null) {
Interlocked.CompareExchange(ref m_syncRoot, new object(), null);
}
return m_syncRoot;
}
}
}
AND
// implemention B.
public class Cache {
public object SyncRoot { get; } = new object(); // in C# 6.0
}
And finally some where uses cache:
static Cache MyCache = new Cache(); // I don't know if this kind of declaration is thread-safe either
lock (MyCache.SyncRoot) {
....
}
Question:
Since "Cache" will be used as static instance, are both "SyncRoot" creations in [A] & [B] thread-safe ?

Yes, both of the two creation are thread-safe. The difference is in implementation B, the SyncRoot object is created when the Cache instance is created. And in A, SyncRoot is created when it is accessed.

Related

Is it okay to initialise WeakReference with a null value?

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.

Singleton Factory to produces multiple singleton instances [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have two singleton classes in my project.
public class VStateManager : IVState
{
private static readonly object _createLock = new object();
private static VStateManager _vsManager = null;
public static VStateManager GetVStateManager()
{
lock (_createLock)
{
if (_vsManager == null)
{
return new VStateManager();
}
return _vsManager;
}
}
}
public class VTRFactory : IVTR
{
private static VehicleFactory _VTRFactory =null;
private static readonly object _createLock = new object();
public static VehicleFactory GetVTRFactory()
{
lock(_createLock)
{
if(_VTRFactory == null)
{
return new VTRFactory();
}
return _VTRFactory;
}
}
}
My colleague suggested to create a singleton class (something like a singleton factory) that accepts a generic interface and produces both these singleton objects
How can this be done.?
First of all, your classes aren't implementing singleton at all. Look at this:
if (_vsManager == null)
{
return new VStateManager();
}
return _vsManager;
_vsManager will be always null, so multiple instances will be created each time you access the instance. It should be:
if (_vsManager == null)
{
_vsManager = new VStateManager();
}
return _vsManager;
That's the way you ensure only one instance will be created.
Also, I would use a property instead of a function, it's more clear:
public class VStateManager : IVState
{
private static readonly object _createLock = new object();
private static VStateManager _vsManager = null;
public static VStateManager Instance
{
get
{
lock (_createLock)
{
if (_vsManager == null)
{
_vsManager = new VStateManager();
}
return _vsManager;
}
}
}
}
Then you can use per example VStateManager.Instance.XXX.
Second, why you need a third class to create those singletons? When you need to use them accessing GetXXXX would create the needed instance, is there any reason to create those instances before you need them?
If you really need those instances to be initialized before they are needed then you can do something very simple like this:
public static class Initializer()
{
public static void Init()
{
var a = VStateManager.GetVStateManager();
var b = VehicleFactory.GetVTRFactory();
}
}
Then to initialize just call Initializer.Init(). Overcomplicating the code without any reason is the root of all evil in programming, don't try to solve a problem that doesn't exists as that solution can create real problems.
The singleton factory you are looking for can be created using generics. You need to pass the type for which you need to create a singleton instance and the factory will return an instance of that type with making sure that only one instance of that type is created.
The very basic implementation of such singleton factory would look as following.
public static class SingletonFactory
{
private static readonly object lockObject = new object();
//Dictionary to store the singleton objects
private static readonly Dictionary<string, object> singletonObjects = new Dictionary<string, object>();
// Method to retrieve singleton instance.
// Note the constraint "new ()". This indicates that this method can be called for the types which has default constructor.
public static T GetSingletoneInstance<T>() where T:new ()
{
var typeName = typeof(T).Name;
T instance;
lock (lockObject)
{
// Check in the dictionary if the instance already exist.
if (singletonObjects.ContainsKey(typeName))
{
//Retrieve the instance from the dictionary.
instance = (T) singletonObjects[typeName];
}
else
{
// If it does not exist in the dictionary,
// create a new instance
// and store it in the dictionary.
lock (lockObject)
{
instance = new T();
singletonObjects.Add(typeName, instance);
}
}
}
// Return the instance of type "T" either retrieved from dictionary
// or the newly created one.
return instance;
}
}
Following is how you use this factory.
class Program
{
static void Main(string[] args)
{
var vstateManager = SingletonFactory.GetSingletoneInstance<VStateManager>();
var vehicleFactory = SingletonFactory.GetSingletoneInstance<VehicleFactory>();
Console.ReadKey();
}
}
The implementation of SingletonFactory is a very basic version. And it has limitation that it can be used only for the types which have default constructor.
But it can be further extended to use DI module to initialize the instances without worrying about their constructors. Also it can be extended to store the instances in somewhere else then dictionary such as cache, memcaches or database.
I hope this would help you get whatever you are looking for.

Initialize a resource and destroy it until another thread needs it

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.

Singleton in current thread

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]

What's the use of the SyncRoot pattern?

I'm reading a c# book that describes the SyncRoot pattern. It shows
void doThis()
{
lock(this){ ... }
}
void doThat()
{
lock(this){ ... }
}
and compares to the SyncRoot pattern:
object syncRoot = new object();
void doThis()
{
lock(syncRoot ){ ... }
}
void doThat()
{
lock(syncRoot){ ... }
}
However, I don't really understand the difference here; it seems that in both cases both methods can only be accessed by one thread at a time.
The book describes ... because the object of the instance can also be used for synchronized access from the outside and you can't control this form the class itself, you can use the SyncRoot pattern Eh? 'object of the instance'?
Can anyone tell me the difference between the two approaches above?
If you have an internal data structure that you want to prevent simultaneous access to by multiple threads, you should always make sure the object you're locking on is not public.
The reasoning behind this is that a public object can be locked by anyone, and thus you can create deadlocks because you're not in total control of the locking pattern.
This means that locking on this is not an option, since anyone can lock on that object. Likewise, you should not lock on something you expose to the outside world.
Which means that the best solution is to use an internal object, and thus the tip is to just use Object.
Locking data structures is something you really need to have full control over, otherwise you risk setting up a scenario for deadlocking, which can be very problematic to handle.
The actual purpose of this pattern is implementing correct synchronization with wrappers hierarchy.
For example, if class WrapperA wraps an instance of ClassThanNeedsToBeSynced, and class WrapperB wraps the same instance of ClassThanNeedsToBeSynced, you can't lock on WrapperA or WrapperB, since if you lock on WrapperA, lock on WrappedB won't wait.
For this reason you must lock on wrapperAInst.SyncRoot and wrapperBInst.SyncRoot, which delegate lock to ClassThanNeedsToBeSynced's one.
Example:
public interface ISynchronized
{
object SyncRoot { get; }
}
public class SynchronizationCriticalClass : ISynchronized
{
public object SyncRoot
{
// you can return this, because this class wraps nothing.
get { return this; }
}
}
public class WrapperA : ISynchronized
{
ISynchronized subClass;
public WrapperA(ISynchronized subClass)
{
this.subClass = subClass;
}
public object SyncRoot
{
// you should return SyncRoot of underlying class.
get { return subClass.SyncRoot; }
}
}
public class WrapperB : ISynchronized
{
ISynchronized subClass;
public WrapperB(ISynchronized subClass)
{
this.subClass = subClass;
}
public object SyncRoot
{
// you should return SyncRoot of underlying class.
get { return subClass.SyncRoot; }
}
}
// Run
class MainClass
{
delegate void DoSomethingAsyncDelegate(ISynchronized obj);
public static void Main(string[] args)
{
SynchronizationCriticalClass rootClass = new SynchronizationCriticalClass();
WrapperA wrapperA = new WrapperA(rootClass);
WrapperB wrapperB = new WrapperB(rootClass);
// Do some async work with them to test synchronization.
//Works good.
DoSomethingAsyncDelegate work = new DoSomethingAsyncDelegate(DoSomethingAsyncCorrectly);
work.BeginInvoke(wrapperA, null, null);
work.BeginInvoke(wrapperB, null, null);
// Works wrong.
work = new DoSomethingAsyncDelegate(DoSomethingAsyncIncorrectly);
work.BeginInvoke(wrapperA, null, null);
work.BeginInvoke(wrapperB, null, null);
}
static void DoSomethingAsyncCorrectly(ISynchronized obj)
{
lock (obj.SyncRoot)
{
// Do something with obj
}
}
// This works wrong! obj is locked but not the underlaying object!
static void DoSomethingAsyncIncorrectly(ISynchronized obj)
{
lock (obj)
{
// Do something with obj
}
}
}
Here is an example :
class ILockMySelf
{
public void doThat()
{
lock (this)
{
// Don't actually need anything here.
// In this example this will never be reached.
}
}
}
class WeveGotAProblem
{
ILockMySelf anObjectIShouldntUseToLock = new ILockMySelf();
public void doThis()
{
lock (anObjectIShouldntUseToLock)
{
// doThat will wait for the lock to be released to finish the thread
var thread = new Thread(x => anObjectIShouldntUseToLock.doThat());
thread.Start();
// doThis will wait for the thread to finish to release the lock
thread.Join();
}
}
}
You see that the second class can use an instance of the first one in a lock statement. This leads to a deadlock in the example.
The correct SyncRoot implementation is:
object syncRoot = new object();
void doThis()
{
lock(syncRoot ){ ... }
}
void doThat()
{
lock(syncRoot ){ ... }
}
as syncRoot is a private field, you don't have to worry about external use of this object.
Here's one other interesting thing related to this topic:
Questionable value of SyncRoot on Collections (by Brad Adams):
You’ll notice a SyncRoot property on many of the Collections in System.Collections. In retrospeced (sic), I think this property was a mistake. Krzysztof Cwalina, a Program Manger on my team, just sent me some thoughts on why that is – I agree with him:
We found the SyncRoot-based synchronization APIs to be insufficiently flexible for most scenarios. The APIs allow for thread safe access to a single member of a collection. The problem is that there are numerous scenarios where you need to lock on multiple operations (for example remove one item and add another). In other words, it’s usually the code that uses a collection that wants to choose (and can actually implement) the right synchronization policy, not the collection itself. We found that SyncRoot is actually used very rarely and in cases where it is used, it actually does not add much value. In cases where it’s not used, it is just an annoyance to implementers of ICollection.
Rest assured we will not make the same mistake as we build the generic versions of these collections.
See this Jeff Richter's article. More specifically, this example which demonstrates that locking on "this" can cause a deadlock:
using System;
using System.Threading;
class App {
static void Main() {
// Construct an instance of the App object
App a = new App();
// This malicious code enters a lock on
// the object but never exits the lock
Monitor.Enter(a);
// For demonstration purposes, let's release the
// root to this object and force a garbage collection
a = null;
GC.Collect();
// For demonstration purposes, wait until all Finalize
// methods have completed their execution - deadlock!
GC.WaitForPendingFinalizers();
// We never get to the line of code below!
Console.WriteLine("Leaving Main");
}
// This is the App type's Finalize method
~App() {
// For demonstration purposes, have the CLR's
// Finalizer thread attempt to lock the object.
// NOTE: Since the Main thread owns the lock,
// the Finalizer thread is deadlocked!
lock (this) {
// Pretend to do something in here...
}
}
}
Another concrete example:
class Program
{
public class Test
{
public string DoThis()
{
lock (this)
{
return "got it!";
}
}
}
public delegate string Something();
static void Main(string[] args)
{
var test = new Test();
Something call = test.DoThis;
//Holding lock from _outside_ the class
IAsyncResult async;
lock (test)
{
//Calling method on another thread.
async = call.BeginInvoke(null, null);
}
async.AsyncWaitHandle.WaitOne();
string result = call.EndInvoke(async);
lock (test)
{
async = call.BeginInvoke(null, null);
async.AsyncWaitHandle.WaitOne();
}
result = call.EndInvoke(async);
}
}
In this example, the first call will succeed, but if you trace in the debugger the call to DoSomething will block until the lock is release. The second call will deadlock, since the Main thread is holding the monitor lock on test.
The issue is that Main can lock the object instance, which means that it can keep the instance from doing anything that the object thinks should be synchronized. The point being that the object itself knows what requires locking, and outside interference is just asking for trouble. That's why the pattern of having a private member variable that you can use exclusively for synchronization without having to worry about outside interference.
The same goes for the equivalent static pattern:
class Program
{
public static class Test
{
public static string DoThis()
{
lock (typeof(Test))
{
return "got it!";
}
}
}
public delegate string Something();
static void Main(string[] args)
{
Something call =Test.DoThis;
//Holding lock from _outside_ the class
IAsyncResult async;
lock (typeof(Test))
{
//Calling method on another thread.
async = call.BeginInvoke(null, null);
}
async.AsyncWaitHandle.WaitOne();
string result = call.EndInvoke(async);
lock (typeof(Test))
{
async = call.BeginInvoke(null, null);
async.AsyncWaitHandle.WaitOne();
}
result = call.EndInvoke(async);
}
}
Use a private static object to synchronize on, not the Type.

Categories

Resources