I've been sitting on this idea for quite a long time and would like to hear what you guys think about it.
The standard idiom for writing a singleton is roughly as follows:
public class A {
...
private static A _instance;
public static A Instance() {
if(_instance == null) {
_instance = new A();
}
return _instance;
}
...
}
Here I'm proposing another solution:
public class A {
...
private static A _instance;
public static A Instance() {
try {
return _instance.Self();
} catch(NullReferenceExceptio) {
_instance = new A();
}
return _instance.Self();
}
public A Self() {
return this;
}
...
}
The basic idea behind it is that the runtime cost of 1 dereference and unthrown exception is lesser than that of one null check. I've tried to measure the potentional performance gain and here are my numbers:
Sleep 1sec (try/catch): 188788ms
Sleep 1sec (nullcheck): 207485ms
And the test code:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
public class A
{
private static A _instance;
public static A Instance() {
try {
return _instance.Self();
} catch(NullReferenceException) {
_instance = new A();
}
return _instance.Self();
}
public A Self() {
return this;
}
public void DoSomething()
{
Thread.Sleep(1);
}
}
public class B
{
private static B _instance;
public static B Instance() {
if(_instance == null) {
_instance = new B();
}
return _instance;
}
public void DoSomething()
{
Thread.Sleep(1);
}
}
public class MyClass
{
public static void Main()
{
Stopwatch sw = new Stopwatch();
sw.Reset();
sw.Start();
for(int i = 0; i < 100000; ++i) {
A.Instance().DoSomething();
}
Console.WriteLine(sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
for(int i = 0; i < 100000; ++i) {
B.Instance().DoSomething();
}
Console.WriteLine(sw.ElapsedMilliseconds);
RL();
}
#region Helper methods
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
The resulting performance gain is almost 10%, the question is whether it's a micro-op, or it can offer significant performance boost for singleton happy applications (or it's middleware, like, logging)?
What you're asking about is the best way to implement a bad singleton pattern. You should have a look at Jon Skeet's article on how to implement the singleton pattern in C#. You'll find that there are much better (safer) ways and they don't suffer from the same performance issues.
This is a horrid way to do this. As others have pointed out, exceptions should only be used for handling exceptional, unexpected situations. And because we make that assumption, many organizations run their code in contexts which aggressively seek out and report exceptions, even handled ones, because a handled null reference exception is almost certainly a bug. If your program is unexpectedly dereferencing invalid memory and continuing merrily along then odds are good that something is deeply, badly broken in your program and it should be brought to someone's attention.
Do not "cry wolf" and deliberately construct a situation that looks horribly broken but is in fact by design. That's just making more work for everyone. There is a standard, straightforward, accepted way to make a singleton in C#; do that if that's what you mean. Don't try to invent some crazy thing that violates good programming principles. People smarter than me have designed a singleton implementation that works; it's foolish to not use it.
I learned this the hard way. Long story short, I once deliberately used a test that would most of the time dereference bad memory in a mainline scenario in the VBScript runtime. I made sure to carefully handle the exception and recover correctly, and the ASP team went crazy that afternoon. Suddenly all their checks for server integrity started reporting that huge numbers of their pages were violating memory integrity and recovering from that. I ended up rearchitecting the implementation of that scenario to only do code paths that did not result in exceptions.
A null ref exception should always be a bug, period. When you handle a null ref exception, you are hiding a bug.
More musing on exception classifications:
http://ericlippert.com/2008/09/10/vexing-exceptions/
I think that if my application is calling a singleton's constructor often enough for a 10% performance boost to mean anything I'd be rather worried.
That said, neither version is thread-safe. Focus on getting things like that right first.
"We should forget about small
efficiencies, say about 97% of the
time: premature optimization is the
root of all evil."
This optimization seems trivial. I've always be taught to use try/catch blocks only to catch conditions that would be difficult or impossible to check with an if-statement.
Its not that your proposed approach wouldn't work. It just isn't significantly better than the original way.
The "improved" implementation has a big problem and that is that it fires an interrupt. A rule of thumb is that application logic should not be dependent on exceptions firing.
You should never use exception handling for control flow.
Besides, instead of:
if(_instance == null) {
_instance = new A();
}
return _instance;
you can do:
return _instance ?? (_instance = new A());
Which is semantically the same.
why not just:
public class A {
...
private static A _instance = new A();
public static A Instance() {
return _instance;
}
...
}
I think that your solution is perfectly acceptable though I do think there are a few things that you should (and are rarely) consider before implementing a lazy loaded singleton panti-pattern.
Could you provide a DI version instead, would a unity container suffice with an interface contract? This would allow you to swap the implementation later if need be, also makes testing a lot easier.
If you must insist on using a singleton, do you really need a lazy-loaded implementation? The cost of creating the instance on the static constructor either implicitly or explicitly will only be executed when the class has been referenced at run-time, and in my experience almost ALL singletons are only ever referenced when they want to get access to "Instance" anyway.
If you need to implement it the way you've described, you'd do it like the following.
UPDATE: I've updated the example to instead lock class type instead of a lock variable as Brian Gideon points out the instance could be in a half initialized state. Any use of lock(typeof()) is strongly advised against and I recommend that you never use this approach.
public class A {
private static A _instance;
private A() { }
public static A Instance {
get {
try {
return _instance.Self();
} catch (NullReferenceException) {
lock (typeof(A)) {
if (_instance == null)
_instance = new A();
}
}
return _instance.Self();
}
}
private A Self() { return this; }
}
Related
I have a class from a third-party assembly (so I can't edit it):
public class MyClass
{
private bool _loggedIn;
public void Login() {_loggedIn = true;}
public void Logout() {
if (!_loggedIn) throw new InvalidOperationException();
_loggedIn = false;
}
}
Now, suppose I have an instance of MyClass (for which I don't know _loggedIn), and I need call LogOut. Which of the following methods of avoiding a fatal exception will generally be faster? (any other method would be fine too):
To call LogOut, and if _loggedIn == false, just catch the exception
To use reflection to check that _loggedIn == true, and only call LogOut if so
It depends on the invariants you expect to see in your application.
1. If you expect to have a lot of MyClass having different state(logged in, logged off), then it is better to avoid overhead of exception (because exception is Exceptional situation) and use some specific public IsLoggedIn property (obviously to avoid Reflection) or some TryXxxxx-like methods.
And even if you can't modify the original code no one stops you from wrapping it:
public class MyWrappedClass
{
public Boolean IsLoggedIn {get; private set;}
private MyClass m_Log;
public MyWrappedClass ()
{
this.m_Log = new MyClass();
this.IsLoggedIn = false;
}
public void Log()
{
try
{
this.m_Log.LogIn();
this.IsLoggedIn = true;
}
catch
{
this.IsLoggedIn = false;
}
}
public void LogOut()
{
try
{
this.m_Log.LogOut();
this.IsLoggedIn = false;
}
catch
{
this.IsLoggedIn = true;
}
}
}
You could even go further and implement IDisposable interface with it to avoid manual LogIn-LogOut management:
public class MyWrappedClass
{
private class LogSessionToken : IDisposable
{
private MyWrappedClass parent;
public LogSessionToken (MyWrappedClass parent)
{
parent.LogIn();
}
public void Dispose()
{
parent.LogOut();
}
}
public IDisposable LogSession()
{
return new LogSessionToken (this);
}
// ...
}
And use it like
using (var logToken = wrappedInstance.LogSession)
{
// do the work.
} // No need to worry about manual LogOut
2. If you expect to use only few of MyClass in a proper fashion, then it would be a better idea to not handle exception at all - if something wrong happened then it is some programming error thus the program shall be terminated.
First, if your class doesn't expose at least a read-only property for LoggedIn, there sounds like a fairly large design flaw.
For speed, using reflection will generally be faster, particularly if you cache the FieldInfo or build a Func<bool> using System.Linq.Expressions. This is because Exceptions collect lots of debug information when thrown, including a StackTrace, which can be expensive.
As with anything, though, it is often best to test such operations, as there are sometime optimizations or other factors that may surprise you.
If the pattern if (CanFoo) Foo(); appears very much, that tends to imply very strongly that either:
A properly-written client would know when it can or cannot call Foo. The fact that a client doesn't know suggest that it's probably deficient in other ways.
The class exposing CanFoo and Foo should also expose a method which will Foo if possible and appropriate (the method should throw if unable to establish expected post-conditions, but should return silently if the post-conditions were established before the call)
In cases where a class one does not control should provide such a method but doesn't, the cleanest approach may be to write one's own wrapper method whose semantics mirror those the missing method should have had. If a later version of the class implements the missing method, changing one's code to use that implementation may be easier than refactoring lots of if (CanFoo) constructs.
BTW, I would suggest that a properly-designed class should allow calling code to indicate whether it is expecting a transition from logged-in state to logged-out state, or whether it wants to end up in logged-out state but it doesn't care how it gets there. Both kinds of semantics have perfectly legitimate uses; in cases where the first kind would be appropriate, having a LogOut method throw an exception if called on a closed session would be a good thing, but in cases where client code merely wants to ensure that it is logged out, having an EnsureLoggedOut method that could be invoked unconditionally would be cleaner than having to add extra client-side code for that purpose.
I have some questions regarding the the singleton pattern as documented here:
http://msdn.microsoft.com/en-us/library/ff650316.aspx
The following code is an extract from the article:
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;
}
}
}
Specifically, in the above example, is there a need to compare instance to null twice, before and after the lock? Is this necessary? Why not perform the lock first and make the comparison?
Is there a problem in simplifying to the following?
public static Singleton Instance
{
get
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
return instance;
}
}
Is the performing the lock expensive?
Performing the lock is terribly expensive when compared to the simple pointer check instance != null.
The pattern you see here is called double-checked locking. Its purpose is to avoid the expensive lock operation which is only going to be needed once (when the singleton is first accessed). The implementation is such because it also has to ensure that when the singleton is initialized there will be no bugs resulting from thread race conditions.
Think of it this way: a bare null check (without a lock) is guaranteed to give you a correct usable answer only when that answer is "yes, the object is already constructed". But if the answer is "not constructed yet" then you don't have enough information because what you really wanted to know is that it's "not constructed yet and no other thread is intending to construct it shortly". So you use the outer check as a very quick initial test and you initiate the proper, bug-free but "expensive" procedure (lock then check) only if the answer is "no".
The above implementation is good enough for most cases, but at this point it's a good idea to go and read Jon Skeet's article on singletons in C# which also evaluates other alternatives.
The Lazy<T> version:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy
= new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
=> lazy.Value;
private Singleton() { }
}
Requires .NET 4 and C# 6.0 (VS2015) or newer.
Performing a lock: Quite cheap (still more expensive than a null test).
Performing a lock when another thread has it: You get the cost of whatever they've still to do while locking, added to your own time.
Performing a lock when another thread has it, and dozens of other threads are also waiting on it: Crippling.
For performance reasons, you always want to have locks that another thread wants, for the shortest period of time at all possible.
Of course it's easier to reason about "broad" locks than narrow, so it's worth starting with them broad and optimising as needed, but there are some cases that we learn from experience and familiarity where a narrower fits the pattern.
(Incidentally, if you can possibly just use private static volatile Singleton instance = new Singleton() or if you can possibly just not use singletons but use a static class instead, both are better in regards to these concerns).
The reason is performance. If instance != null (which will always be the case except the very first time), there is no need to do a costly lock: Two threads accessing the initialized singleton simultaneously would be synchronized unneccessarily.
In almost every case (that is: all cases except the very first ones), instance won't be null. Acquiring a lock is more costly than a simple check, so checking once the value of instance before locking is a nice and free optimization.
This pattern is called double-checked locking: http://en.wikipedia.org/wiki/Double-checked_locking
This is called Double checked locking mechanism, first, we will check whether the instance is created or not. If not then only we will synchronize the method and create the instance. It will drastically improve the performance of the application. Performing lock is heavy. So to avoid the lock first we need to check the null value. This is also thread safe and it is the best way to achieve the best performance. Please have a look at the following code.
public sealed class Singleton
{
private static readonly object Instancelock = new object();
private Singleton()
{
}
private static Singleton instance = null;
public static Singleton GetInstance
{
get
{
if (instance == null)
{
lock (Instancelock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
Jeffrey Richter recommends following:
public sealed class Singleton
{
private static readonly Object s_lock = new Object();
private static Singleton instance = null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if(instance != null) return instance;
Monitor.Enter(s_lock);
Singleton temp = new Singleton();
Interlocked.Exchange(ref instance, temp);
Monitor.Exit(s_lock);
return instance;
}
}
}
You could eagerly create the a thread-safe Singleton instance, depending on your application needs, this is succinct code, though I would prefer #andasa's lazy version.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance()
{
return instance;
}
}
Another version of Singleton where the following line of code creates the Singleton instance at the time of application startup.
private static readonly Singleton singleInstance = new Singleton();
Here CLR (Common Language Runtime) will take care of object initialization and thread safety. That means we will not require to write any code explicitly for handling the thread safety for a multithreaded environment.
"The Eager loading in singleton design pattern is nothing a process in
which we need to initialize the singleton object at the time of
application start-up rather than on demand and keep it ready in memory
to be used in future."
public sealed class Singleton
{
private static int counter = 0;
private Singleton()
{
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
private static readonly Singleton singleInstance = new Singleton();
public static Singleton GetInstance
{
get
{
return singleInstance;
}
}
public void PrintDetails(string message)
{
Console.WriteLine(message);
}
}
from main :
static void Main(string[] args)
{
Parallel.Invoke(
() => PrintTeacherDetails(),
() => PrintStudentdetails()
);
Console.ReadLine();
}
private static void PrintTeacherDetails()
{
Singleton fromTeacher = Singleton.GetInstance;
fromTeacher.PrintDetails("From Teacher");
}
private static void PrintStudentdetails()
{
Singleton fromStudent = Singleton.GetInstance;
fromStudent.PrintDetails("From Student");
}
Reflection resistant Singleton pattern:
public sealed class Singleton
{
public static Singleton Instance => _lazy.Value;
private static Lazy<Singleton, Func<int>> _lazy { get; }
static Singleton()
{
var i = 0;
_lazy = new Lazy<Singleton, Func<int>>(() =>
{
i++;
return new Singleton();
}, () => i);
}
private Singleton()
{
if (_lazy.Metadata() == 0 || _lazy.IsValueCreated)
throw new Exception("Singleton creation exception");
}
public void Run()
{
Console.WriteLine("Singleton called");
}
}
Isn't this a simpler as well as safe (and hence better) way to implement a singleton instead of doing double-checked locking mambo-jambo? Any drawbacks of this approach?
public class Singleton
{
private static Singleton _instance;
private Singleton() { Console.WriteLine("Instance created"); }
public static Singleton Instance
{
get
{
if (_instance == null)
{
Interlocked.CompareExchange(ref _instance, new Singleton(), null);
}
return _instance;
}
}
public void DoStuff() { }
}
EDIT: the test for thread-safety failed, can anyone explain why? How come Interlocked.CompareExchange isn't truly atomic?
public class Program
{
static void Main(string[] args)
{
Parallel.For(0, 1000000, delegate(int i) { Singleton.Instance.DoStuff(); });
}
}
Result (4 cores, 4 logical processors)
Instance created
Instance created
Instance created
Instance created
Instance created
If your singleton is ever in danger of initializing itself multiple times, you have a lot worse problems. Why not just use:
public class Singleton
{
private static Singleton instance=new Singleton();
private Singleton() {}
public static Singleton Instance{get{return instance;}}
}
Absolutely thread-safe in regards to initialization.
Edit: in case I wasn't clear, your code is horribly wrong. Both the if check and the new are not thread-safe! You need to use a proper singleton class.
You may well be creating multiple instances, but these will get garbage collected because they are not used anywhere. In no case does the static _instance field variable change its value more than once, the single time that it goes from null to a valid value. Hence consumers of this code will only ever see the same instance, despite the fact that multiple instances have been created.
Lock free programming
Joe Duffy, in his book entitled Concurrent Programming on Windows actually analyses this very pattern that you are trying to use on chapter 10, Memory models and Lock Freedom, page 526.
He refers to this pattern as a Lazy initialization of a relaxed reference:
public class LazyInitRelaxedRef<T> where T : class
{
private volatile T m_value;
private Func<T> m_factory;
public LazyInitRelaxedRef(Func<T> factory) { m_factory = factory; }
public T Value
{
get
{
if (m_value == null)
Interlocked.CompareExchange(ref m_value, m_factory(), null);
return m_value;
}
}
/// <summary>
/// An alternative version of the above Value accessor that disposes
/// of garbage if it loses the race to publish a new value. (Page 527.)
/// </summary>
public T ValueWithDisposalOfGarbage
{
get
{
if (m_value == null)
{
T obj = m_factory();
if (Interlocked.CompareExchange(ref m_value, obj, null) != null && obj is IDisposable)
((IDisposable)obj).Dispose();
}
return m_value;
}
}
}
As we can see, in the above sample methods are lock free at the price of creating throw-away objects. In any case the Value property will not change for consumers of such an API.
Balancing Trade-offs
Lock Freedom comes at a price and is a matter of choosing your trade-offs carefully. In this case the price of lock freedom is that you have to create instances of objects that you are not going to use. This may be an acceptable price to pay since you know that by being lock free, there is a lower risk of deadlocks and also thread contention.
In this particular instance however, the semantics of a singleton are in essence to Create a single instance of an object, so I would much rather opt for Lazy<T> as #Centro has quoted in his answer.
Nevertheless, it still begs the question, when should we use Interlocked.CompareExchange? I liked your example, it is quite thought provoking and many people are very quick to diss it as wrong when it is not horribly wrong as #Blindy quotes.
It all boils down to whether you have calculated the tradeoffs and decided:
How important is it that you produce one and only one instance?
How important is it to be lock free?
As long as you are aware of the trade-offs and make it a conscious decision to create new objects for the benefit of being lock free, then your example could also be an acceptable answer.
In order not to use 'double-checked locking mambo-jambo' or simply not to implement an own singleton reinventing the wheel, use a ready solution included into .NET 4.0 - Lazy<T>.
public class Singleton
{
private static Singleton _instance = new Singleton();
private Singleton() {}
public static Singleton Instance
{
get
{
return _instance;
}
}
}
I am not convinced you can completely trust that. Yes, Interlocked.CompareExchanger is atomic, but new Singleton() is in not going to be atomic in any non-trivial case. Since it would have to evaluated before exchanging values, this would not be a thread-safe implementation in general.
what about this?
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
It's the fifth version on this page:
http://www.yoda.arachsys.com/csharp/singleton.html
I'm not sure, but the author seems to think its both thread-safe and lazy loading.
Your singleton initializer is behaving exactly as it should. See Raymond Chen's Lock-free algorithms: The singleton constructor:
This is a double-check lock, but without the locking. Instead of taking lock when doing the initial construction, we just let it be a free-for-all over who gets to create the object. If five threads all reach this code at the same time, sure, let's create five objects. After everybody creates what they think is the winning object, they called InterlockedCompareExchangePointerRelease to attempt to update the global pointer.
This technique is suitable when it's okay to let multiple threads try to create the singleton (and have all the losers destroy their copy). If creating the singleton is expensive or has unwanted side-effects, then you don't want to use the free-for-all algorithm.
Each thread creates the object; as it thinks nobody has created it yet. But then during the InterlockedCompareExchange, only one thread will really be able to set the global singleton.
Bonus reading
One-Time Initialization helper functions save you from having to write all this code yourself. They deal with all the synchronization and memory barrier issues, and support both the one-person-gets-to-initialize and the free-for-all-initialization models.
A lazy initialization primitive for .NET provides a C# version of the same.
This is not thread-safe.
You would need a lock to hold the if() and the Interlocked.CompareExchange() together, and then you wouldn't need the CompareExchange anymore.
You still have the issue that you're quite possibly creating and throwing away instances of your singleton. When you execute Interlocked.CompareExchange(), the Singleton constructor will always be executed, regardless of whether the assignment will succeed. So you're no better off (or worse off, IMHO) than if you said:
if ( _instance == null )
{
lock(latch)
{
_instance = new Singleton() ;
}
}
Better performance vis-a-vis thread contention than if you swapped the position of the lock and the test for null, but at the risk of an extra instance being constructed.
An obvious singleton implementation for .NET?
Auto-Property initialization (C# 6.0) does not seem to cause the multiple instantiations of Singleton you are seeing.
public class Singleton
{
static public Singleton Instance { get; } = new Singleton();
private Singleton();
}
I think the simplest way after .NET 4.0 is using System.Lazy<T>:
public class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton() { }
}
Jon Skeet has a nice article here that covers a lot of ways of implementing singleton and the problems of each one.
Don't use locking. Use your language environment
Mostly simple Thread-safe implementation is:
public class Singleton
{
private static readonly Singleton _instance;
private Singleton() { }
static Singleton()
{
_instance = new Singleton();
}
public static Singleton Instance
{
get { return _instance; }
}
}
I have some code for the instance property of a controller class that looks like this:
public class Controller
{
private static volatile Controller _instance;
private static object syncRoot = new Object();
private Controller() { }
public static Controller Instance
{
get
{
if (_instance == null)
{
lock (syncRoot)
{
if (_instance == null)
_instance = new Controller();
}
}
return _instance;
}
}
public void Start()
{
}
}
After reading through the msdn docs on the volatile keyword, I'm not sure if the second null check is redundant or not and whether the better way to write the getter would be something like this:
get
{
lock (syncRoot)
{
if (_instance == null)
_instance = new Controller();
}
return _instance;
}
Which of the two implementations are better for multi-thread performance and DRY'ness (redundancy removal)?
This is called the "double checked locking" pattern. It is an attempt at a low-lock optimization and is therefore extremely dangerous.
The pattern is not guaranteed to work correctly on CLR v1.0. Whether it is so guaranteed on later versions is a matter of some debate; some articles say yes, some say no. It is very confusing.
I would avoid it entirely unless you had a very good reason to suppose that the solution with locking was insufficient to meet your needs. I would use higher-level primitives, like Lazy<T>, written by experts like Joe Duffy. They're more likely to be correct.
This question is a duplicate of
The need for volatile modifier in double checked locking in .NET
See the detailed answers there for more information. In particular, if you ever intend to write any low-lock code you absolutely have to read Vance's article:
http://msdn.microsoft.com/en-us/magazine/cc163715.aspx
and Joe's article:
http://www.bluebytesoftware.com/blog/PermaLink,guid,543d89ad-8d57-4a51-b7c9-a821e3992bf6.aspx
Note that Vance's article makes the claim that double-checked locking is guaranteed to work in CLR v2. It is not clear to me that the guarantees discussed in the article were actually implemented in CLR v2 or not; I have never gotten a straight answer out of anyone and have heard both that they were and were not implemented as specified. Again, you're on the trapeze without a net when you do this low-lock stuff yourself; avoid it if you possibly can.
A much better option would be to use Lazy<T>:
private static readonly Lazy<Controller> _instance = new Lazy<Controller>
(() => new Controller());
private Controller() { }
public static Controller Instance
{
get
{
return _instance.Value;
}
}
If, however, you're stuck with a version prior to .NET 4, I'd recommend reading Jon Skeet's article on Singletons in C#. It discusses the advantages and disadvantages to the above techiques, as well as providing a better implementation of a lazy instantiated singleton for .NET 3.5 and earlier.
you want to check before locking the object so that no unnecessary locking occurs
you also want to check after locking to avoid multiple instantiations of the object
the first is not needed but highly advisable for performance sake
the classic way to do this is double-checked locking: You check once before acquiring the lock to reduce overhead (acquiring the lock is relatively expensive) - then check again after you got the lock to be sure it wasn't set already.
Edit: As was pointed out Lazy<T> is a much better option here, I'm leaving this answer here for completeness.
if (_instance == null)
{
lock (syncRoot)
{
if (_instance == null)
_instance = new Controller();
}
}
return _instance;
I've got a bunch of properties which I am going to use read/write locks on. I can implement them either with a try finally or a using clause.
In the try finally I would acquire the lock before the try, and release in the finally. In the using clause, I would create a class which acquires the lock in its constructor, and releases in its Dispose method.
I'm using read/write locks in a lot of places, so I've been looking for ways that might be more concise than try finally. I'm interested in hearing some ideas on why one way may not be recommended, or why one might be better than another.
Method 1 (try finally):
static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock();
private DateTime dtMyDateTime_m
public DateTime MyDateTime
{
get
{
rwlMyLock_m .AcquireReaderLock(0);
try
{
return dtMyDateTime_m
}
finally
{
rwlMyLock_m .ReleaseReaderLock();
}
}
set
{
rwlMyLock_m .AcquireWriterLock(0);
try
{
dtMyDateTime_m = value;
}
finally
{
rwlMyLock_m .ReleaseWriterLock();
}
}
}
Method 2:
static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock();
private DateTime dtMyDateTime_m
public DateTime MyDateTime
{
get
{
using (new ReadLock(rwlMyLock_m))
{
return dtMyDateTime_m;
}
}
set
{
using (new WriteLock(rwlMyLock_m))
{
dtMyDateTime_m = value;
}
}
}
public class ReadLock : IDisposable
{
private ReaderWriterLock rwl;
public ReadLock(ReaderWriterLock rwl)
{
this.rwl = rwl;
rwl.AcquireReaderLock(0);
}
public void Dispose()
{
rwl.ReleaseReaderLock();
}
}
public class WriteLock : IDisposable
{
private ReaderWriterLock rwl;
public WriteLock(ReaderWriterLock rwl)
{
this.rwl = rwl;
rwl.AcquireWriterLock(0);
}
public void Dispose()
{
rwl.ReleaseWriterLock();
}
}
From MSDN, using Statement (C# Reference)
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
So basically, it is the same code but with a nice automatic null-checks and an extra scope for your variable. The documentation also states that it "ensures the correct use of IDisposable object" so you might as well gets even better framework support for any obscure cases in the future.
So go with option 2.
Having the variable inside a scope that ends immediately after it's no longer needed is also a plus.
I definitely prefer the second method. It is more concise at the point of usage, and less error prone.
In the first case someone editing the code has to be careful not to insert anything between the Acquire(Read|Write)Lock call and the try.
(Using a read/write lock on individual properties like this is usually overkill though. They are best applied at a much higher level. A simple lock will often suffice here since the possibility of contention is presumably very small given the time the lock is held for, and acquiring a read/write lock is a more expensive operation than a simple lock).
Consider the possibility that both solutions are bad because they mask exceptions.
A try without a catch should obviously be a bad idea; see MSDN for why the using statement is likewise dangerous.
Note also Microsoft now recommends ReaderWriterLockSlim instead of ReaderWriterLock.
Finally, note that the Microsoft examples use two try-catch blocks to avoid these issues, e.g.
try
{
try
{
//Reader-writer lock stuff
}
finally
{
//Release lock
}
}
catch(Exception ex)
{
//Do something with exception
}
A simple, consistent, clean solution is a good goal, but assuming you can't just use lock(this){return mydateetc;}, you might reconsider the approach; with more info I'm sure Stack Overflow can help ;-)
I personally use the C# "using" statement as often as possible, but there are a few specific things that I do along with it to avoid the potential issues mentioned. To illustrate:
void doSomething()
{
using (CustomResource aResource = new CustomResource())
{
using (CustomThingy aThingy = new CustomThingy(aResource))
{
doSomething(aThingy);
}
}
}
void doSomething(CustomThingy theThingy)
{
try
{
// play with theThingy, which might result in exceptions
}
catch (SomeException aException)
{
// resolve aException somehow
}
}
Note that I separate the "using" statement into one method and the use of the object(s) into another method with a "try"/"catch" block. I may nest several "using" statements like this for related objects (I sometimes go three or four deep in my production code).
In my Dispose() methods for these custom IDisposable classes, I catch exceptions (but NOT errors) and log them (using Log4net). I have never encountered a situation where any of those exceptions could possibly affect my processing. The potential errors, as usual, are allowed to propagate up the call stack and typically terminate processing with an appropriate message (the error and stack trace) logged.
If I somehow encountered a situation where a significant exception could occur during Dispose(), I would redesign for that situation. Frankly, I doubt that will ever happen.
Meanwhile, the scope and cleanup advantages of "using" make it one of my most favorite C# features. By the way, I work in Java, C#, and Python as my primary languages, with lots of others thrown in here and there, and "using" is one of my most favorite language features all around because it is a practical, everyday workhorse.
I like the 3rd option
private object _myDateTimeLock = new object();
private DateTime _myDateTime;
public DateTime MyDateTime{
get{
lock(_myDateTimeLock){return _myDateTime;}
}
set{
lock(_myDateTimeLock){_myDateTime = value;}
}
}
Of your two options, the second option is the cleanest and easier to understand what's going on.
"Bunch of properties" and locking at the property getter and setter level looks wrong. Your locking is much too fine-grained. In most typical object usage, you'd want to make sure that you acquired a lock to access more than one property at the same time. Your specific case might be different but I kinda doubt it.
Anyway, acquiring the lock when you access the object instead of the property will significantly cut down on the amount of locking code you'll have to write.
DRY says: second solution. The first solution duplicates the logic of using a lock, whereas the second does not.
Try/Catch blocks are generally for exception handling, while using blocks are used to ensure that the object is disposed.
For the read/write lock a try/catch might be the most useful, but you could also use both, like so:
using (obj)
{
try { }
catch { }
}
so that you can implicitly call your IDisposable interface as well as make exception handling concise.
The following creates extension methods for the ReaderWriterLockSlim class that allow you to do the following:
var rwlock = new ReaderWriterLockSlim();
using (var l = rwlock.ReadLock())
{
// read data
}
using (var l = rwlock.WriteLock())
{
// write data
}
Here's the code:
static class ReaderWriterLockExtensions() {
/// <summary>
/// Allows you to enter and exit a read lock with a using statement
/// </summary>
/// <param name="readerWriterLockSlim">The lock</param>
/// <returns>A new object that will ExitReadLock on dispose</returns>
public static OnDispose ReadLock(this ReaderWriterLockSlim readerWriterLockSlim)
{
// Enter the read lock
readerWriterLockSlim.EnterReadLock();
// Setup the ExitReadLock to be called at the end of the using block
return new OnDispose(() => readerWriterLockSlim.ExitReadLock());
}
/// <summary>
/// Allows you to enter and exit a write lock with a using statement
/// </summary>
/// <param name="readerWriterLockSlim">The lock</param>
/// <returns>A new object that will ExitWriteLock on dispose</returns>
public static OnDispose WriteLock(this ReaderWriterLockSlim rwlock)
{
// Enter the write lock
rwlock.EnterWriteLock();
// Setup the ExitWriteLock to be called at the end of the using block
return new OnDispose(() => rwlock.ExitWriteLock());
}
}
/// <summary>
/// Calls the finished action on dispose. For use with a using statement.
/// </summary>
public class OnDispose : IDisposable
{
Action _finished;
public OnDispose(Action finished)
{
_finished = finished;
}
public void Dispose()
{
_finished();
}
}
I think method 2 would be better.
Simpler and more readable code in your properties.
Less error-prone since the locking code doesn't have to be re-written several times.
While I agree with many of the above comments, including the granularity of the lock and questionable exception handling, the question is one of approach. Let me give you one big reason why I prefer using over the try {} finally model... abstraction.
I have a model very similar to yours with one exception. I defined a base interface ILock and in it I provided one method called Acquire(). The Acquire() method returned the IDisposable object and as a result means that as long as the object I am dealing with is of type ILock that it can be used to do a locking scope. Why is this important?
We deal with many different locking mechanisms and behaviors. Your lock object may have a specific timeout that employs. Your lock implementation may be a monitor lock, reader lock, writer lock or spin lock. However, from the perspective of the caller all of that is irrelevant, what they care about is that the contract to lock the resource is honored and that the lock does it in a manner consistent with it's implementation.
interface ILock {
IDisposable Acquire();
}
class MonitorLock : ILock {
IDisposable Acquire() { ... acquire the lock for real ... }
}
I like your model, but I'd consider hiding the lock mechanics from the caller. FWIW, I've measured the overhead of the using technique versus the try-finally and the overhead of allocating the disposable object will have between a 2-3% performance overhead.
I'm surprised no one has suggested encapsulating the try-finally in anonymous functions. Just like the technique of instantiating and disposing of classes with the using statement, this keeps the locking in one place. I prefer this myself only because I'd rather read the word "finally" than the word "Dispose" when I'm thinking about releasing a lock.
class StackOTest
{
private delegate DateTime ReadLockMethod();
private delegate void WriteLockMethod();
static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock();
private DateTime dtMyDateTime_m;
public DateTime MyDateTime
{
get
{
return ReadLockedMethod(
rwlMyLock_m,
delegate () { return dtMyDateTime_m; }
);
}
set
{
WriteLockedMethod(
rwlMyLock_m,
delegate () { dtMyDateTime_m = value; }
);
}
}
private static DateTime ReadLockedMethod(
ReaderWriterLock rwl,
ReadLockMethod method
)
{
rwl.AcquireReaderLock(0);
try
{
return method();
}
finally
{
rwl.ReleaseReaderLock();
}
}
private static void WriteLockedMethod(
ReaderWriterLock rwl,
WriteLockMethod method
)
{
rwl.AcquireWriterLock(0);
try
{
method();
}
finally
{
rwl.ReleaseWriterLock();
}
}
}
SoftwareJedi, I don't have an account, so I can't edit my answers.
In any case, the previous version wasn't really good for general purpose use since the read lock always required a return value. This fixes that:
class StackOTest
{
static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock();
private DateTime dtMyDateTime_m;
public DateTime MyDateTime
{
get
{
DateTime retval = default(DateTime);
ReadLockedMethod(
delegate () { retval = dtMyDateTime_m; }
);
return retval;
}
set
{
WriteLockedMethod(
delegate () { dtMyDateTime_m = value; }
);
}
}
private void ReadLockedMethod(Action method)
{
rwlMyLock_m.AcquireReaderLock(0);
try
{
method();
}
finally
{
rwlMyLock_m.ReleaseReaderLock();
}
}
private void WriteLockedMethod(Action method)
{
rwlMyLock_m.AcquireWriterLock(0);
try
{
method();
}
finally
{
rwlMyLock_m.ReleaseWriterLock();
}
}
}
Actually in your first example, to make the solutions comparable, you would also implement IDisposable there as well. Then you'd call Dispose() from the finally block instead of releasing the lock directly.
Then you'd be "apples to apples" implementation (and MSIL)-wise (MSIL will be the same for both solutions). It's still probably a good idea to use using because of the added scoping and because the Framework will ensure proper usage of IDisposable (the latter being less beneficial if you're implementing IDisposable yourself).
Silly me. There's a way to make that even simpler by making the locked methods part of each instance (instead of static like in my previous post). Now I really prefer this because there's no need to pass `rwlMyLock_m' off to some other class or method.
class StackOTest
{
private delegate DateTime ReadLockMethod();
private delegate void WriteLockMethod();
static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock();
private DateTime dtMyDateTime_m;
public DateTime MyDateTime
{
get
{
return ReadLockedMethod(
delegate () { return dtMyDateTime_m; }
);
}
set
{
WriteLockedMethod(
delegate () { dtMyDateTime_m = value; }
);
}
}
private DateTime ReadLockedMethod(ReadLockMethod method)
{
rwlMyLock_m.AcquireReaderLock(0);
try
{
return method();
}
finally
{
rwlMyLock_m.ReleaseReaderLock();
}
}
private void WriteLockedMethod(WriteLockMethod method)
{
rwlMyLock_m.AcquireWriterLock(0);
try
{
method();
}
finally
{
rwlMyLock_m.ReleaseWriterLock();
}
}
}