Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Thread Safe Dictionary (ConcurrentDictionary)

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 469
    Comment on it

    .NET has introduced a thread safe dictionary (4.0 onward). Essentially, it does something similar like conventional dictionary plus lock system. Read the MSDN documentation for the same at following link: http://msdn.microsoft.com/en-us/library/ee378677(v=vs.110).aspx

    The .NET implementation of dictionary has only caveat, it doesn't guarantee of insertion of element, if traffic is heavy. Following is MSDN remarks in this context

    If you call GetOrAdd simultaneously on different threads, addValueFactory may be called multiple times, but its key/value pair might not be added to the dictionary for every call.

    We should still use .NET version of thread safe dictionary (known as ConcurrentDictionary) due to two reasons:

    1. It is apparently fast for most common scenarios (especially when read is dominating write)
    2. Our code readability will improve significantly (by avoiding lock code overhead)

    What does this mean to you in term of action items?

    1. Start using ConcurrentDictionary now onward in place of regular Dictionary
    2. Replace all regular Dictionary (with or without lock) objects with ConcurrentDictionary

    How do we mitigate the known caveat with ConcurrentDictionary?

    Avoid using the dictionary value immediately after assigning the value. See the following example for the same.

    Wrong:

    static ConcurrentDictionary<int, string> userIDNameMap = new ConcurrentDictionary<int, string>();
    
        public string GetUserName(int id)
        {
            if (!userIDNameMap.ContainsKey(id))
            {
                userIDNameMap[id] = GetUserNameFromDB(id);
            }
            return userIDNameMap[id]; //Remember concurrent dictionary does not guarantee addition of the object
        }
    

    Right:

    static ConcurrentDictionary<int, string> userIDNameMap = new ConcurrentDictionary<int, string>();
    
        public string GetUserName(int id)
        {
            string userName = string.Empty;
            if (userIDNameMap.ContainsKey(id))
            {
                userName = userIDNameMap[id];
            }
            else
            {
                userName = GetUserNameFromDB(id);
                userIDNameMap[id] = userName;
            }
            return userName;
        }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: