Is Structuremap singleton thread safe? - c#

Currently I have the following class:
public class PluginManager
{
private static bool s_initialized;
private static object s_lock = new object();
public static void Initialize() {
if (!s_initialized) {
lock (s_lock) {
if (!s_initialized) {
// initialize
s_initialized = true;
}
}
}
}
}
The important thing here is that Initialize() should only be executed once whilst the application is running. I thought that I would refactor this into a singleton class since this would be more thread safe?:
public sealed class PluginService
{
static PluginService() { }
private static PluginService _instance = new PluginService();
public static PluginService Instance { get { return _instance; } }
private bool s_initialized;
public void Initialize() {
if (!s_initialized)
{
// initialize
s_initialized = true;
}
}
}
Question one, is it still necessary to have the lock here (I have removed it) since we will only ever be working on the same instance?
Finally, I want to use DI and structure map to initialize my servcices so I have refactored as below:
public interface IPluginService {
void Initialize();
}
public class NewPluginService : IPluginService
{
private bool s_initialized;
public void Initialize() {
if (!s_initialized) {
// initialize
s_initialized = true;
}
}
}
And in my registry:
ForRequestedType<IPluginService>()
.TheDefaultIsConcreteType<NewPluginService>().AsSingletons();
This works as expected (singleton returning true in the following code):
var instance1 = ObjectFactory.GetInstance<IPluginService>();
var instance2 = ObjectFactory.GetInstance<IPluginService>();
bool singleton = (instance1 == instance2);
So my next question, is the structure map solution as thread safe as the singleton class (second example). The only downside is that this would still allow NewPluginService to be instantiated directly (if not using structure map).
Many thanks,
Ben

I would make several recommendations:
the boolean flag should be volatile
make your singleton instance readonly
the initialization is not thread safe, regardless of the fact that you have only one instance... so it should be synchronized
public sealded class PluginService
{
static PluginService() { }
//make the instance readonly
private static readonly PluginService _instance = new PluginService();
public static PluginService Instance { get { return _instance; } }
// make the flag volatile
private static volatile bool s_initialized = false;
private static object s_lock = new object();
// you still need to synchronize when you're initializing
public void Initialize() {
lock(s_lock)
{
if (!s_initialized)
{
// initialize
s_initialized = true;
}
}
}
}
There is no contention on the structured map, so its thread safety doesn't seem compromised...
The singleton class you had was not thread safe. The main thing to remember is that a single instance does not ensure a single thread can only access it. If there are multiple threads that have a reference to the instance, then there is contention on the instance and the data it's holding. If there is contention then you should ensure thread safety (synchronize at the very minimum).

Related

What can I do for a static class to be reloaded/reinstantiated?

An application I work with has a static class that loads some configuration from XML files in its constructor.
But when we make changes to one of these XML's, this class is not reloaded (as it should be, since it is static).
What can I do for this static class to be instantiated again, reloading the configuration?
Would I need to restart the IIS server? Are there some other ways?
Probably better to use a Singleton pattern with locks and with data invalidation
(typed in here so sorry in any syntax is wrong)
public class MySingleton
{
private static MySingleton _instance;
private static object _lock = new object();
private static MySingleton
{
// initialize here
}
public static MySingleton Instance
{
get
{
var singl = _instance;
if (singl != null)
return singl;
lock(_lock)
{
if (singl != null)
return singl;
_instance = new MySingleton();
return _instance;
}
}
}
public static void Invalidate()
{
lock(_lock)
{
_instance = null;
}
}
// -- your non-static methods
public bool CheckSomething(){ return true; }
}
use
// thread one
if (MySingleton.Instance.CheckSomething())
// my code
// thread two
MySingleton.Invalidate();

Thread-safe methods in the singleton class

The question is a follow-up to Thread - safe singelton
I have a following class :
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(string str,int i)
{
s_c1 = SingletonClass1.Instance(str);
s_c2 = SingletonClass2.Instance(str);
s_c3 = SingletonClass3.Instance(i);
}
// 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 SingletonClass2 s_c2 = null;
static SingletonClass3 s_c3 = null;
}
I started to implement it to have a constructor with arguments, but don`t know how to proceed. Any suggestions?
I was said in comments of previous question that func1 is not thread-safe.How to make it thread-safe? Is MyLazySingleton defined to be Lazy not for thread-safety?

Deallocate and re-instantiate new a singleton

I want to de-allocate the memory from the original singleton object and create a new one with another method.
public sealed class ObjectZ {
static readonly ObjectZ _instance = new ObjectZ();
private ObjectZ() {}
public static ObjectZ Instance{
get { return _instance; }
}
}
What would this method look like?
Singletons are usually created once and exist for the lifetime of the domain, recreating a singleton is dodgy business and by definition the code I've provided isn't truly a singleton.
The behaviour you seem to be after is a statically accessible single object cache that can be invalidated.
public static class SingletonAccessor
{
private static SomeClass _instance;
private static object _lock = new Object();
public static SomeClass Singleton
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new SomeClass();
}
return _instance;
}
}
}
public static void Recycle()
{
lock (_lock)
{
if (_instance != null)
{
// Do any cleanup, perhaps call .Dispose if it's needed
_instance = null;
}
}
}
}

ASP NET C# : Singleton with in Queue and thread worker on it

I need to create a single class instance in web application that manage a queue of process. This class have multiple thread inside that look for queue and consume it.
What is the best why to do this?
I have apply singleton design pattern, but I don't understand if have to create static or normal queue inside it. Some one can give me an example please?
SOLUTION
Ok thank you! This is my singleton class:
public sealed class MyWorkingSingletonClass
{
private static readonly ILog LOG = LogManager.GetLogger(typeof(MyWorkingSingletonClass));
private static MyWorkingSingletonClass instanza;
private static readonly object lockObject = new object();
private static ConcurrentQueue<Process> syncCoda = new ConcurrentQueue<Process>();
private MyWorkingSingletonClass()
{
}
public static MyWorkingSingletonClass Instanza
{
get
{
lock (lockObject)
{
if (instanza == null)
instanza = new PdfDucumentConverter();
return instanza;
}
}
}
public void AddProcess(Process p)
{
syncCoda.Enqueue(p);
}
public void Start()
{
Task.Factory.StartNew(WorkerTask2);
}
public static void WorkerTask2()
{
do
{
try
{
Process p;
if (syncCoda.TryDequeue(out p))
{
p.Start();
p.PriorityClass = ProcessPriorityClass.High;
p.WaitForExit();
}
}
catch (Exception ex)
{
LOG.Error(ex);
}
} while (true);
}
}
What you need is to implement new singleton class which inherits Concurrent Queue class which is thread-safe queue to ensure it will work in multi-thread environment:
public class SingletonConcurrentQueue<T> : ConcurrentQueue<T>
{
private static readonly SingletonConcurrentQueue<T>
_instance = new SingletonConcurrentQueue<T>();
static SingletonConcurrentQueue(){}
private SingletonConcurrentQueue(){}
public static SingletonConcurrentQueue<T> Instance
{
get { return _instance; }
}
}

Thread safety of C# singleton instance in ApplicationState

I have a bit of code that I've been trying to examine for thread safety. I'm using the basic lazy singleton model found here. I was wondering if it is still thread safe if I'm putting the instance in the HttpApplicationState object. I need to access this instance across all instances of the web application, so if this is not thread safe how can I make it thread safe?
public sealed class EmailWorker {
private HttpApplicationState _app;
private const EMAIL_WORKER = "EmailWorker";
EmailWorker() { }
class NestedWorker {
static NestedWorker() { }
internal static readonly EmailWorker Instance = new EmailWorker();
}
public static void Initialize(HttpApplicationState appState) {
_appState = appState;
_appState.Lock();
if (_appState[EMAIL_WORKER] == null) {
_appState.Add(EMAIL_WORKER, NestedWorker.Instance);
}
_appState.UnLock();
}
public static EmailWorker Instance {
get {
// TODO: If we haven't called Initialize() first then throw exception
return (EmailWorker)_appState[EMAIL_WORKER];
}
}
}
You don't need to use Application state at all.
It should be thread-safe, but why bother?
A "standard" singleton will also be accessible across the entire application, and it won't require injecting and keeping a reference to the HttpApplicationState:
public sealed class EmailWorker
{
private EmailWorker() { }
private static class NestedWorker
{
static NestedWorker() { }
internal static readonly EmailWorker Instance = new EmailWorker();
}
public static EmailWorker Instance
{
get { return NestedWorker.Instance; }
}
}

Categories

Resources