1 // ConcurrentDictionary.cs
3 // Copyright (c) 2009 Jérémie "Garuma" Laval
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #if NET_4_0 || BOOTSTRAP_NET_4_0
28 using System.Threading;
29 using System.Collections;
30 using System.Collections.Generic;
31 using System.Runtime.Serialization;
33 namespace System.Collections.Concurrent
35 public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>,
36 ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
37 IDictionary, ICollection, IEnumerable
39 IEqualityComparer<TKey> comparer;
41 SplitOrderedList<KeyValuePair<TKey, TValue>> internalDictionary = new SplitOrderedList<KeyValuePair<TKey, TValue>> ();
43 public ConcurrentDictionary () : this (EqualityComparer<TKey>.Default)
47 public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values)
48 : this (values, EqualityComparer<TKey>.Default)
50 foreach (KeyValuePair<TKey, TValue> pair in values)
51 Add (pair.Key, pair.Value);
54 public ConcurrentDictionary (IEqualityComparer<TKey> comparer)
56 this.comparer = comparer;
59 public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values, IEqualityComparer<TKey> comparer)
62 foreach (KeyValuePair<TKey, TValue> pair in values)
63 Add (pair.Key, pair.Value);
67 public ConcurrentDictionary (int concurrencyLevel, int capacity)
68 : this (EqualityComparer<TKey>.Default)
73 public ConcurrentDictionary (int concurrencyLevel,
74 IEnumerable<KeyValuePair<TKey, TValue>> values,
75 IEqualityComparer<TKey> comparer)
76 : this (values, comparer)
82 public ConcurrentDictionary (int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer)
88 void Add (TKey key, TValue value)
90 while (!TryAdd (key, value));
93 void IDictionary<TKey, TValue>.Add (TKey key, TValue value)
98 public bool TryAdd (TKey key, TValue value)
100 return internalDictionary.Insert (Hash (key), Make (key, value));
103 void ICollection<KeyValuePair<TKey,TValue>>.Add (KeyValuePair<TKey, TValue> pair)
105 Add (pair.Key, pair.Value);
108 public TValue AddOrUpdate (TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
110 return internalDictionary.InsertOrUpdate (Hash (key),
111 () => Make (key, addValueFactory (key)),
112 (e) => Make (key, updateValueFactory (key, e.Value))).Value;
115 public TValue AddOrUpdate (TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
117 return AddOrUpdate (key, (_) => addValue, updateValueFactory);
120 TValue AddOrUpdate (TKey key, TValue addValue, TValue updateValue)
122 return internalDictionary.InsertOrUpdate (Hash (key),
123 Make (key, addValue),
124 Make (key, updateValue)).Value;
127 TValue GetValue (TKey key)
130 if (!TryGetValue (key, out temp))
131 // TODO: find a correct Exception
132 throw new ArgumentException ("Not a valid key for this dictionary", "key");
136 public bool TryGetValue (TKey key, out TValue value)
138 KeyValuePair<TKey, TValue> pair;
139 bool result = internalDictionary.Find (Hash (key), out pair);
145 public bool TryUpdate (TKey key, TValue newValue, TValue comparand)
147 return internalDictionary.CompareExchange (Hash (key), Make (key, newValue), (e) => e.Value.Equals (comparand));
150 public TValue this[TKey key] {
152 return GetValue (key);
155 AddOrUpdate (key, value, value);
159 public TValue GetOrAdd (TKey key, Func<TKey, TValue> valueFactory)
161 return internalDictionary.InsertOrGet (Hash (key), Make (key, default(TValue)), () => Make (key, valueFactory (key))).Value;
164 public TValue GetOrAdd (TKey key, TValue value)
166 return internalDictionary.InsertOrGet (Hash (key), Make (key, value), null).Value;
169 public bool TryRemove (TKey key, out TValue value)
171 KeyValuePair<TKey, TValue> data;
172 bool result = internalDictionary.Delete (Hash (key), out data);
177 bool Remove (TKey key)
181 return TryRemove (key, out dummy);
184 bool IDictionary<TKey, TValue>.Remove (TKey key)
189 bool ICollection<KeyValuePair<TKey,TValue>>.Remove (KeyValuePair<TKey,TValue> pair)
191 return Remove (pair.Key);
194 public bool ContainsKey (TKey key)
196 KeyValuePair<TKey, TValue> dummy;
197 return internalDictionary.Find (Hash (key), out dummy);
200 bool IDictionary.Contains (object key)
205 return ContainsKey ((TKey)key);
208 void IDictionary.Remove (object key)
216 object IDictionary.this [object key]
220 throw new ArgumentException ("key isn't of correct type", "key");
222 return this[(TKey)key];
225 if (!(key is TKey) || !(value is TValue))
226 throw new ArgumentException ("key or value aren't of correct type");
228 this[(TKey)key] = (TValue)value;
232 void IDictionary.Add (object key, object value)
234 if (!(key is TKey) || !(value is TValue))
235 throw new ArgumentException ("key or value aren't of correct type");
237 Add ((TKey)key, (TValue)value);
240 bool ICollection<KeyValuePair<TKey,TValue>>.Contains (KeyValuePair<TKey, TValue> pair)
242 return ContainsKey (pair.Key);
245 public KeyValuePair<TKey,TValue>[] ToArray ()
247 // This is most certainly not optimum but there is
248 // not a lot of possibilities
250 return new List<KeyValuePair<TKey,TValue>> (this).ToArray ();
256 internalDictionary = new SplitOrderedList<KeyValuePair<TKey, TValue>> ();
261 return internalDictionary.Count;
265 public bool IsEmpty {
271 bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
277 bool IDictionary.IsReadOnly {
283 public ICollection<TKey> Keys {
285 return GetPart<TKey> ((kvp) => kvp.Key);
289 public ICollection<TValue> Values {
291 return GetPart<TValue> ((kvp) => kvp.Value);
295 ICollection IDictionary.Keys {
297 return (ICollection)Keys;
301 ICollection IDictionary.Values {
303 return (ICollection)Values;
307 ICollection<T> GetPart<T> (Func<KeyValuePair<TKey, TValue>, T> extractor)
309 List<T> temp = new List<T> ();
311 foreach (KeyValuePair<TKey, TValue> kvp in this)
312 temp.Add (extractor (kvp));
314 return temp.AsReadOnly ();
317 void ICollection.CopyTo (Array array, int startIndex)
319 KeyValuePair<TKey, TValue>[] arr = array as KeyValuePair<TKey, TValue>[];
323 CopyTo (arr, startIndex, Count);
326 void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
328 CopyTo (array, startIndex, Count);
331 void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
333 CopyTo (array, startIndex);
336 void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex, int num)
338 foreach (var kvp in this) {
339 array [startIndex++] = kvp;
346 public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
348 return GetEnumeratorInternal ();
351 IEnumerator IEnumerable.GetEnumerator ()
353 return (IEnumerator)GetEnumeratorInternal ();
356 IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorInternal ()
358 return internalDictionary.GetEnumerator ();
361 IDictionaryEnumerator IDictionary.GetEnumerator ()
363 return new ConcurrentDictionaryEnumerator (GetEnumeratorInternal ());
366 class ConcurrentDictionaryEnumerator : IDictionaryEnumerator
368 IEnumerator<KeyValuePair<TKey, TValue>> internalEnum;
370 public ConcurrentDictionaryEnumerator (IEnumerator<KeyValuePair<TKey, TValue>> internalEnum)
372 this.internalEnum = internalEnum;
375 public bool MoveNext ()
377 return internalEnum.MoveNext ();
382 internalEnum.Reset ();
385 public object Current {
391 public DictionaryEntry Entry {
393 KeyValuePair<TKey, TValue> current = internalEnum.Current;
394 return new DictionaryEntry (current.Key, current.Value);
400 return internalEnum.Current.Key;
404 public object Value {
406 return internalEnum.Current.Value;
411 object ICollection.SyncRoot {
417 bool IDictionary.IsFixedSize {
423 bool ICollection.IsSynchronized {
427 static KeyValuePair<U, V> Make<U, V> (U key, V value)
429 return new KeyValuePair<U, V> (key, value);
434 return (uint)comparer.GetHashCode (key);