Bringing together the Apache Cassandra experts from the community and DataStax.

Want to learn? Have a question? Want to share your expertise? You are in the right place!

Not sure where to begin? Getting Started

 

question

TayYeh avatar image
TayYeh asked erik.merkle answered

Clear Function is Invalid in the Cassandra.Collections.CopyOnWriteDictionary

DataStax C# Driver for Apache Cassandra (.Net 4.5.2)

I think this is an invalid method

private static readonly Dictionary<TKey, TValue> Empty = new Dictionary<TKey, TValue>();
private volatile Dictionary<TKey, TValue> _map;

public CopyOnWriteDictionary()
{
    //Start with an instance without nodes
    _map = Empty;
}

SO, _map and Empty is same object

public void Clear()
{
    _map = Empty;
}

(_map = Empty ) Can't Clear Dictionary, They are same object...

csharp driver
10 |1000 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

1 Answer

erik.merkle avatar image
erik.merkle answered

The Clear() method clears the _map variable in that it resets _map to an empty dictionary. If you look at the rest of the methods in CopyOnWriteDicitonary, you'll see that _map is never added to or removed from directly. All of the modifications are done by cloning the current _map contents, making the modification to the clone, and then setting _map to point to the clone. For example:

        public void Add(TKey key, TValue value)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            lock (_writeLock)
            {
                CloneMapAndAddUnsafe(key, value);
            }
        }

Add calls CloneMapAndAddUnsafe, which does this:

        private void CloneMapAndAddUnsafe(TKey key, TValue value)
        {
            var newMap = new Dictionary<TKey, TValue>(_map)
            {
                { key, value }
            };

            _map = newMap;
        }

Because _map is never modified directly, the static Dictionary "Empty" is never modified either, so it always remains empty. That is why calling Clear() does effectively clear _map as it simply resets _map to the static Empty Dictionary.


Share
10 |1000 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.