Locking a private static object - c#

I am wondering which following code is best:
private static volatile OrderedDictionary _instance;
private static readonly Object SyncLock = new Object();
private static OrderedDictionary Instance
{
get { return _instance ?? (_instance = new OrderedDictionary()); }
}
public static Mea Add(Double pre, Double rec)
{
lock (SyncLock)
{
...
}
}
Or is it OK and better IMO just use the following?
private static volatile OrderedDictionary _instance;
private static OrderedDictionary Instance
{
get { return _instance ?? (_instance = new OrderedDictionary()); }
}
public static Mea Add(Double pre, Double rec)
{
lock (Instance)
{
...
}
}
Based on Mike Strobel's answer I have done to following changes:
public static class Meas
{
private static readonly OrderedDictionary Instance = new OrderedDictionary();
private static readonly Object SyncLock = new Object();
public static Mea Add(Double pre, Double rec)
{
lock (SyncLock)
{
Instance.Add(pre, rec);
...
}
}
}

Mike Strobel's advice is good advice. To sum up:
Lock only objects that are specifically intended to be locks.
Those lock objects should be private readonly fields that are initialized in their declarations.
Do not try to roll your own threadsafe lazy initialization. Use the Lazy<T> type; it was designed by experts who know what they are doing.
Lock all accesses to the protected variable.
Violate these sensible guidelines when both of the following two conditions are true: (1) you have a empirically demonstrated customer-impacting performance problem and solid proof that going with a more complex low-lock thread safety system is the only reasonable solution to the problem, and (2) you are a leading expert on the implications of processor optimizations on low-lock code. For example, if you are Grant Morrison or Joe Duffy.

The two pieces of code are not equivalent. The former ensures that all threads will always use the same lock object. The latter locks a lazily-initialized object, and there is absolutely nothing preventing multiple instantiations of your _instance dictionary, resulting in contents being lost.
What is the purpose of the lock? Does the serve a purpose other than to guarantee single-initialization of the dictionary? Ignoring that it fails to accomplish this in the second example, if that is its sole intended purpose, then you may consider simply using the Lazy<T> class or a double-check locking pattern.
But since this is a static member (and does not appear to capture outer generic parameters), it will presumably only be instantiated once per AppDomain. In that case, just mark it as readonly and initialize it in the declaration. You're probably not saving much this way.
Since you are concerned with best practices: you should never use the lock construct on a mutable value; this goes for both static and instance fields, as well as locals. It is especially bad practice to lock on a volatile field, as the presence of that keyword indicates that you expect the underlying value to change. If you're going to lock on a field, it should almost always be a readonly field. It's also considered bad practice to lock on a method result; that applies to properties too, as properties are effectively a pair of specially-named accessor methods.

If you do not expose the Instance to other classes, the second approach is okay (but not equivalent). It's best practice to keep the lock object private to the class that is using it as a lock object. Only if other classes can also take this object as lock object you may run into issues.
(For completeness and regarding #Scott Chamberlain comment:)
This assumes that the class of Instance is not using lock (this) which contrary represents bad practice.
Nevertheless, the property could make problems. The null coalescing operator is compiled to a null check + assignment... Therefore you could run into race conditions. You might want to read more about this. But also consider to remove the lazy initialization at all, if possible.

Related

lock variable in C#

I know when to use lock block in C#, but what is not clear to me is lock variable in the parentheses of lock statement. Consider following Singleton Design Pattern from DoFactory:
class LoadBalancer
{
private static LoadBalancer _instance;
private List<string> _servers = new List<string>();
private static object syncLock = new object();
public static LoadBalancer GetLoadBalancer()
{
// Support multithreaded applications through
// 'Double checked locking' pattern which (once
// the instance exists) avoids locking each
// time the method is invoked
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
{
_instance = new LoadBalancer();
}
}
}
return _instance;
}
}
in the above code, i can not understand why we do not use _instance for lock variable instead of `syncLock?
in the above code, i can not understand why we do not use _instance for lock variable instead of `syncLock?
Well you'd be trying to lock on a null reference, for one thing...
Additionally, you'd be locking via mutable field, which is a bad idea. (If the field changes value, then another thread can get into the same code. Not great.) It's generally a good idea to lock via a readonly field.
Also, you'd be locking on a reference which is also returned to callers, who could hold the lock for arbitrarily long periods. I prefer to lock on a reference which is never exposed outside the class - like syncLock.
Finally, this implementation is broken anyway due to the CLI memory model. (It may or may not be broken in the MS implementation, which is a bit stronger. I wouldn't like to bet either way.) The _instance variable should be marked as volatile if you really want to use this approach... but I'd personally avoid double-checked locking anyway. See my article on the singleton pattern for more details.
I haven't used the lock statement much myself.
But my guess is, that it is because you can't lock the instance because it is null.
So you have to make the static object 'synclock' which is only used for locking the part where you actually create the 'instance' variable.
This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking.
http://www.yoda.arachsys.com/csharp/singleton.html

Have I been doing locks wrong this whole time?

I was reading this article about thread safety in Singletons, and it got me thinking that I don't understand the lock method.
In the second version, the author has this:
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Whereas I would've done something more like this:
public sealed class Singleton
{
private static Singleton instance = null;
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (instance)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Why would you use a padlock object, rather than locking the actual object you want to lock?
What would you expect to happen the first time you accessed the Instance property, before you've got an object to lock on?
(Hint: lock(null) goes bang...)
As a separate measure, I almost always avoid locking on "the actual object" - because typically there may well be other code which that reference is exposed to, and I don't necessarily know what that's going to lock on. Even if your version did work, what would happen if some external code wrote:
// Make sure only one thread is ever in this code...
lock (Singleton.Instance)
{
// Do stuff
}
Now no-one else can even get the instance while that code is executing, because they'll end up blocked in the getter. The lock in the getter isn't meant to be guarding against that - it's only meant to be guarding against multiple access within the getter.
The more tightly you can keep control of your locks, the easier it is to reason about them and to avoid deadlocks.
I very occasionally take a lock on a "normal" object if:
I'm not exposing that reference outside that class
I have confidence that the type itself (which will always have a reference to this, of course) won't lock on itself.
(All of this is a reason to avoid locking on this, too, of course...)
Fundamentally, I believe the idea of allowing you to lock on any object was a bad idea in Java, and it was a bad move to copy it in .NET :(
Locking on this or any other non-private object is dangerous because it can lead to deadlocks if someone else also tries to use that object for synchronization.
It's not terribly likely, which is why people can be in the habit of doing it for years without ever getting bitten. But it is still possible, and the cost of a private instance of object probably isn't great enough to justify running the risk.
For locking you can use any kind of object, the type really doesn't matter, it just used as a flag and only one thread can hold it in a time.
It is of course possible to have this as locking param. But I guess the main reason why it's not recommended is that other class somewhere can also use instance of your class as locking object and that can cause strage problems

rationale behind lock inside lock?

I am reviewing an example code in a book and came across the following code(simplified).
In the code, when Subscribe(T subscriber) is called, the thread enters into a lock section.
and then, when code inside the lock calls AddToSubscribers(T subscriber) method, the method has another lock. why is this second lock necessary?
public abstract class SubscriptionManager<T> where T : class
{
private static List<T> subscribers;
private static void AddToSubscribers(T subscriber)
{
lock (typeof(SubscriptionManager<T>))
{
if (subscribers.Contains(subscriber))
return;
subscribers.Add(subscriber);
}
}
public void Subscribe(T subscriber)
{
lock (typeof(SubscriptionManager<T>))
{
AddToSubscribers(subscriber);
}
}
}
In that context, it isn't; however, since locks are re-entrant that can be useful to ensure that any other caller of AddToSubscribers observes the lock. Actually, for that reason I'd say "remove it from Subscribe and just let AddToSubscribers do the locking".
However! A lock on a Type is pretty dangerous. A field would be safer:
// assuming static is correct
private static readonly object syncLock = new object();
and lock(syncLock). Depending on when subscribers is assigned, you might also get away with lock(subscribers) (and no extra field).
I should also note that having an instance method add to static state is pretty.... unusual; IMO Subscribe should be a static method, since it has nothing to do with the current instance.
In the code you posted, it isn't necessary. But then again, the code you posted is incomplete - for example the subscribers list is never initialized.
Locking on typeof(SubscriptionManager) is probably not a good idea either - locking on the subscribers field would be better - but would require the subscribers field to be initialized, e.g.
private static List<T> subscribers = new List<T>();
You probably should read near that sample and see what book talks about.
For that particular case - no, second lock is unnecessary.
Note: The sample is dangerous since it locks on public object (type). Normally one locks on special private object so external code is not able to mistakenly introduce deadlocks by mistakenly locking on the same object.
I also faced a situation once where I had to use nested Lock.
My case was, the function of the second lock maybe called from elsewhere, since it was a static function. However, for your case it won't be necessary since each data member belongs to an Instance and not static..

locking the object inside a property, c#

public ArrayList InputBuffer
{
get { lock (this.in_buffer) { return this.in_buffer; } }
}
is this.in_buffer locked during a call to InputBuffer.Clear?
or does the property simply lock the in_buffer object while it's getting the reference to it; the lock exits, and then that reference is used to Clear?
No, the property locks the reference while it's getting that reference. Pretty pointless, to be honest... this is more common:
private readonly object mutex = new object();
private Foo foo = ...;
public Foo Foo
{
get
{
lock(mutex)
{
return foo;
}
}
}
That lock would only cover the property access itself, and wouldn't provide any protection for operations performed with the Foo. However, it's not the same as not having the lock at all, because so long as the variable is only written while holding the same lock, it ensures that any time you read the Foo property, you're accessing the most recent value of the property... without the lock, there's no memory barrier and you could get a "stale" result.
This is pretty weak, but worth knowing about.
Personally I try to make very few types thread-safe, and those tend to have more appropriate operations... but if you wanted to write code which did modify and read properties from multiple threads, this is one way of doing so. Using volatile can help too, but the semantics of it are hideously subtle.
The object is locked inside the braces of the lock call, and then it is unlocked.
In this case the only code in the lock call is return this.in_buffer;.
So in this case, the in_buffer is not locked during a call to InputBuffer.Clear.
One solution to your problem, using extension methods, is as follows.
private readonly object _bufLock;
class EMClass{
public static void LockedClear(this ArrayList a){
lock(_bufLock){
a.Clear();
}
}
}
Now when you do:
a.LockedClear();
The Clear call will be done in a lock.
You must ensure that the buffer is only accessed inside _bufLocks.
In addition to what others have said about the scope of the lock, remember that you aren't locking the object, you are only locking based on the object instance named.
Common practice is to have a separate lock mutex as Jon Skeet exemplifies.
If you must guarantee synchronized execution while the collection is being cleared, expose a method that clears the collection, have clients call that, and don't expose your underlying implementation details. (Which is good practice anyway - look up encapsulation.)

thread access to variables in use

I was wondering, if i have a multi-core processor and i have multiple threads,is it possible that the program will crash if 2 or more threads access a variable at the same time? How can i block temporarily a variable so that simultaneously access is restricted?
Regards,
Alexandru Badescu
It won't crash, but it might give the wrong results.
To block, you need to make sure that every access is protected via a lock statement on the same monitor:
private readonly object monitor = new object();
private int sharedVariable;
public void MethodThatSetsVariable()
{
lock (monitor)
{
sharedVariable = 5;
}
}
public void MethodThatReadsVariable()
{
int foo;
lock (monitor)
{
foo = sharedVariable;
}
// Use foo now
}
Alternatives:
Use a volatile variable, although the exact behaviour of volatile is hard to understand. (Well, it's beyond me, anyway.)
Use methods on the Interlocked class
Note that both of these are best suited when it's only a single shared variable you're interested in. When you've got to access a set of variables, making sure you only ever see a fully consistent state, locks are the easiest way to go.
Another option - and preferred if at all possible - is to avoid requiring mutable shared state in the first place. It's not always possible, at least without a complete redesign to a messaging-passing architecture - but it's worth aiming for where possible. Immutable types can help to make this easier to achieve.
it is possible that the program will crash if 2 or more threads access a variable at the same time
It is unlikely that the program will crash. It probably won't behave as you expect it to as it will create a race condition.
How can i block temporarily a variable so that multiple access simultaneously is restricted
Using a lock statement.
You could use the lock keyword, or Interlocked class.
e.g.
public class Foo
{
private object barLock = new object();
private int bar;
public void Add(int x)
{
lock (barLock)
{
this.bar += x;
}
}
}
or
public class Foo
{
private int bar;
public void Increment()
{
Interlocked.Increment(ref x);
}
}
I would use the Interlocked class whenever possible, as this is generally the simplest and most efficient (fastest) way to do this, but only certain operations are catered for. For more complex operations, a lock is the way to go.
I would recommend against using the C# volatile keyword as this affects all access to a given field. It's better stick to higher level concepts such as lock or Interlocked.
using a lock statement (which is really syntactic sugar for a Monitor.Enter/Exit)

Categories