2 // ConcurrentSkipList.cs
4 // Copyright (c) 2009 Jérémie "Garuma" Laval
6 // Permission is hereby granted, free of charge, to any person obtaining a copy
7 // of this software and associated documentation files (the "Software"), to deal
8 // in the Software without restriction, including without limitation the rights
9 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 // copies of the Software, and to permit persons to whom the Software is
11 // furnished to do so, subject to the following conditions:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 using System.Threading;
28 using System.Collections;
29 using System.Collections.Generic;
30 using System.Runtime.Serialization;
32 namespace System.Collections.Concurrent
34 public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>,
35 ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
36 IDictionary, ICollection, IEnumerable
40 public readonly TKey Key;
43 public Pair (TKey key, TValue value)
49 public override bool Equals (object obj)
51 Pair rhs = obj as Pair;
52 return rhs == null ? false : Key.Equals (rhs.Key) && Value.Equals (rhs.Value);
55 public override int GetHashCode ()
57 return Key.GetHashCode ();
61 class Basket: List<Pair>
65 // Assumption: a List<T> is never empty
66 ConcurrentSkipList<Basket> container
67 = new ConcurrentSkipList<Basket> ((value) => value[0].GetHashCode ());
69 int stamp = int.MinValue;
70 IEqualityComparer<TKey> comparer;
72 public ConcurrentDictionary () : this (EqualityComparer<TKey>.Default)
76 public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values)
77 : this (values, EqualityComparer<TKey>.Default)
79 foreach (KeyValuePair<TKey, TValue> pair in values)
80 Add (pair.Key, pair.Value);
83 public ConcurrentDictionary (IEqualityComparer<TKey> comparer)
85 this.comparer = comparer;
88 public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values, IEqualityComparer<TKey> comparer)
91 foreach (KeyValuePair<TKey, TValue> pair in values)
92 Add (pair.Key, pair.Value);
96 public ConcurrentDictionary (int concurrencyLevel, int capacity)
97 : this (EqualityComparer<TKey>.Default)
102 public ConcurrentDictionary (int concurrencyLevel,
103 IEnumerable<KeyValuePair<TKey, TValue>> values,
104 IEqualityComparer<TKey> comparer)
105 : this (values, comparer)
111 public ConcurrentDictionary (int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer)
117 void Add (TKey key, TValue value)
119 while (!TryAdd (key, value));
122 void IDictionary<TKey, TValue>.Add (TKey key, TValue value)
127 public bool TryAdd (TKey key, TValue value)
129 Interlocked.Increment (ref count);
130 Interlocked.Increment (ref stamp);
133 // Add a value to an existing basket
134 if (TryGetBasket (key, out basket)) {
135 // Find a maybe more sexy locking scheme later
137 foreach (var p in basket) {
138 if (comparer.Equals (p.Key, key))
139 throw new ArgumentException ("An element with the same key already exists");
141 basket.Add (new Pair (key, value));
145 basket = new Basket ();
146 basket.Add (new Pair (key, value));
147 return container.TryAdd (basket);
153 void ICollection<KeyValuePair<TKey,TValue>>.Add (KeyValuePair<TKey, TValue> pair)
155 Add (pair.Key, pair.Value);
158 TValue GetValue (TKey key)
161 if (!TryGetValue (key, out temp))
162 // TODO: find a correct Exception
163 throw new ArgumentException ("Not a valid key for this dictionary", "key");
167 public bool TryGetValue (TKey key, out TValue value)
170 value = default (TValue);
172 if (!TryGetBasket (key, out basket))
176 Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
185 public bool TryUpdate (TKey key, TValue newValue, TValue comparand)
188 if (!TryGetBasket (key, out basket))
192 Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
193 if (pair.Value.Equals (comparand)) {
194 pair.Value = newValue;
203 public TValue this[TKey key] {
205 return GetValue (key);
209 if (!TryGetBasket (key, out basket)) {
214 Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
216 throw new InvalidOperationException ("pair is null, shouldn't be");
218 Interlocked.Increment (ref stamp);
223 public bool TryRemove(TKey key, out TValue value)
225 value = default (TValue);
228 if (!TryGetBasket (key, out b))
232 TValue temp = default (TValue);
233 // Should always be == 1 but who know
234 bool result = b.RemoveAll ((p) => {
235 bool r = comparer.Equals (p.Key, key);
236 if (r) temp = p.Value;
242 Interlocked.Decrement (ref count);
248 bool Remove (TKey key)
252 return TryRemove (key, out dummy);
255 bool IDictionary<TKey, TValue>.Remove (TKey key)
260 bool ICollection<KeyValuePair<TKey,TValue>>.Remove (KeyValuePair<TKey,TValue> pair)
262 return Remove (pair.Key);
265 public bool ContainsKey (TKey key)
267 return container.ContainsFromHash (key.GetHashCode ());
270 bool IDictionary.Contains (object key)
275 return ContainsKey ((TKey)key);
278 void IDictionary.Remove (object key)
286 object IDictionary.this [object key]
290 throw new ArgumentException ("key isn't of correct type", "key");
292 return this[(TKey)key];
295 if (!(key is TKey) || !(value is TValue))
296 throw new ArgumentException ("key or value aren't of correct type");
298 this[(TKey)key] = (TValue)value;
302 void IDictionary.Add (object key, object value)
304 if (!(key is TKey) || !(value is TValue))
305 throw new ArgumentException ("key or value aren't of correct type");
307 Add ((TKey)key, (TValue)value);
310 bool ICollection<KeyValuePair<TKey,TValue>>.Contains (KeyValuePair<TKey, TValue> pair)
312 return ContainsKey (pair.Key);
315 public KeyValuePair<TKey,TValue>[] ToArray ()
317 // This is most certainly not optimum but there is
318 // not a lot of possibilities
320 return new List<KeyValuePair<TKey,TValue>> (this).ToArray ();
326 container = new ConcurrentSkipList<Basket> ((value) => value [0].GetHashCode ());
335 public bool IsEmpty {
341 bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
347 bool IDictionary.IsReadOnly {
353 public ICollection<TKey> Keys {
355 return GetPart<TKey> ((kvp) => kvp.Key);
359 public ICollection<TValue> Values {
361 return GetPart<TValue> ((kvp) => kvp.Value);
365 ICollection IDictionary.Keys {
367 return (ICollection)Keys;
371 ICollection IDictionary.Values {
373 return (ICollection)Values;
377 ICollection<T> GetPart<T> (Func<KeyValuePair<TKey, TValue>, T> extractor)
379 List<T> temp = new List<T> ();
381 foreach (KeyValuePair<TKey, TValue> kvp in this)
382 temp.Add (extractor (kvp));
384 return temp.AsReadOnly ();
387 void ICollection.CopyTo (Array array, int startIndex)
389 KeyValuePair<TKey, TValue>[] arr = array as KeyValuePair<TKey, TValue>[];
393 CopyTo (arr, startIndex, count);
396 void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
398 CopyTo (array, startIndex, count);
401 void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
403 CopyTo (array, startIndex);
406 void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex, int num)
408 // TODO: This is quite unsafe as the count value will likely change during
409 // the copying. Watchout for IndexOutOfRange thingies
410 if (array.Length <= count + startIndex)
411 throw new InvalidOperationException ("The array isn't big enough");
415 foreach (Basket b in container) {
417 foreach (Pair p in b) {
420 array[i++] = new KeyValuePair<TKey, TValue> (p.Key, p.Value);
426 public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
428 return GetEnumeratorInternal ();
431 IEnumerator IEnumerable.GetEnumerator ()
433 return (IEnumerator)GetEnumeratorInternal ();
436 IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorInternal ()
438 foreach (Basket b in container) {
440 foreach (Pair p in b)
441 yield return new KeyValuePair<TKey, TValue> (p.Key, p.Value);
446 IDictionaryEnumerator IDictionary.GetEnumerator ()
448 return new ConcurrentDictionaryEnumerator (GetEnumeratorInternal ());
451 class ConcurrentDictionaryEnumerator : IDictionaryEnumerator
453 IEnumerator<KeyValuePair<TKey, TValue>> internalEnum;
455 public ConcurrentDictionaryEnumerator (IEnumerator<KeyValuePair<TKey, TValue>> internalEnum)
457 this.internalEnum = internalEnum;
460 public bool MoveNext ()
462 return internalEnum.MoveNext ();
467 internalEnum.Reset ();
470 public object Current {
476 public DictionaryEntry Entry {
478 KeyValuePair<TKey, TValue> current = internalEnum.Current;
479 return new DictionaryEntry (current.Key, current.Value);
485 return internalEnum.Current.Key;
489 public object Value {
491 return internalEnum.Current.Value;
496 object ICollection.SyncRoot {
503 bool IDictionary.IsFixedSize {
509 bool ICollection.IsSynchronized {
513 bool TryGetBasket (TKey key, out Basket basket)
516 if (!container.GetFromHash (key.GetHashCode (), out basket))