Locking the Static object inside the static property in the HTTPModule - c#

We have a custom DLL implemented IHttpModule to handle the httpApplication_EndRequest, what I want to know is
The DLL has a class (not a static class) which has a static property is used to create an instance for a static variables/object reference defined inside the class.
Now, should I need to lock inside static property before creating an instance for the static object/variable?
Eg:-
public class SPEnvironment : IEnvironment
{
private static SPEnvironment _instance;
private static object _syncRoot = new object();
private SPEnvironment()
{
try {
.....
}
finally {
......
}
}
public static SPEnvironment Instance
{
get
{
if (_instance == null)
{
lock (_syncRoot)
{
if (_instance == null)
{
_instance = new SPEnvironment();
}
}
}
return _instance;
}
}
}
I will calling this from an another class, like below
SPEnvironment.Instance;
Is it the right way? or the lock should be removed?

The double null check with a lock in the middle is a good, thread-safe way of instantiating a singleton. However, you could save yourself a lot of code by just saying
public class SPEnvironment : IEnvironment
{
public static SPEnvironment Instance = new SPEnvironment();
private SPEnvironment()
{
try {
.....
}
finally {
......
}
}
}
The difference between the two is that this code instantiates the singleton the first time an object of that type is created where your code instantiates the singleton the first time SPEnvironment.Instance is accessed. In almost all cases, those are the same thing; in most of the remaining cases, it doesn't matter; but it is a subtle distinction that is worth understanding for that very rare edge case.

Related

Prevent typecasting of singleton object

I extended a singleton class that gets the reference to the singleton object with the following call
SingletonClass.singleton
Now I want that every time I call the singleton variable on my CustomSingletonClass that I get a reference to a CustomSingletonClass and not SingletonClass.
Right now I'm using a typecast to achieve that ((CustomSingletonClass)CustomSingletonClass.singleton)
Do I have to override the singleton property somehow?
Usually singleton use static properties to get the instance of the object (seems like yours is SingletonClass.singleton).
As it is a static call, you can't override this porperty in an inherited object because the call will always be done on the current type, not on the instance (overriding static is just nonsense).
You could try to change the way it works by adding a setter to your singleton and setting the desired instance before any call.
public class A
{
private static A _instance;
public static A Instance
{
get
{
if (_instance == null)
{
_instance = new A();
}
return _instance;
}
set { _instance = value; }
}
}
public class B : A
{
}
A.Instance = new B();

Singleton design pattern with double-check lock

Consider you have the following code:
1. Why do we use double check lock, why single lock is not good enough, please provide detailed example.
2. What are the main drawbacks with this implementation? and how should I prove it?
Thanks.
public sealed class SomeSingleton5
{
private static SomeSingleton5 s_Instance = null;
private static object s_LockObj = new Object();
private SomeSingleton5() { }
public static SomeSingleton5 Instance
{
get
{
if (s_Instance == null)
{
lock (s_LockObj)
{
if (s_Instance == null)
{
s_Instance = new SomeSingleton5();
}
}
}
return s_Instance;
}
}
}
I think the best implementation of singleton class is provided by Jon Skeet.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
static Singleton() {}
private Singleton() {}
}
Singleton by Jon Skeet Clarification
Aquiring a lock is expensive. Without the first if(s_Instance == null) check, a lock would be aquired each time someone accesses the singleton. But a lock actually only needs to be there during instance creation. So the first if(s_Instance == null) prevents the unnecessary locking. The second if(s_Instance == null) needs to be there because initially two threads might have evaluated the first if(s_Instance == null) as true and the two threads would thereafter instanciate s_Instance after each other inside the lock.
I don't see any real drawbacks in your implementation but with the alternative (static constructor, see below) we have a solution that is simpler and involves less code. So it is more maintainable and less errorprone. Also it doesn't require locking at all. As mentioned earlier, locking is expensive.
you can improve it by using a static constructor:
public sealed class SomeSingleton5
{
// the compiler will generate a static constructor containing the following code
// and the CLR will call it (once) before SomeSingleton5 is first acccessed
private static SomeSingleton5 s_Instance = new SomeSingleton5();
private SomeSingleton5() { }
public static SomeSingleton5 Instance
{
get
{
return s_Instance;
}
}
}

Monitor.TryEnter with Generic Class

I have a situation where, for testing, I only want my timer method (FooMethod) to run one at a time. In the example below, FooMethod is passed as the delegate to a timer. There are many concrete instances of this class. I thought that by making _locker static, only one instance of FooMethod() would process at a time. But when I run the app, multiple threads are getting past the TryEnter() line at a time.
This is how I'm adding each class to a new timer. This is done, in a loop, for each foo instance:
_timers.Add(new Timer(foo.FooMethod, null, 0, 10000));
And this is the class that has that method:
public class Foo<T>
{
private static readonly object _locker = new object();
public void FooMethod(object stateInfo)
{
// Don't let threads back up; just get out
if (!Monitor.TryEnter(_locker)) { return; }
try
{
// Logic here
}
finally
{
Monitor.Exit(_locker);
}
}
}
Note: Normally, _locker isn't static; I don't want the same thread entering the method before it got a chance to complete. I changed it to static here for testing.
My first thought is that maybe this isn't working because the class is generic? And that each concrete class is actually its own class and they don't share the _locker variable? Is that true? If that's true how should I have the concrete classes share a _locker variable? Do I need to add a static _locker variable to some other class to which the Foos have access?
Do I need to add a static _locker variable to some other class to
which the Foos have access?
Yes.
Each closed Foo<T> type, with different T arguments, has its own static _locker object. You could make Foo inherit from a base class, and put the static object there. Then, all the types would use the same instance.
Maybe
public class Foo
{
protected static readonly object _locker = new object();
}
public class Foo<T> : Foo
{
public void FooMethod(object stateInfo)
{
if (!Monitor.TryEnter(_locker)) { return; }
try
{
// Logic here
}
finally
{
Monitor.Exit(_locker);
}
}
}
You are correct. Each unique type T referenced in code causes the CLR to generate a new concrete type for Foo<T> and each has its own set of static members.
You could restructure your code to look like the following. It is but one among many valid variations.
public class Foo
{
private static readonly object _locker = new object();
public void FooMethod(object stateInfo)
{
// Don't let threads back up; just get out
if (!Monitor.TryEnter(_locker)) { return; }
try
{
// Logic here
}
finally
{
Monitor.Exit(_locker);
}
}
}
public class Foo<T>
{
public void FooMethod(object stateInfo)
{
Foo.FooMethod(stateInfo);
}
}
Also, keep in mind that you can start the timer with an infinite period to prevent the callback from executing more than once. Call Change again at the end of FooMethod to queue the timer again. Since you have multiple timers all going at once you will still have multiple concurrent executions of FooMethod going simultaneously, but at least now there will only be one active call per timer. That is not exactly what you asked for, but I thought I would point this out anyway.
_timers.Add(new Timer(foo.FooMethod, _timers.Count, 10000, Timeout.Infinite));
public class Foo<T>
{
public void FooMethod(object stateInfo)
{
try
{
// Logic here
}
finally
{
int index = (int)stateInfo;
_timers[index].Change(10000, Timeout.Infinite);
}
}
}
Please make this class as non-generic type. That would purpose your need.
public class Foo
{
private static readonly object _locker = new object();
public void FooMethod(object stateInfo)
{
// Don't let threads back up; just get out
if (!Monitor.TryEnter(_locker)) { return; }
try
{
// Logic here
}
finally
{
Monitor.Exit(_locker);
}
}
}

C# ASP .NET MVC 3 singleton constructor called twice

I have a project consisting of three projects,
WCF service
Asp.net MVC 3 application
Class library.
The one in the class library is my singleton, which I have made like this;
public sealed class Singleton
{
public static Singleton Instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (Instance == null)
Instance = new Singleton();
return Instance;
}
}
}
The thing is, I put a Debug.WriteLinein the constructor, and it gets called twice.
What I am trying to do is use the singleton from the mvc 3 application and from the WCF service, but they make different instances. Why?
EDIT: I tried a treadsafe singleton earlier. It made no difference.
There's a couple of things that could be going on here.
The most likely is that your MVC application and your WCF service are running in different AppDomains. It will be impossible for the code to 'share' the same instance if this is the case.
An alternative and less likely cause, is that because your code is not thread safe multiple instances are created. If the Singleton constructor takes a long time to return then this could be the issue. Since your using MVC3, I'll assume .Net 4, in which case the Lazy class is your friend:
private static readonly Lazy<Singleton> _singleton = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return _singleton.Value; } }
I guess your implementation is not thread safe. check the article: Implementing Singleton in C#
here a thread-safe example: (there are many other ways to do this, more complex and safer, this is just a reference...)
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
I have no experience with WCF, but maybe you should implement a thread safe singleton, see: http://www.yoda.arachsys.com/csharp/singleton.html
If the WCF Service is running as a separate application, it will have it's own instance of the singleton as the two applications do not share memory.
Does the WCF Service run on a different IP Address/port number to the MVC application?
You can use the lazy pattern in .Net 4.0
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()
{
}
}
Source: http://csharpindepth.com/Articles/General/Singleton.aspx
First, your exact code as posted is not working. It is not syntactically correct (the curly braces are not balanced), and there are two public Singleton.Instance members. I assume your original code was like that:
public sealed class Singleton
{
private static Singleton _instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (_instance == null)
Instance = new Singleton();
return _instance;
}
}
}
The problem is probably related to a multi-threading environment. That is, while one of threads is calling new Singleton(), another tried to get Singleton.Instance, which, in turn, called another new Singleton().
You should either use double-checked locking there:
public sealed class Singleton
{
private static Singleton _instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (_instance == null)
lock (typeof(Singleton))
if (_instance == null)
{
var instance = new Singleton();
_instance = instance;
}
return _instance;
}
}
}
or, much easier,
public sealed class Singleton
{
public static readonly Singleton _instance = new Singleton();
private Singleton()
{
}
}

double check locking in singleton pattern

it may be basic question
to have a singleton in multi-threaded environment we can use a lock. Please refer the code snippet. But why do we need double-checked locking in singleton pattern? And more what does double-checked locking means?
class singleton
{
private static singleton instance = null;
private static singleton() { }
private static object objectlock = new object();
public static singleton Instance
{
get
{
lock (objectlock) //single - check lock
{
if (instance == null)
{
instance = new singleton();
}
return instance;
}
}
}
}
Jon Skeet explains this in detail.
Locks are expensive.
If the object already exists, there's no point in taking out a lock.
Thus, you have a first check outside the lock.
However, even if the object didn't exist before you took the look, another thread may have created it between the if condition and the lock statement.
Therefore, you need to check again inside the lock.
However, the best way to write a singleton is to use a static constructor:
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
And with .Net 4.x and newer you should defer to the Lazy class when possible as this pattern is used with the Initialization And Publication option. (note: the inverse is available as well where creation isn't thread safe but the publication of the instance is via the Publication option)
Multithreaded Singleton : The best approach to use double check locking
public sealed class Singleton
{
private static volatile Singleton _instance;
private static readonly object InstanceLoker= new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (_instance == null)
{
lock (InstanceLoker)
{
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
}
The "best" way I know is this:
public class MySingleton {
// object for synchronization
private static readonly object syncRoot = new object();
// the singleton instance
private static MySingleton #default;
public static MySingleton Default {
get {
// geting singleton instance without locking
var result = #default;
// if result is NOT null, no additional action is required
if ( object.ReferenceEquals(result, null) ){
// lock the synchronization object
lock(syncRoot) {
// geting singleton instanc in lock - because
// the value of #default field could be changed
result = #default;
// checking for NULL
if ( object.ReferenceEquals(result, null) ) {
// if result is NULL, create new singleton instance
result = new MySingleton();
// set the default instance
#default = result;
}
}
}
// return singleton instance
return result;
}
}
}
If you create the object in the field initialiser, you don't need the lock:
class singleton
{
private static singleton instance = new singleton();
private static singleton() { }
public static singleton Instance
{
get { return instance; }
}
}
Also - bear in mind that the lock is only controlling the creation of the object, the object would still need to be thread-safe if you're using it in multiple threads.
When we try to execute the method of the singleton class using Parallel libraries. It doesn’t recognize the singleton behavior because of multi threading is executing in TPL which causes to failure of concept Singleton Pattern . To overcome this problem there is concept of the locking of the object so that at a time only one thread can access it.
But this is not efficient approach because involvement of lock checking creates unnecessary watches to the object. To avoid it we make use “Double locking checking”

Categories

Resources