Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Core/Reactive/Internal/ConcurrentDictionary.cs

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