3

I want to code an auto clear cache which in real scenario clears all items in cache once in many hours but has constant read hits. Since clearing and reading are from different threads this data structure needs to be thread safe. Want to avoid locks if possible with this constant read but very seldom write. With _cache marked as volatile and CleartheCache() being only an assignment (atomic) is this threadsafe ?

public class AutoClearCache
{
   volatile IDictionary<Key,Resource> _cache = new Dictionary<Key, Resource>();

   public AutoClearCache(TimeSpan autocleanInterval)
   {
       var observable = Observable.Interval(autocleanInterval);
       observable.Subscribe((r) => CleartheCache());
   }

   private void CleartheCache()
   {
       _cache = new Dictionary<Key, Resource>();
   }
Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
Ira
  • 734
  • 10
  • 7
  • 1
    Your question is too broad because it is covering two languages (Java and C#) in which `volatile` means significantly different things. Since you are apparently more interested in C#, remove the Java tag. – Stephen C Sep 24 '16 at 07:20

1 Answers1

2

Volatile keyword doesn't make a Data Structure thread safe in C#, its sole aim is to tell the compiler that this Data Structure is accessed by multiple threads or outside the program scope, so don't optimize various operations on it by caching its value, let it be evaluated every time, check here

IDictionary<Key,Resource> _cache is not thread safe in the current form, preferably either use a Thread safe collection like ConcurrentDictionary or during Write operation use a Synchronization construct like lock to restrict the access.

Community
  • 1
  • 1
Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
  • @StephenC I have modified my answer and pointed to a different answer on same question as earlier, which seems to be much more plausible, as its pointing to the documentation – Mrinal Kamboj Sep 24 '16 at 07:22
  • @StephenC, I am not disagreeing with you, this is a possible issue, with my limited knowledge of Java, I have pointed it to a better link now, thanks for the clarification. – Mrinal Kamboj Sep 24 '16 at 07:25
  • The Answer you have linked to now is correct about Java. I am not qualified to talk about C# – Stephen C Sep 24 '16 at 07:26