ConcurrentDictionary.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. /*
  3. * WARNING: Auto-generated file (7/18/2012 4:59:53 PM)
  4. *
  5. * Stripped down code based on ndp\clr\src\BCL\System\Collections\Concurrent\ConcurrentDictionary.cs
  6. */
  7. #if NO_CDS_COLLECTIONS
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Collections.ObjectModel;
  11. using System.Diagnostics.CodeAnalysis;
  12. using System.Reflection;
  13. using System.Threading;
  14. namespace System.Collections.Concurrent
  15. {
  16. internal class ConcurrentDictionary<TKey, TValue>
  17. {
  18. /* >>> Code copied from the Array class */
  19. // We impose limits on maximum array lenght in each dimension to allow efficient
  20. // implementation of advanced range check elimination in future.
  21. // Keep in sync with vm\gcscan.cpp and HashHelpers.MaxPrimeArrayLength.
  22. internal const int MaxArrayLength = 0X7FEFFFFF;
  23. /* <<< Code copied from the Array class */
  24. private class Tables
  25. {
  26. internal readonly Node[] m_buckets; // A singly-linked list for each bucket.
  27. internal readonly object[] m_locks; // A set of locks, each guarding a section of the table.
  28. internal volatile int[] m_countPerLock; // The number of elements guarded by each lock.
  29. internal Tables(Node[] buckets, object[] locks, int[] countPerLock)
  30. {
  31. m_buckets = buckets;
  32. m_locks = locks;
  33. m_countPerLock = countPerLock;
  34. }
  35. }
  36. private volatile Tables m_tables; // Internal tables of the dictionary
  37. private readonly IEqualityComparer<TKey> m_comparer; // Key equality comparer
  38. private readonly bool m_growLockArray; // Whether to dynamically increase the size of the striped lock
  39. private int m_budget; // The maximum number of elements per lock before a resize operation is triggered
  40. // The default concurrency level is DEFAULT_CONCURRENCY_MULTIPLIER * #CPUs. The higher the
  41. // DEFAULT_CONCURRENCY_MULTIPLIER, the more concurrent writes can take place without interference
  42. // and blocking, but also the more expensive operations that require all locks become (e.g. table
  43. // resizing, ToArray, Count, etc). According to brief benchmarks that we ran, 4 seems like a good
  44. // compromise.
  45. private const int DEFAULT_CONCURRENCY_MULTIPLIER = 4;
  46. // The default capacity, i.e. the initial # of buckets. When choosing this value, we are making
  47. // a trade-off between the size of a very small dictionary, and the number of resizes when
  48. // constructing a large dictionary. Also, the capacity should not be divisible by a small prime.
  49. private const int DEFAULT_CAPACITY = 31;
  50. // The maximum size of the striped lock that will not be exceeded when locks are automatically
  51. // added as the dictionary grows. However, the user is allowed to exceed this limit by passing
  52. // a concurrency level larger than MAX_LOCK_NUMBER into the constructor.
  53. private const int MAX_LOCK_NUMBER = 1024;
  54. // Whether TValue is a type that can be written atomically (i.e., with no danger of torn reads)
  55. private static readonly bool s_isValueWriteAtomic = IsValueWriteAtomic();
  56. private static bool IsValueWriteAtomic()
  57. {
  58. Type valueType = typeof(TValue);
  59. //
  60. // Section 12.6.6 of ECMA CLI explains which types can be read and written atomically without
  61. // the risk of tearing.
  62. //
  63. // See http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf
  64. //
  65. bool isAtomic =
  66. (valueType.GetTypeInfo().IsClass)
  67. || valueType == typeof(Boolean)
  68. || valueType == typeof(Char)
  69. || valueType == typeof(Byte)
  70. || valueType == typeof(SByte)
  71. || valueType == typeof(Int16)
  72. || valueType == typeof(UInt16)
  73. || valueType == typeof(Int32)
  74. || valueType == typeof(UInt32)
  75. || valueType == typeof(Single);
  76. if (!isAtomic && IntPtr.Size == 8)
  77. {
  78. isAtomic |= valueType == typeof(Double) || valueType == typeof(Int64);
  79. }
  80. return isAtomic;
  81. }
  82. public ConcurrentDictionary(IEqualityComparer<TKey> comparer) : this(DefaultConcurrencyLevel, DEFAULT_CAPACITY, true, comparer) { }
  83. public ConcurrentDictionary(int capacity, IEqualityComparer<TKey> comparer) : this(DefaultConcurrencyLevel, capacity, true, comparer) { }
  84. internal ConcurrentDictionary(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<TKey> comparer)
  85. {
  86. if (concurrencyLevel < 1)
  87. {
  88. throw new ArgumentOutOfRangeException("concurrencyLevel");
  89. }
  90. if (capacity < 0)
  91. {
  92. throw new ArgumentOutOfRangeException("capacity");
  93. }
  94. if (comparer == null) throw new ArgumentNullException("comparer");
  95. // The capacity should be at least as large as the concurrency level. Otherwise, we would have locks that don't guard
  96. // any buckets.
  97. if (capacity < concurrencyLevel)
  98. {
  99. capacity = concurrencyLevel;
  100. }
  101. object[] locks = new object[concurrencyLevel];
  102. for (int i = 0; i < locks.Length; i++)
  103. {
  104. locks[i] = new object();
  105. }
  106. int[] countPerLock = new int[locks.Length];
  107. Node[] buckets = new Node[capacity];
  108. m_tables = new Tables(buckets, locks, countPerLock);
  109. m_comparer = comparer;
  110. m_growLockArray = growLockArray;
  111. m_budget = buckets.Length / locks.Length;
  112. }
  113. public bool TryAdd(TKey key, TValue value)
  114. {
  115. if (key == null) throw new ArgumentNullException("key");
  116. TValue dummy;
  117. return TryAddInternal(key, value, false, true, out dummy);
  118. }
  119. public bool TryRemove(TKey key, out TValue value)
  120. {
  121. if (key == null) throw new ArgumentNullException("key");
  122. return TryRemoveInternal(key, out value, false, default(TValue));
  123. }
  124. [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
  125. private bool TryRemoveInternal(TKey key, out TValue value, bool matchValue, TValue oldValue)
  126. {
  127. while (true)
  128. {
  129. Tables tables = m_tables;
  130. int bucketNo, lockNo;
  131. GetBucketAndLockNo(m_comparer.GetHashCode(key), out bucketNo, out lockNo, tables.m_buckets.Length, tables.m_locks.Length);
  132. lock (tables.m_locks[lockNo])
  133. {
  134. // If the table just got resized, we may not be holding the right lock, and must retry.
  135. // This should be a rare occurence.
  136. if (tables != m_tables)
  137. {
  138. continue;
  139. }
  140. Node prev = null;
  141. for (Node curr = tables.m_buckets[bucketNo]; curr != null; curr = curr.m_next)
  142. {
  143. if (m_comparer.Equals(curr.m_key, key))
  144. {
  145. if (matchValue)
  146. {
  147. bool valuesMatch = EqualityComparer<TValue>.Default.Equals(oldValue, curr.m_value);
  148. if (!valuesMatch)
  149. {
  150. value = default(TValue);
  151. return false;
  152. }
  153. }
  154. if (prev == null)
  155. {
  156. Volatile.Write<Node>(ref tables.m_buckets[bucketNo], curr.m_next);
  157. }
  158. else
  159. {
  160. prev.m_next = curr.m_next;
  161. }
  162. value = curr.m_value;
  163. tables.m_countPerLock[lockNo]--;
  164. return true;
  165. }
  166. prev = curr;
  167. }
  168. }
  169. value = default(TValue);
  170. return false;
  171. }
  172. }
  173. [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
  174. public bool TryGetValue(TKey key, out TValue value)
  175. {
  176. if (key == null) throw new ArgumentNullException("key");
  177. int bucketNo, lockNoUnused;
  178. // We must capture the m_buckets field in a local variable. It is set to a new table on each table resize.
  179. Tables tables = m_tables;
  180. GetBucketAndLockNo(m_comparer.GetHashCode(key), out bucketNo, out lockNoUnused, tables.m_buckets.Length, tables.m_locks.Length);
  181. // We can get away w/out a lock here.
  182. // The Volatile.Read ensures that the load of the fields of 'n' doesn't move before the load from buckets[i].
  183. Node n = Volatile.Read<Node>(ref tables.m_buckets[bucketNo]);
  184. while (n != null)
  185. {
  186. if (m_comparer.Equals(n.m_key, key))
  187. {
  188. value = n.m_value;
  189. return true;
  190. }
  191. n = n.m_next;
  192. }
  193. value = default(TValue);
  194. return false;
  195. }
  196. [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
  197. private bool TryAddInternal(TKey key, TValue value, bool updateIfExists, bool acquireLock, out TValue resultingValue)
  198. {
  199. int hashcode = m_comparer.GetHashCode(key);
  200. while (true)
  201. {
  202. int bucketNo, lockNo;
  203. Tables tables = m_tables;
  204. GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables.m_buckets.Length, tables.m_locks.Length);
  205. bool resizeDesired = false;
  206. bool lockTaken = false;
  207. try
  208. {
  209. if (acquireLock)
  210. Monitor.Enter(tables.m_locks[lockNo], ref lockTaken);
  211. // If the table just got resized, we may not be holding the right lock, and must retry.
  212. // This should be a rare occurence.
  213. if (tables != m_tables)
  214. {
  215. continue;
  216. }
  217. // Try to find this key in the bucket
  218. Node prev = null;
  219. for (Node node = tables.m_buckets[bucketNo]; node != null; node = node.m_next)
  220. {
  221. if (m_comparer.Equals(node.m_key, key))
  222. {
  223. // The key was found in the dictionary. If updates are allowed, update the value for that key.
  224. // We need to create a new node for the update, in order to support TValue types that cannot
  225. // be written atomically, since lock-free reads may be happening concurrently.
  226. if (updateIfExists)
  227. {
  228. if (s_isValueWriteAtomic)
  229. {
  230. node.m_value = value;
  231. }
  232. else
  233. {
  234. Node newNode = new Node(node.m_key, value, hashcode, node.m_next);
  235. if (prev == null)
  236. {
  237. tables.m_buckets[bucketNo] = newNode;
  238. }
  239. else
  240. {
  241. prev.m_next = newNode;
  242. }
  243. }
  244. resultingValue = value;
  245. }
  246. else
  247. {
  248. resultingValue = node.m_value;
  249. }
  250. return false;
  251. }
  252. prev = node;
  253. }
  254. // The key was not found in the bucket. Insert the key-value pair.
  255. Volatile.Write<Node>(ref tables.m_buckets[bucketNo], new Node(key, value, hashcode, tables.m_buckets[bucketNo]));
  256. checked
  257. {
  258. tables.m_countPerLock[lockNo]++;
  259. }
  260. //
  261. // If the number of elements guarded by this lock has exceeded the budget, resize the bucket table.
  262. // It is also possible that GrowTable will increase the budget but won't resize the bucket table.
  263. // That happens if the bucket table is found to be poorly utilized due to a bad hash function.
  264. //
  265. if (tables.m_countPerLock[lockNo] > m_budget)
  266. {
  267. resizeDesired = true;
  268. }
  269. }
  270. finally
  271. {
  272. if (lockTaken)
  273. Monitor.Exit(tables.m_locks[lockNo]);
  274. }
  275. //
  276. // The fact that we got here means that we just performed an insertion. If necessary, we will grow the table.
  277. //
  278. // Concurrency notes:
  279. // - Notice that we are not holding any locks at when calling GrowTable. This is necessary to prevent deadlocks.
  280. // - As a result, it is possible that GrowTable will be called unnecessarily. But, GrowTable will obtain lock 0
  281. // and then verify that the table we passed to it as the argument is still the current table.
  282. //
  283. if (resizeDesired)
  284. {
  285. GrowTable(tables);
  286. }
  287. resultingValue = value;
  288. return true;
  289. }
  290. }
  291. public ICollection<TValue> Values
  292. {
  293. get { return GetValues(); }
  294. }
  295. private void GrowTable(Tables tables)
  296. {
  297. int locksAcquired = 0;
  298. try
  299. {
  300. // The thread that first obtains m_locks[0] will be the one doing the resize operation
  301. AcquireLocks(0, 1, ref locksAcquired);
  302. // Make sure nobody resized the table while we were waiting for lock 0:
  303. if (tables != m_tables)
  304. {
  305. // We assume that since the table reference is different, it was already resized (or the budget
  306. // was adjusted). If we ever decide to do table shrinking, or replace the table for other reasons,
  307. // we will have to revisit this logic.
  308. return;
  309. }
  310. // Compute the (approx.) total size. Use an Int64 accumulation variable to avoid an overflow.
  311. long approxCount = 0;
  312. for (int i = 0; i < tables.m_countPerLock.Length; i++)
  313. {
  314. approxCount += tables.m_countPerLock[i];
  315. }
  316. //
  317. // If the bucket array is too empty, double the budget instead of resizing the table
  318. //
  319. if (approxCount < tables.m_buckets.Length / 4)
  320. {
  321. m_budget = 2 * m_budget;
  322. if (m_budget < 0)
  323. {
  324. m_budget = int.MaxValue;
  325. }
  326. return;
  327. }
  328. // Compute the new table size. We find the smallest integer larger than twice the previous table size, and not divisible by
  329. // 2,3,5 or 7. We can consider a different table-sizing policy in the future.
  330. int newLength = 0;
  331. bool maximizeTableSize = false;
  332. try
  333. {
  334. checked
  335. {
  336. // Double the size of the buckets table and add one, so that we have an odd integer.
  337. newLength = tables.m_buckets.Length * 2 + 1;
  338. // Now, we only need to check odd integers, and find the first that is not divisible
  339. // by 3, 5 or 7.
  340. while (newLength % 3 == 0 || newLength % 5 == 0 || newLength % 7 == 0)
  341. {
  342. newLength += 2;
  343. }
  344. if (newLength > MaxArrayLength)
  345. {
  346. maximizeTableSize = true;
  347. }
  348. }
  349. }
  350. catch (OverflowException)
  351. {
  352. maximizeTableSize = true;
  353. }
  354. if (maximizeTableSize)
  355. {
  356. newLength = MaxArrayLength;
  357. // We want to make sure that GrowTable will not be called again, since table is at the maximum size.
  358. // To achieve that, we set the budget to int.MaxValue.
  359. //
  360. // (There is one special case that would allow GrowTable() to be called in the future:
  361. // calling Clear() on the ConcurrentDictionary will shrink the table and lower the budget.)
  362. m_budget = int.MaxValue;
  363. }
  364. // Now acquire all other locks for the table
  365. AcquireLocks(1, tables.m_locks.Length, ref locksAcquired);
  366. object[] newLocks = tables.m_locks;
  367. // Add more locks
  368. if (m_growLockArray && tables.m_locks.Length < MAX_LOCK_NUMBER)
  369. {
  370. newLocks = new object[tables.m_locks.Length * 2];
  371. Array.Copy(tables.m_locks, newLocks, tables.m_locks.Length);
  372. for (int i = tables.m_locks.Length; i < newLocks.Length; i++)
  373. {
  374. newLocks[i] = new object();
  375. }
  376. }
  377. Node[] newBuckets = new Node[newLength];
  378. int[] newCountPerLock = new int[newLocks.Length];
  379. // Copy all data into a new table, creating new nodes for all elements
  380. for (int i = 0; i < tables.m_buckets.Length; i++)
  381. {
  382. Node current = tables.m_buckets[i];
  383. while (current != null)
  384. {
  385. Node next = current.m_next;
  386. int newBucketNo, newLockNo;
  387. GetBucketAndLockNo(current.m_hashcode, out newBucketNo, out newLockNo, newBuckets.Length, newLocks.Length);
  388. newBuckets[newBucketNo] = new Node(current.m_key, current.m_value, current.m_hashcode, newBuckets[newBucketNo]);
  389. checked
  390. {
  391. newCountPerLock[newLockNo]++;
  392. }
  393. current = next;
  394. }
  395. }
  396. // Adjust the budget
  397. m_budget = Math.Max(1, newBuckets.Length / newLocks.Length);
  398. // Replace tables with the new versions
  399. m_tables = new Tables(newBuckets, newLocks, newCountPerLock);
  400. }
  401. finally
  402. {
  403. // Release all locks that we took earlier
  404. ReleaseLocks(0, locksAcquired);
  405. }
  406. }
  407. private void GetBucketAndLockNo(
  408. int hashcode, out int bucketNo, out int lockNo, int bucketCount, int lockCount)
  409. {
  410. bucketNo = (hashcode & 0x7fffffff) % bucketCount;
  411. lockNo = bucketNo % lockCount;
  412. }
  413. private static int DefaultConcurrencyLevel
  414. {
  415. get { return DEFAULT_CONCURRENCY_MULTIPLIER * Environment.ProcessorCount; }
  416. }
  417. private void AcquireAllLocks(ref int locksAcquired)
  418. {
  419. // First, acquire lock 0
  420. AcquireLocks(0, 1, ref locksAcquired);
  421. // Now that we have lock 0, the m_locks array will not change (i.e., grow),
  422. // and so we can safely read m_locks.Length.
  423. AcquireLocks(1, m_tables.m_locks.Length, ref locksAcquired);
  424. }
  425. private void AcquireLocks(int fromInclusive, int toExclusive, ref int locksAcquired)
  426. {
  427. object[] locks = m_tables.m_locks;
  428. for (int i = fromInclusive; i < toExclusive; i++)
  429. {
  430. bool lockTaken = false;
  431. try
  432. {
  433. Monitor.Enter(locks[i], ref lockTaken);
  434. }
  435. finally
  436. {
  437. if (lockTaken)
  438. {
  439. locksAcquired++;
  440. }
  441. }
  442. }
  443. }
  444. [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
  445. private void ReleaseLocks(int fromInclusive, int toExclusive)
  446. {
  447. for (int i = fromInclusive; i < toExclusive; i++)
  448. {
  449. Monitor.Exit(m_tables.m_locks[i]);
  450. }
  451. }
  452. [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
  453. private ReadOnlyCollection<TValue> GetValues()
  454. {
  455. int locksAcquired = 0;
  456. try
  457. {
  458. AcquireAllLocks(ref locksAcquired);
  459. List<TValue> values = new List<TValue>();
  460. for (int i = 0; i < m_tables.m_buckets.Length; i++)
  461. {
  462. Node current = m_tables.m_buckets[i];
  463. while (current != null)
  464. {
  465. values.Add(current.m_value);
  466. current = current.m_next;
  467. }
  468. }
  469. return new ReadOnlyCollection<TValue>(values);
  470. }
  471. finally
  472. {
  473. ReleaseLocks(0, locksAcquired);
  474. }
  475. }
  476. private class Node
  477. {
  478. internal TKey m_key;
  479. internal TValue m_value;
  480. internal volatile Node m_next;
  481. internal int m_hashcode;
  482. internal Node(TKey key, TValue value, int hashcode, Node next)
  483. {
  484. m_key = key;
  485. m_value = value;
  486. m_next = next;
  487. m_hashcode = hashcode;
  488. }
  489. }
  490. }
  491. }
  492. #endif