views:

18

answers:

2

I have a CacheHelper class to facilitate interaction with the cache. I want to use a static int field to specify my cache timeout. The field is initially set to a const default value but I want to provide a way for the application to change the default timeout value.

Do you need to lock when modifying a static value type? Is the lock in the setter necessary? Are there any other problems you can see here? Sorry, I'm still pretty dumb when it comes to multithreading.

Thanks.

public static class CacheHelper
{
    private static object _SyncRoot;
    private static int _TimeoutInMinutes = CacheDefaults.TimeoutInMinutes; 

    public static int TimeoutInMinutes
    {
        get
        {
            return _TimeoutInMinutes;
        }
        set
        {
            lock (_SyncRoot)
            {
                if (_TimeoutInMinutes != value)
                {
                    _TimeoutInMinutes = value;
                }
            }
        }
    }

    public static void Insert(string key, Object data)
    {
        if (HttpContext.Current != null && data != null)
        {
            HttpContext.Current.Cache.Insert(key, data, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(CacheHelper.TimeoutInMinutes));
        }
    }
}
+1  A: 

You could use a volatile variable instead... but you need something, otherwise it's possible that a value written by one thread would never be seen by another.

Note that for "larger" types such as double or long you really should use a lock or the Interlocked class, as modifications to those values may not be atomic.

Jon Skeet
Is it okay to combine the use of volatile and a lock? The timeout value is going to be read from a lot but written to rarely (if ever, other than on application startup by code in Global.asax).
whatispunk
@whatispunk: Well, it won't do any harm... but it won't help much either. Why would you use both? Volatile is enough for the `int` case...
Jon Skeet
@Jon: Thanks for your help. I'm just trying to wrap my head around what all of this means. There seem to be varying opinions about the use of volatile and I don't even understand most of the lingo behind it, i.e. multiple CPUs and ordering of instructions, etc. Definitely gotta take some time to read about multithreading.
whatispunk
A: 

You don't need to lock here if the client of CacheHelper does somthing like

CacheHelper.TimeoutInMinutes = input.Value; 

Since it doesn't rely on the previous value.

If your client does something like

CacheHelper.TimeoutInMinutes += input.Value; 

Then you'll need to do some locking

.

Conrad Frix