Santosh
Santosh

Reputation: 149

locking static variable

I have a following class at server-side.

public class Sample
{
    private enum Status
    {
        NotEvaluated,
        Yes,
        No
    }

    private static object _lockObj = new object();
    private static Status _status = Status.NotEvaluated;

    public static Status GetStatus()
    {
        if (_status == Status.NotEvaluated)
        {
            lock (_lockObj)
            {
                if (_status == Status.NotEvaluated)
                {
                    //some evaluation code which sets status to either Yes/No;
                    _status = Status.Yes;
                }
            }
        }

        return _status;
    }

}

Is anything wrong in locking mechanism above? do i need to lock at all? Because it is server-side (multiple requests will be there) and the variable is static i would think it should be locked at the time of evaluation.

correct me if i am wrong.

Thanks

Upvotes: 3

Views: 12038

Answers (1)

gangelo
gangelo

Reputation: 3182

You do not/should not have the outer check for "if (_status == Status.NotEvaluated)". While it appears that nothing "bad" would happen if you left it it, there is the possibility that a second thread may enter that "if" needlessly, just prior to the first thread setting _status to Status.Yes. And yes, you need to lock:

"As a basic rule, you need to lock around accessing any writable shared field." http://www.albahari.com/threading/part2.aspx

lock (_lockObj)
   {
      if (_status == Status.NotEvaluated)
         {
            // some evaluation code which sets status to either Yes/No;
            _status = Status.Yes;
         }
      return _status;    
  }

Upvotes: 2

Related Questions