ConcurrentDictionary.cs 23 KB

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