Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking a private static object

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);
            ...
        }
    }
}
like image 319
user1615362 Avatar asked Dec 03 '22 21:12

user1615362


1 Answers

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.
like image 93
Eric Lippert Avatar answered Dec 15 '22 21:12

Eric Lippert