1
\$\begingroup\$

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; 
 }
 }
}
asked Nov 1, 2015 at 17:34
\$\endgroup\$
2
  • 4
    \$\begingroup\$ Deinit is very very very very awkward and reeks of the wrong solution being implemented for whatever problem you're solving. \$\endgroup\$ Commented Nov 1, 2015 at 22:58
  • 3
    \$\begingroup\$ @Mat'sMug I second that. To me, having to "init" and "deinit" etc. is an indicator that perhaps the class shouldn't be static to begin with. \$\endgroup\$ Commented Nov 3, 2015 at 10:18

1 Answer 1

1
\$\begingroup\$

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.

answered Nov 3, 2015 at 17:01
\$\endgroup\$
1
  • \$\begingroup\$ +1 for immutable data structures. This is one of the first things I teach new hires when working with threading. \$\endgroup\$ Commented Nov 20, 2015 at 15:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.