Singleton management implementation and thread safety - c#

I have been playing around with ways to implement Singletons. I have written a little management object that allows for a easier, less code approach to writing singleton classes.
I would never use something like this in a production system for a couple of reason which lead me to my question.
With the below code - I am assuming that this implementation would/could lead to both threading issues and memory leaks? Would I be correct?
namespace ConsoleApplication1
{
public static class SingletonManager
{
private static readonly Dictionary<string, object> Objects;
static SingletonManager()
{
Objects = new Dictionary<string, object>();
}
public static T InstanceOf<T>(object[] ctorArgs = null)
where T : class
{
var name = typeof (T).FullName;
if (Objects.ContainsKey(name))
return Objects[name] as T;
var ctor = typeof (T).GetConstructors(
BindingFlags.Instance |
BindingFlags.NonPublic)[0];
var instance = ctor.Invoke(ctorArgs) as T;
Objects[name] = instance;
return instance as T;
}
public static void DisposeOf<T>()
where T : Singleton<T>
{
Dispose(typeof (T).FullName);
}
public static void DisposeOf(Type type)
{
Dispose(type.FullName);
}
private static void Dispose(string name)
{
if (!Objects.ContainsKey(name)) return;
var obj = Objects[name];
if (obj is IDisposable)
((IDisposable) Objects[name]).Dispose();
Objects.Remove(name);
}
}
public class Singleton<T>
where T : class
{
private static object ThreadLock = new object();
public static T Instance(object[] ctorArgs = null)
{
lock (ThreadLock)
{
return SingletonManager.InstanceOf<T>(ctorArgs);
}
}
}
public class SomeSingletonClass : Singleton<SomeSingletonClass>
{
public int Number;
private SomeSingletonClass(int i)
{
Number = i;
}
}
internal class Program
{
private static void Main(string[] args)
{
var instance1= SomeSingletonClass.Instance(new object[] {1});
var instance2 = SomeSingletonClass.Instance(new object[] { 2 });
//Is false
var updated = instance1.Number == 2;
instance2.Number = 99;
//Is true
var equals = instance1.Number == instance2.Number;
//Is true
var refEquals = ReferenceEquals(instance1, instance2);
Debugger.Break();
}
}
}

Classical singletons are very rarely a good idea. In most cases you're better off with simply creating a single instance which you pass to the code that needs it, instead of enforcing that there is only one. An IoC container will do most of that work for you.
An implementation of a classical singleton is quite compact, no need to simplify it further:
public class MySingleton
{
private static Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton());
public static MySingleton Instance { get { return _instance.Value; } }
private MySingleton()
{
}
}
At best you can save two of these lines.
Yes, your code is not thread safe. You'd need to put most of it in lock statements to fix that.
The consumer determining the constructor parameters is very dubious. Unless all of them are identical, you'll end up with different instances, depending on which consumer runs first.
This violates the "single source of truth" principle and is a maintenance and debugging nightmare.
Your code relies on private reflection.

Related

Automatically calling an init function whenever an object is used for the 1st time

I have an object that only initializes itself with barebones data when constructed (fast), and loads itself for real (slow) when first accessed. The idea is that I'm creating a lot of these barebones objects at startup and hash them into a map, then fully load each object whenever it is individually accessed for the first time. The problem is that I cannot guarantee how clients will interact with this object, there are multiple public methods that might be invoked.
Is there a good pattern to support this kind of situation? The obvious (and my current) solution is to track state with an internal bool, check against that bool in every function that might be invoked, and load that way. But that requires code duplication of that behavior across all public functions, and is vulnerable to errors.
I can imagine a single point-of-entry method that then dishes out behaviors based on a client request type etc., but before I go consider going down that road I want to see if there's a commonly accepted approach/pattern that I might not be aware of. I'm doing this in C#, but any insight is appreciated.
If I understood what you want to achieve, you are looking for the Proxy Design Pattern, more specifically, a virtual Proxy.
Refer to http://www.dofactory.com/net/proxy-design-pattern
A small example would be something like:
public abstract class IObjectProvider
{
public abstract IObjectProvider Object{get;}
public abstract void doStuff();
}
public class RealObject : IObjectProvider
{
public RealObject()
{
//Do very complicated and time taking stuff;
}
public override IObjectProvider Object
{
get { return this; }
}
public override void doStuff()
{
//do this stuff that these objects normally do
}
}
public class ObjectProxy : IObjectProvider
{
private IObjectProvider objectInstance = null;
public override IObjectProvider Object
{
get
{
if (objectInstance == null)
objectInstance = new RealObject();
return objectInstance;
}
}
public override void doStuff()
{
if(objectInstance!=null)
objectInstance.doStuff();
}
}
public class SkeletonClass
{
public IObjectProvider Proxy1 = new ObjectProxy();
public IObjectProvider Proxy2 = new ObjectProxy();
}
static void Main(String[] args)
{
//Objects Not Loaded
SkeletonClass skeleton = new SkeletonClass();
//Proxy1 loads object1 on demand
skeleton.Proxy1.Object.doStuff();
//Proxy2 not loaded object2 until someone needs it
}
Here's an example of dynamic proxy approach.
using System;
using System.Diagnostics;
using Castle.DynamicProxy; //Remember to include a reference, too. It's nugettable package is Castle.Core
namespace ConsoleApp
{
public class ActualClass
{
//Have static instances of two below for performance
private static ProxyGenerator pg = new ProxyGenerator();
private static ActualClassInterceptor interceptor = new ActualClassInterceptor();
//This is how we get ActualClass items that are wrapped in the Dynamic Proxy
public static ActualClass getActualClassInstance()
{
ActualClass instance = new ActualClass();
return pg.CreateClassProxyWithTarget<ActualClass>(instance, interceptor);
}
//Tracking whether init has been called
private bool initialized = false;
//Will be used as evidence of true initialization, i.e. no longer null
private int? someValue = null;
public void Initialize()
{
if (!initialized)
{
//do some initialization here.
someValue = -1; //Will only get set to non-null if we've run this line.
initialized = true;
}
}
//Any methods you want to intercept need to be virtual!
public virtual int replaceValue(int value)
{
//below will blow up, if someValue has not been set to -1 via Initialize();
int oldValue = someValue.Value;
someValue = value;
return oldValue;
}
//block off constructor from public to enforce use of getActualClassInstance
protected ActualClass() { }
}
public class ActualClassInterceptor : ActualClass, IInterceptor
{
public void Intercept(IInvocation invocation)
{
//Call initialize before proceeding to call the intercepted method
//Worth noting that this is the only place we actually call Initialize()
((ActualClass)invocation.InvocationTarget).Initialize();
invocation.Proceed();
}
}
class Program
{
static void Main(string[] args)
{
ActualClass instance1 = ActualClass.getActualClassInstance();
ActualClass instance2 = ActualClass.getActualClassInstance();
int x1 = instance1.replaceValue(41);
int x2 = instance2.replaceValue(42);
int y1 = instance1.replaceValue(82);
Debug.Assert(y1 == 41);
int y2 = instance2.replaceValue(84);
Debug.Assert(y2 == 42);
var read = Console.ReadKey();
}
}
}

Singleton class for an object with parameters

I realized that I should have only one instance of an object called StdSchedulerFactory running at a time. So far I instantiated the object like this
StdSchedulerFactory sf = new StdSchedulerFactory(properties);
And properties is a NameValueCollection.
How can I write a Singleton class for this object so that the variable sf will always have one instance throughout the program?
Part of the Singleton pattern is typically a private constructor, so that other classes can not make new instances.
The workaround for parameters coming from outside the class is to add a "Init" or "Configure" function:
public static void Configure(NameValueCollection properties)
{
}
Of course, if you forget to call this function, you may get behavior you don't want; so you may want to set a "Configured" flag or something like that so your other functions can react appropriately if this function has not yet been called.
Here is a basic Singleton implementation. It is not thread-safe.
public sealed class StdSchedulerFactory
{
private static readonly StdSchedulerFactory instance;
private NameValueCollection _properties;
private StdSchedulerFactory(NameValueCollection properties)
{
_properties = properties;
}
public static StdSchedulerFactory GetInstance(NameValueCollection properties)
{
if (instance == null)
{
instance = new StdSchedulerFactory(properties);
}
else
{
return instance;
}
}
}
this is my two favorite way implementing simple singleton pattern. The second one is just easier when debugging :)
public sealed class SingletonOne
{
private static readonly Lazy<SingletonOne> instance = new Lazy<SingletonOne>(() => new SingletonOne());
private Lazy<Controller> controller = new Lazy<Controller>(() => new Controller(properties));
private static object properties = null;
public static SingletonOne Instance { get { return instance.Value; } }
public Controller GetController(object properties)
{
SingletonOne.properties = properties;
return this.controller.Value;
}
}
public sealed class SingletonTwo
{
private static readonly SingletonTwo instance = new SingletonTwo();
private Controller controller;
private static object properties = null;
public static SingletonTwo Instance
{
get
{
return SingletonTwo.instance;
}
}
public Controller GetController(object properties)
{
SingletonTwo.properties = properties;
if(this.controller == null)
{
this.controller = new Controller(SingletonTwo.properties);
}
return this.controller;
}
}
public class Controller
{
public Controller(object properties) { }
}

Receiving dynamically changing classes

In my system I have 16 different classes alike used for statistics. They look like the following
public class myClass : myInheritage
{
private static myClass _instance;
public static myClass Instance
{
get { return _instance ?? (_instance = new myClass(); }
}
public static void Reset()
{
_instance = null;
}
}
They are all made into singletons
myInheritage looks like this:
public class myInheritage
{
int data = 0;
public myInheritage()
{
}
public int Data
{
get { return data; }
set { data+= value; }
}
}
The program is made, so the user chooses which class he wants to make statistics with.
Something like this is what I want
public void statistics(Object myObject, string name)
{
Object x = myObject;
x.Data = 10;
x.Data();
}
Called from another class
statistics(myClass.Instance, "myClass");
statistics(myClass2.Instance, "myClass2)";
So I want to dynamically change my instance in my statistics class.
Is that possible with .NET 2.0 ?
You could use reflection...
MethodInfo method = myObject.GetType().GetMethod("Reset");
if (method != null) method.Invoke(myObject, null);
If you can modify the classes themselves, a better approach might be to have each implement an interface (or base class) IResettable.
public interface IResettable
{
void Reset();
}
public class myClass : myInheritage, IResettable
{
public void Reset() { ... }
}
Then you could write the function against the interface:
public void statistics(IResettable myObject, string name)
{
myObject.Reset();
}
Yes. What you want here is a Strategy/Factory pattern. I name both as they could be used in conjunction for your case. There are great examples of these design patterns here and the following are detailed intros to the Strategy pattern and the Factory pattern. The former of the last two links also shows you how to combine the two to do exactly waht you require.
So in your case, you could set up the following interface
public interface IStatistics
{
// Some method used by all classes to impose statistics.
void ImposeStatistics();
}
Then in you singleton classes you could have
public class myClass : myInheritage, IStatistics
{
private static myClass _instance;
public static myClass Instance
{
get { return _instance ?? (_instance = new myClass()); }
}
public static void Reset()
{
_instance = null;
}
// You would also inherit from IStatistics in your other classes.
public void ImposeStatistics()
{
// Do stuff.
}
}
Then you would have a 'factory' class that imposes you stratgey at runtime.
public static class StatisticFactory
{
public static void ImposeStatistics(IStatistics statsType)
{
statsType.ImposeStatistics();
}
/// <summary>
/// Get the conversion type.
/// </summary>
/// <param name="col">The column to perform the conversion upon.</param>
public static IStatistics GetStatsType(string typeName)
{
switch (typeName)
{
case "BoseEinstein":
return new BoseEinsteinStats();
case "FermiDirac":
return new FermiDiracStats();
default:
return null;
}
}
}
You can then call this like
// Run stats.
IStatistics stats = StatisticFactory(GetStatsType("BoseEinstein"));
to get the statistics for the required class.
I hope this helps.

Initialization of static fields in C# generic types

I understood from this answer that C# static field initializers "are executed... prior to the first use of a static field of that class," but that still produces results I didn't expect, at least with generic types.
Coming from the Java world, I was missing my rich enums, and I thought with C#'s more serious generics that I ought to be able to replicate them with a minimum of boilerplate. Here (stripped of some details, like comparability) is what I came up with:
public class AbstractEnum<T> where T : AbstractEnum<T>
{
static readonly IDictionary<String, T> nameRegistry = new Dictionary<String, T>();
readonly String name;
protected AbstractEnum (String name)
{
this.name = name;
nameRegistry[name] = (T) this;
}
public String Name {
get {
return name;
}
}
public static T ValueOf(String name) {
return nameRegistry[name];
}
public static IEnumerable<T> Values {
get {
return nameRegistry.Values;
}
}
}
And some example subclasses:
public class SomeEnum : AbstractEnum<SomeEnum> {
public static readonly SomeEnum V1 = new SomeEnum("V1");
public static readonly SomeEnum V2 = new SomeEnum("V2");
SomeEnum(String name) : base(name) {
}
}
public class OtherEnum : AbstractEnum<OtherEnum> {
public static readonly OtherEnum V1 = new OtherEnum("V1");
public static readonly OtherEnum V2 = new OtherEnum("V2");
OtherEnum(String name) : base(name) {
}
}
This looks good and more or less does the trick... except that, following the letter of the spec, the actual instances (SomeEnum.V1, OtherEnum.V1 etc.) don't get initialized unless at least one of them is referred to explicitly. Static fields/methods in the base class don't count. So, for instance, the following:
Console.WriteLine("Count: {0}", SomeEnum.Values.Count());
foreach (SomeEnum e in SomeEnum.Values) {
Console.WriteLine(e.Name);
}
writes Count: 0, but if I add the following line --
Console.WriteLine("SomeEnum.V1: " + SomeEnum.V1.Name);
-- even after the above, I get:
Count: 2
V1
V2
(Note, by the way, that initializing the instances in a static constructor makes no difference.)
Now, I can fix this by marking nameRegistry as protected and pushing Values and ValueOf down into the subclasses, but I was hoping to keep all the complexity in the superclass and keep the boilerplate to a minimum. Can anyone whose C#-fu is superior to mine come up with a trick for making the subclass instances "self-executing"?
Note: FWIW, this is in Mono, on Mac OS. YM in MS .NET, on Windows, MV.
ETA: For monoglot C# developers (or even polyglot developers whose experience is limited to languages starting with 'C') wondering WTF I'm trying to do: this. C# enums take care of the type safety issue, but they're still missing everything else.
I came up with this - not entirely pleasing, but does do the job:
public static IEnumerable<T> Values
{
get
{
if (nameRegistry.Count > 0)
{
return nameRegistry.Values;
}
var aField = typeof (T).GetFields(
BindingFlags.Public | BindingFlags.Static)
.FirstOrDefault();
if (aField != null)
aField.GetValue(null);
return nameRegistry.Values;
}
}
EDIT Here's a slightly different version that should address VinayC's concerns in the comments. The problem was this: thread A calls Values(). While the static constructor of SomeEnum is running, after it's added V1 but before it adds V2, thread B calls values. In the code as originally written, it would be handed an IEnumerable that might only yield V1. So you could get incorrect results from Values() if a second thread calls during the very first call to Values() for any particular type.
The version below uses a boolean flag rather than relying on a non-zero count in nameRegistry. In this version it is still possible that the reflection code to run more than once, but no longer possible to get wrong answers from Values(), since by the time the reflection code completes, the nameRegistry is guaranteed to be fully initialized.
private static bool _initialized;
public static IEnumerable<T> Values
{
get
{
if (_initialized)
{
return nameRegistry.Values;
}
var aField = typeof(T).GetFields(
BindingFlags.Public | BindingFlags.Static)
.FirstOrDefault();
if (aField != null)
aField.GetValue(null);
_initialized = true;
return nameRegistry.Values;
}
}
Admittedly, I don't know what RichEnums are, but does this C# not do what you want?
public enum SomeEnum
{
V1,
V2
}
class Program
{
static void Main(string[] args)
{
var values = Enum.GetValues(typeof (SomeEnum));
Console.WriteLine("Count: {0}", values.Length);
foreach (SomeEnum e in values)
{
Console.WriteLine(e);
}
}
}
How about:
public class BaseRichEnum
{
public static InitializeAll()
{
foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
{
if (t.IsClass && !t.IsAbstract && typeof (BaseRichEnum).IsAssignableFrom(t))
{
t.GetMethod("Initialize").Invoke(null, null); //might want to use flags on GetMethod
}
}
}
}
public class AbstractEnum<T> : BaseRichEnum where T : AbstractEnum<T>
{
static readonly IDictionary<String, T> nameRegistry = new Dictionary<String, T>();
readonly String name;
protected AbstractEnum (String name)
{
this.name = name;
nameRegistry[name] = (T) this;
}
public String Name {
get {
return name;
}
}
public static T ValueOf(String name) {
return nameRegistry[name];
}
public static IEnumerable<T> Values {
get {
return nameRegistry.Values;
}
}
}
And then:
public class SomeEnum : AbstractEnum<SomeEnum>
{
public static readonly SomeEnum V1;
public static readonly SomeEnum V2;
public static void Initialize()
{
V1 = new SomeEnum("V1");
V2 = new SomeEnum("V2");
}
SomeEnum(String name) : base(name) {
}
}
Then you have to call BaseRichEnum.InitializeAll() in application startup code. I think it's better to impose this simple requirement on clients, thereby making visible the mechanism, than to expect future maintainers to grasp the subtleties of static-time initialization.
I don't like below solution as such but...
public class AbstractEnum<T> where T : AbstractEnum<T>
{
...
private static IEnumerable<T> ValuesInternal {
get {
return nameRegistry.Values;
}
}
public IEnumerable<T> Values {
get {
return ValuesInternal;
}
}
}
You have to use like SomeEnum.V1.Values - I know it sucks!
Yet another alternative that would involve some work is
public class AbstractEnum<T> where T : AbstractEnum<T>
{
...
protected static IEnumerable<T> ValuesInternal {
get {
return nameRegistry.Values;
}
}
}
public class SomeEnum : AbstractEnum<SomeEnum> {
...
public static IEnumerable<SomeEnum> Values
{
get
{
return ValuesInternal;
}
}
}
I would go with the second option.

c# singleton code reuse

I have a number of classes doing different things but using the same Singleton pattern from http://www.yoda.arachsys.com/csharp/singleton.html
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Does anyone have a neat way I can reuse as much of the common Singleton code as possible between the different classes?
For example if I have SingletonJob1 and SingletonJob2 I'd like to be able to change the code in only place if I move to one of the other Singleton patterns.
Edit: Yes as people have pointed out Method 5 from http://www.yoda.arachsys.com/csharp/singleton.html is less code. I did read to the end of the page! I chose method 2 because the Singleton objects relate to hardware devices and I want only want a couple of them initialised and used in any given run of the program. Method 5 will initialise them all straight away.
Is there any reason you're using that version rather than the simpler one which just initializes the instance in the declaration?
public class Singleton
{
private static Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
// Only use this if you really need it - see the page for details
static Singleton() {}
private Singleton()
{
// I assume this logic varies
}
}
This pattern is sufficiently short that I don't think it's much of a problem to include it everywhere.
I would urge you to consider whether you really need that many singletons; they're generally not great for testability etc.
EDIT: If you really, really want laziness and you're using .NET 4, you can get it with the 6th pattern which is on the singleton page's new home:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
public static class Singleton<T> where T: new()
{
static T instance=null;
static readonly object padlock = new object();
public static T Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new T();
}
return instance;
}
}
}
}
So you can use your Singleton for all Classes:
Singleton<YourClass>.Instance.YourMethod();
Try take a look at:
http://www.codeproject.com/KB/architecture/GenericSingletonPattern.aspx
Something like this?
public sealed class Singleton<T>
{
static T instance=null;
static readonly object padlock = new object();
static Func<T> createInstance;
Singleton(Func<T> constructor)
{
createInstance = constructor;
}
public static T Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = createInstance();
}
return instance;
}
}
}
}
I believe this is what you are after. However I strongly recommend avoiding this Singleton (capital S) pattern as it crushes all unit testing souls and makes heaps of things difficult to control.
public class Singleton<T> where T : new()
{
private static T _Instance;
private static readonly object _InstanceLock = new object();
public static T Instance
{
get
{
if (_Instance == null)
{
lock (_InstanceLock)
{
if (_Instance == null)
{
_Instance = new T();
}
}
}
return _Instance;
}
}
}
public class Foo : Singleton<Foo>
{
public void Something()
{
}
}
public class Example
{
public static void Main()
{
Foo.Instance.Something();
}
}

Categories