ConcurrentDictionary.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. #if NET_4_0
  2. // ConcurrentSkipList.cs
  3. //
  4. // Copyright (c) 2009 Jérémie "Garuma" Laval
  5. //
  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:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  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
  22. // THE SOFTWARE.
  23. //
  24. //
  25. using System;
  26. using System.Threading;
  27. using System.Collections;
  28. using System.Collections.Generic;
  29. using System.Runtime.Serialization;
  30. namespace System.Collections.Concurrent
  31. {
  32. public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>,
  33. ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
  34. IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback
  35. {
  36. class Pair
  37. {
  38. public readonly TKey Key;
  39. public TValue Value;
  40. public Pair (TKey key, TValue value)
  41. {
  42. Key = key;
  43. Value = value;
  44. }
  45. public override bool Equals (object obj)
  46. {
  47. Pair rhs = obj as Pair;
  48. return rhs == null ? false : Key.Equals (rhs.Key) && Value.Equals (rhs.Value);
  49. }
  50. public override int GetHashCode ()
  51. {
  52. return Key.GetHashCode ();
  53. }
  54. }
  55. class Basket: List<Pair>
  56. {
  57. }
  58. // Assumption: a List<T> is never empty
  59. ConcurrentSkipList<Basket> container
  60. = new ConcurrentSkipList<Basket> ((value) => value[0].GetHashCode ());
  61. int count;
  62. int stamp = int.MinValue;
  63. IEqualityComparer<TKey> comparer;
  64. public ConcurrentDictionary () : this (EqualityComparer<TKey>.Default)
  65. {
  66. }
  67. public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values)
  68. : this (values, EqualityComparer<TKey>.Default)
  69. {
  70. foreach (KeyValuePair<TKey, TValue> pair in values)
  71. Add (pair.Key, pair.Value);
  72. }
  73. public ConcurrentDictionary (IEqualityComparer<TKey> comparer)
  74. {
  75. this.comparer = comparer;
  76. }
  77. public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values, IEqualityComparer<TKey> comparer)
  78. : this (comparer)
  79. {
  80. foreach (KeyValuePair<TKey, TValue> pair in values)
  81. Add (pair.Key, pair.Value);
  82. }
  83. // Parameters unused
  84. public ConcurrentDictionary (int concurrencyLevel, int capacity)
  85. : this (EqualityComparer<TKey>.Default)
  86. {
  87. }
  88. public ConcurrentDictionary (int concurrencyLevel,
  89. IEnumerable<KeyValuePair<TKey, TValue>> values,
  90. IEqualityComparer<TKey> comparer)
  91. : this (values, comparer)
  92. {
  93. }
  94. // Parameters unused
  95. public ConcurrentDictionary (int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer)
  96. : this (comparer)
  97. {
  98. }
  99. [MonoTODO]
  100. protected ConcurrentDictionary (SerializationInfo info, StreamingContext context)
  101. {
  102. throw new NotImplementedException ();
  103. }
  104. void Add (TKey key, TValue value)
  105. {
  106. while (!TryAdd (key, value));
  107. }
  108. void IDictionary<TKey, TValue>.Add (TKey key, TValue value)
  109. {
  110. Add (key, value);
  111. }
  112. public bool TryAdd (TKey key, TValue value)
  113. {
  114. Interlocked.Increment (ref count);
  115. Interlocked.Increment (ref stamp);
  116. Basket basket;
  117. // Add a value to an existing basket
  118. if (TryGetBasket (key, out basket)) {
  119. // Find a maybe more sexy locking scheme later
  120. lock (basket) {
  121. foreach (var p in basket) {
  122. if (comparer.Equals (p.Key, key))
  123. throw new ArgumentException ("An element with the same key already exists");
  124. }
  125. basket.Add (new Pair (key, value));
  126. }
  127. } else {
  128. // Add a new basket
  129. basket = new Basket ();
  130. basket.Add (new Pair (key, value));
  131. return container.TryAdd (basket);
  132. }
  133. return true;
  134. }
  135. void ICollection<KeyValuePair<TKey,TValue>>.Add (KeyValuePair<TKey, TValue> pair)
  136. {
  137. Add (pair.Key, pair.Value);
  138. }
  139. TValue GetValue (TKey key)
  140. {
  141. TValue temp;
  142. if (!TryGetValue (key, out temp))
  143. // TODO: find a correct Exception
  144. throw new ArgumentException ("Not a valid key for this dictionary", "key");
  145. return temp;
  146. }
  147. public bool TryGetValue (TKey key, out TValue value)
  148. {
  149. Basket basket;
  150. value = default (TValue);
  151. if (!TryGetBasket (key, out basket))
  152. return false;
  153. lock (basket) {
  154. Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
  155. if (pair == null)
  156. return false;
  157. value = pair.Value;
  158. }
  159. return true;
  160. }
  161. public bool TryUpdate (TKey key, TValue newValue, TValue comparand)
  162. {
  163. Basket basket;
  164. if (!TryGetBasket (key, out basket))
  165. return false;
  166. lock (basket) {
  167. Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
  168. if (pair.Value.Equals (comparand)) {
  169. pair.Value = newValue;
  170. return true;
  171. }
  172. }
  173. return false;
  174. }
  175. public TValue this[TKey key] {
  176. get {
  177. return GetValue (key);
  178. }
  179. set {
  180. Basket basket;
  181. if (!TryGetBasket (key, out basket)) {
  182. Add (key, value);
  183. return;
  184. }
  185. lock (basket) {
  186. Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
  187. if (pair == null)
  188. throw new InvalidOperationException ("pair is null, shouldn't be");
  189. pair.Value = value;
  190. Interlocked.Increment (ref stamp);
  191. }
  192. }
  193. }
  194. public bool TryRemove(TKey key, out TValue value)
  195. {
  196. value = default (TValue);
  197. Basket b;
  198. if (!TryGetBasket (key, out b))
  199. return false;
  200. lock (b) {
  201. TValue temp = default (TValue);
  202. // Should always be == 1 but who know
  203. bool result = b.RemoveAll ((p) => {
  204. bool r = comparer.Equals (p.Key, key);
  205. if (r) temp = p.Value;
  206. return r;
  207. }) >= 1;
  208. value = temp;
  209. if (result)
  210. Interlocked.Decrement (ref count);
  211. return result;
  212. }
  213. }
  214. bool Remove (TKey key)
  215. {
  216. TValue dummy;
  217. return TryRemove (key, out dummy);
  218. }
  219. bool IDictionary<TKey, TValue>.Remove (TKey key)
  220. {
  221. return Remove (key);
  222. }
  223. bool ICollection<KeyValuePair<TKey,TValue>>.Remove (KeyValuePair<TKey,TValue> pair)
  224. {
  225. return Remove (pair.Key);
  226. }
  227. public bool ContainsKey (TKey key)
  228. {
  229. return container.ContainsFromHash (key.GetHashCode ());
  230. }
  231. bool IDictionary.Contains (object key)
  232. {
  233. if (!(key is TKey))
  234. return false;
  235. return ContainsKey ((TKey)key);
  236. }
  237. void IDictionary.Remove (object key)
  238. {
  239. if (!(key is TKey))
  240. return;
  241. Remove ((TKey)key);
  242. }
  243. object IDictionary.this [object key]
  244. {
  245. get {
  246. if (!(key is TKey))
  247. throw new ArgumentException ("key isn't of correct type", "key");
  248. return this[(TKey)key];
  249. }
  250. set {
  251. if (!(key is TKey) || !(value is TValue))
  252. throw new ArgumentException ("key or value aren't of correct type");
  253. this[(TKey)key] = (TValue)value;
  254. }
  255. }
  256. void IDictionary.Add (object key, object value)
  257. {
  258. if (!(key is TKey) || !(value is TValue))
  259. throw new ArgumentException ("key or value aren't of correct type");
  260. Add ((TKey)key, (TValue)value);
  261. }
  262. bool ICollection<KeyValuePair<TKey,TValue>>.Contains (KeyValuePair<TKey, TValue> pair)
  263. {
  264. return ContainsKey (pair.Key);
  265. }
  266. public KeyValuePair<TKey,TValue>[] ToArray ()
  267. {
  268. // This is most certainly not optimum but there is
  269. // not a lot of possibilities
  270. return new List<KeyValuePair<TKey,TValue>> (this).ToArray ();
  271. }
  272. public void Clear()
  273. {
  274. // Pronk
  275. container = new ConcurrentSkipList<Basket> ((value) => value [0].GetHashCode ());
  276. }
  277. public int Count {
  278. get {
  279. return count;
  280. }
  281. }
  282. public bool IsEmpty {
  283. get {
  284. return count == 0;
  285. }
  286. }
  287. bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
  288. get {
  289. return false;
  290. }
  291. }
  292. bool IDictionary.IsReadOnly {
  293. get {
  294. return false;
  295. }
  296. }
  297. public ICollection<TKey> Keys {
  298. get {
  299. return GetPart<TKey> ((kvp) => kvp.Key);
  300. }
  301. }
  302. public ICollection<TValue> Values {
  303. get {
  304. return GetPart<TValue> ((kvp) => kvp.Value);
  305. }
  306. }
  307. ICollection IDictionary.Keys {
  308. get {
  309. return (ICollection)Keys;
  310. }
  311. }
  312. ICollection IDictionary.Values {
  313. get {
  314. return (ICollection)Values;
  315. }
  316. }
  317. ICollection<T> GetPart<T> (Func<KeyValuePair<TKey, TValue>, T> extractor)
  318. {
  319. List<T> temp = new List<T> ();
  320. foreach (KeyValuePair<TKey, TValue> kvp in this)
  321. temp.Add (extractor (kvp));
  322. return temp.AsReadOnly ();
  323. }
  324. void ICollection.CopyTo (Array array, int startIndex)
  325. {
  326. KeyValuePair<TKey, TValue>[] arr = array as KeyValuePair<TKey, TValue>[];
  327. if (arr == null)
  328. return;
  329. CopyTo (arr, startIndex, count);
  330. }
  331. void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
  332. {
  333. CopyTo (array, startIndex, count);
  334. }
  335. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
  336. {
  337. CopyTo (array, startIndex);
  338. }
  339. void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex, int num)
  340. {
  341. // TODO: This is quite unsafe as the count value will likely change during
  342. // the copying. Watchout for IndexOutOfRange thingies
  343. if (array.Length <= count + startIndex)
  344. throw new InvalidOperationException ("The array isn't big enough");
  345. int i = startIndex;
  346. foreach (Basket b in container) {
  347. lock (b) {
  348. foreach (Pair p in b) {
  349. if (i >= num)
  350. break;
  351. array[i++] = new KeyValuePair<TKey, TValue> (p.Key, p.Value);
  352. }
  353. }
  354. }
  355. }
  356. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
  357. {
  358. return GetEnumeratorInternal ();
  359. }
  360. IEnumerator IEnumerable.GetEnumerator ()
  361. {
  362. return (IEnumerator)GetEnumeratorInternal ();
  363. }
  364. IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorInternal ()
  365. {
  366. foreach (Basket b in container) {
  367. lock (b) {
  368. foreach (Pair p in b)
  369. yield return new KeyValuePair<TKey, TValue> (p.Key, p.Value);
  370. }
  371. }
  372. }
  373. IDictionaryEnumerator IDictionary.GetEnumerator ()
  374. {
  375. return new ConcurrentDictionaryEnumerator (GetEnumeratorInternal ());
  376. }
  377. class ConcurrentDictionaryEnumerator : IDictionaryEnumerator
  378. {
  379. IEnumerator<KeyValuePair<TKey, TValue>> internalEnum;
  380. public ConcurrentDictionaryEnumerator (IEnumerator<KeyValuePair<TKey, TValue>> internalEnum)
  381. {
  382. this.internalEnum = internalEnum;
  383. }
  384. public bool MoveNext ()
  385. {
  386. return internalEnum.MoveNext ();
  387. }
  388. public void Reset ()
  389. {
  390. internalEnum.Reset ();
  391. }
  392. public object Current {
  393. get {
  394. return Entry;
  395. }
  396. }
  397. public DictionaryEntry Entry {
  398. get {
  399. KeyValuePair<TKey, TValue> current = internalEnum.Current;
  400. return new DictionaryEntry (current.Key, current.Value);
  401. }
  402. }
  403. public object Key {
  404. get {
  405. return internalEnum.Current.Key;
  406. }
  407. }
  408. public object Value {
  409. get {
  410. return internalEnum.Current.Value;
  411. }
  412. }
  413. }
  414. object ICollection.SyncRoot {
  415. get {
  416. return this;
  417. }
  418. }
  419. bool IDictionary.IsFixedSize {
  420. get {
  421. return false;
  422. }
  423. }
  424. [MonoTODO]
  425. protected virtual void GetObjectData (SerializationInfo info, StreamingContext context)
  426. {
  427. throw new NotImplementedException ();
  428. }
  429. [MonoTODO]
  430. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  431. {
  432. GetObjectData (info, context);
  433. }
  434. bool ICollection.IsSynchronized {
  435. get { return true; }
  436. }
  437. [MonoTODO]
  438. protected virtual void OnDeserialization (object sender)
  439. {
  440. throw new NotImplementedException ();
  441. }
  442. void IDeserializationCallback.OnDeserialization (object sender)
  443. {
  444. OnDeserialization (sender);
  445. }
  446. bool TryGetBasket (TKey key, out Basket basket)
  447. {
  448. basket = null;
  449. if (!container.GetFromHash (key.GetHashCode (), out basket))
  450. return false;
  451. return true;
  452. }
  453. }
  454. }
  455. #endif