What do you expect to see when you first access the Instance property before you have an object to block?
(Hint: lock(null) comes in ...)
As a standalone measure, I almost always avoid locking on the “actual object” - because there can usually be other code referenced by this link, and I don’t necessarily know that it will block. Even if your version really works, what will happen if some external code wrote:
// Make sure only one thread is ever in this code... lock (Singleton.Instance) { // Do stuff }
Now no one can even get an instance while this code is running, because they will be locked in the getter. A getter lock is not designed to protect against this — it is only intended to protect against multiple access at the receiver.
The tighter you can control your locks, the easier it is for them to reason and avoid deadlocks.
I very rarely have to block a "normal" object if:
- I do not show this link outside this class
- I am sure that the type itself (which will always refer to
this , of course) will not block itself.
(All this is an excuse to avoid blocking on this too, of course ...)
Basically, I believe that the idea of allowing you to block any object was a bad idea in Java, and it was nice to copy it to .NET :(
source share