Thread safe Parameters class (follow up)

Posted on

Problem

This is a follow up question to my previous question. I am trying to design a thread safe parameters class with only readable getters. Idea is it should be possible to initialize this class once with some parameters – and throughout app I should be able to query values. Deinitialization should also be possible.

Please find below. I am interested if this is thread safe or not, or how much thread safe it is?. This is my real code. Other code related feedback also welcome.

static class Parameters
{
  private static int connectionTimeout; // only getters of these will be visible to outside world
  private static int responseTimeout;  
  private static bool isInit;
  private static readonly object Locker = new object();

  public static bool isInited()
  {
   lock(Locker)
    {
    return isInit;
    }
  }

  public static int ConnectionTimeout()
  {
    lock(Locker)
    {
    if(isInit == false) throw new Exception("init first");
    return connectionTimeout;
    }

  }

  public static int ResponseTimeout()
  {
    lock(Locker)
    {
    if(isInit == false) throw new Exception("init first");
    return responseTimeout;
    }

  }

  public static void init(int ct, int rt)
  {
    lock(Locker)
    {
      if(isInit) throw new Exception ("Already inited");
      isInit = true;
      connectionTimeout= ct;
      responseTimeout= rt; 
    }
  }

  public static void Deinit()
  {

    lock(Locker)
    {
      if(!isInit) throw new Exception ("Already deinited");
      isInit = false;
      connectionTimeout= 0;
      responseTimeout= 0; 
    }
  }


}

Solution

I agree with the comments. I don’t see the advantage of your code over something more like below. If there is a use case you have in mind, please clarify.

public class Parameters
{
    public int ConnectionTimeout {get; private set;} // or a readonly field if you prefer
    public int ResponseTimeout {get; private set;}

    public Parameters(int ct, int rt)
    {
        ConnectionTimeout = ct;
        ResponseTimeout = rt;
    }
}

Threading concerns often disappear when you can use immutable data structures.

Leave a Reply

Your email address will not be published. Required fields are marked *