1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain. Use, modify, and |
4 |
* redistribute this code in any way without acknowledgement. |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
import java.util.concurrent.locks.*; |
9 |
import java.util.*; |
10 |
import java.io.Serializable; |
11 |
import java.io.IOException; |
12 |
import java.io.ObjectInputStream; |
13 |
import java.io.ObjectOutputStream; |
14 |
|
15 |
/** |
16 |
* A hash table supporting full concurrency of retrievals and |
17 |
* adjustable expected concurrency for updates. This class obeys the |
18 |
* same functional specification as {@link java.util.Hashtable}, and |
19 |
* includes versions of methods corresponding to each method of |
20 |
* <tt>Hashtable</tt>. However, even though all operations are |
21 |
* thread-safe, retrieval operations do <em>not</em> entail locking, |
22 |
* and there is <em>not</em> any support for locking the entire table |
23 |
* in a way that prevents all access. This class is fully |
24 |
* interoperable with <tt>Hashtable</tt> in programs that rely on its |
25 |
* thread safety but not on its synchronization details. |
26 |
* |
27 |
* <p> Retrieval operations (including <tt>get</tt>) generally do not |
28 |
* block, so may overlap with update operations (including |
29 |
* <tt>put</tt> and <tt>remove</tt>). Retrievals reflect the results |
30 |
* of the most recently <em>completed</em> update operations holding |
31 |
* upon their onset. For aggregate operations such as <tt>putAll</tt> |
32 |
* and <tt>clear</tt>, concurrent retrievals may reflect insertion or |
33 |
* removal of only some entries. Similarly, Iterators and |
34 |
* Enumerations return elements reflecting the state of the hash table |
35 |
* at some point at or since the creation of the iterator/enumeration. |
36 |
* They do <em>not</em> throw |
37 |
* <tt>ConcurrentModificationException</tt>. However, Iterators are |
38 |
* designed to be used by only one thread at a time. |
39 |
* |
40 |
* <p> The allowed concurrency among update operations is guided by |
41 |
* the optional <tt>concurrencyLevel</tt> constructor argument |
42 |
* (default 16), which is used as a hint for internal sizing. The |
43 |
* table is internally partitioned to try to permit the indicated |
44 |
* number of concurrent updates without contention. Because placement |
45 |
* in hash tables is essentially random, the actual concurrency will |
46 |
* vary. Ideally, you should choose a value to accommodate as many |
47 |
* threads as will ever concurrently modify the table. Using a |
48 |
* significantly higher value than you need can waste space and time, |
49 |
* and a significantly lower value can lead to thread contention. But |
50 |
* overestimates and underestimates within an order of magnitude do |
51 |
* not usually have much noticeable impact. A value of one is |
52 |
* appropriate when it is known that only one thread will modify |
53 |
* and all others will only read. |
54 |
* |
55 |
* <p>This class implements all of the <em>optional</em> methods |
56 |
* of the {@link Map} and {@link Iterator} interfaces. |
57 |
* |
58 |
* <p> Like {@link java.util.Hashtable} but unlike {@link |
59 |
* java.util.HashMap}, this class does NOT allow <tt>null</tt> to be |
60 |
* used as a key or value. |
61 |
* |
62 |
* @since 1.5 |
63 |
* @author Doug Lea |
64 |
*/ |
65 |
public class ConcurrentHashMap<K, V> extends AbstractMap<K, V> |
66 |
implements ConcurrentMap<K, V>, Cloneable, Serializable { |
67 |
private static final long serialVersionUID = 7249069246763182397L; |
68 |
|
69 |
/* |
70 |
* The basic strategy is to subdivide the table among Segments, |
71 |
* each of which itself is a concurrently readable hash table. |
72 |
*/ |
73 |
|
74 |
/* ---------------- Constants -------------- */ |
75 |
|
76 |
/** |
77 |
* The default initial number of table slots for this table. |
78 |
* Used when not otherwise specified in constructor. |
79 |
*/ |
80 |
private static int DEFAULT_INITIAL_CAPACITY = 16; |
81 |
|
82 |
/** |
83 |
* The maximum capacity, used if a higher value is implicitly |
84 |
* specified by either of the constructors with arguments. MUST |
85 |
* be a power of two <= 1<<30 to ensure that entries are indexible |
86 |
* using ints. |
87 |
*/ |
88 |
static final int MAXIMUM_CAPACITY = 1 << 30; |
89 |
|
90 |
/** |
91 |
* The default load factor for this table. Used when not |
92 |
* otherwise specified in constructor. |
93 |
*/ |
94 |
static final float DEFAULT_LOAD_FACTOR = 0.75f; |
95 |
|
96 |
/** |
97 |
* The default number of concurrency control segments. |
98 |
**/ |
99 |
private static final int DEFAULT_SEGMENTS = 16; |
100 |
|
101 |
/** |
102 |
* The maximum number of segments to allow; used to bound ctor arguments. |
103 |
*/ |
104 |
private static final int MAX_SEGMENTS = 1 << 16; // slightly conservative |
105 |
|
106 |
/* ---------------- Fields -------------- */ |
107 |
|
108 |
/** |
109 |
* Mask value for indexing into segments. The upper bits of a |
110 |
* key's hash code are used to choose the segment. |
111 |
**/ |
112 |
private final int segmentMask; |
113 |
|
114 |
/** |
115 |
* Shift value for indexing within segments. |
116 |
**/ |
117 |
private final int segmentShift; |
118 |
|
119 |
/** |
120 |
* The segments, each of which is a specialized hash table |
121 |
*/ |
122 |
private final Segment[] segments; |
123 |
|
124 |
private transient Set<K> keySet; |
125 |
private transient Set<Map.Entry<K,V>> entrySet; |
126 |
private transient Collection<V> values; |
127 |
|
128 |
/* ---------------- Small Utilities -------------- */ |
129 |
|
130 |
/** |
131 |
* Return a hash code for non-null Object x. |
132 |
* Uses the same hash code spreader as most other j.u hash tables. |
133 |
* @param x the object serving as a key |
134 |
* @return the hash code |
135 |
*/ |
136 |
private static int hash(Object x) { |
137 |
int h = x.hashCode(); |
138 |
h += ~(h << 9); |
139 |
h ^= (h >>> 14); |
140 |
h += (h << 4); |
141 |
h ^= (h >>> 10); |
142 |
return h; |
143 |
} |
144 |
|
145 |
/** |
146 |
* Return the segment that should be used for key with given hash |
147 |
*/ |
148 |
private Segment<K,V> segmentFor(int hash) { |
149 |
return (Segment<K,V>) segments[(hash >>> segmentShift) & segmentMask]; |
150 |
} |
151 |
|
152 |
/* ---------------- Inner Classes -------------- */ |
153 |
|
154 |
/** |
155 |
* Segments are specialized versions of hash tables. This |
156 |
* subclasses from ReentrantLock opportunistically, just to |
157 |
* simplify some locking and avoid separate construction. |
158 |
**/ |
159 |
private static final class Segment<K,V> extends ReentrantLock implements Serializable { |
160 |
/* |
161 |
* Segments maintain a table of entry lists that are ALWAYS |
162 |
* kept in a consistent state, so can be read without locking. |
163 |
* Next fields of nodes are immutable (final). All list |
164 |
* additions are performed at the front of each bin. This |
165 |
* makes it easy to check changes, and also fast to traverse. |
166 |
* When nodes would otherwise be changed, new nodes are |
167 |
* created to replace them. This works well for hash tables |
168 |
* since the bin lists tend to be short. (The average length |
169 |
* is less than two for the default load factor threshold.) |
170 |
* |
171 |
* Read operations can thus proceed without locking, but rely |
172 |
* on a memory barrier to ensure that completed write |
173 |
* operations performed by other threads are |
174 |
* noticed. Conveniently, the "count" field, tracking the |
175 |
* number of elements, can also serve as the volatile variable |
176 |
* providing proper read/write barriers. This is convenient |
177 |
* because this field needs to be read in many read operations |
178 |
* anyway. |
179 |
* |
180 |
* Implementors note. The basic rules for all this are: |
181 |
* |
182 |
* - All unsynchronized read operations must first read the |
183 |
* "count" field, and should not look at table entries if |
184 |
* it is 0. |
185 |
* |
186 |
* - All synchronized write operations should write to |
187 |
* the "count" field after updating. The operations must not |
188 |
* take any action that could even momentarily cause |
189 |
* a concurrent read operation to see inconsistent |
190 |
* data. This is made easier by the nature of the read |
191 |
* operations in Map. For example, no operation |
192 |
* can reveal that the table has grown but the threshold |
193 |
* has not yet been updated, so there are no atomicity |
194 |
* requirements for this with respect to reads. |
195 |
* |
196 |
* As a guide, all critical volatile reads and writes are marked |
197 |
* in code comments. |
198 |
*/ |
199 |
|
200 |
private static final long serialVersionUID = 2249069246763182397L; |
201 |
|
202 |
/** |
203 |
* The number of elements in this segment's region. |
204 |
**/ |
205 |
transient volatile int count; |
206 |
|
207 |
/** |
208 |
* Number of updates; used for checking lack of modifications |
209 |
* in bulk-read methods. |
210 |
*/ |
211 |
transient int modCount; |
212 |
|
213 |
/** |
214 |
* The table is rehashed when its size exceeds this threshold. |
215 |
* (The value of this field is always (int)(capacity * |
216 |
* loadFactor).) |
217 |
*/ |
218 |
private transient int threshold; |
219 |
|
220 |
/** |
221 |
* The per-segment table |
222 |
*/ |
223 |
transient HashEntry[] table; |
224 |
|
225 |
/** |
226 |
* The load factor for the hash table. Even though this value |
227 |
* is same for all segments, it is replicated to avoid needing |
228 |
* links to outer object. |
229 |
* @serial |
230 |
*/ |
231 |
private final float loadFactor; |
232 |
|
233 |
Segment(int initialCapacity, float lf) { |
234 |
loadFactor = lf; |
235 |
setTable(new HashEntry[initialCapacity]); |
236 |
} |
237 |
|
238 |
/** |
239 |
* Set table to new HashEntry array. |
240 |
* Call only while holding lock or in constructor. |
241 |
**/ |
242 |
private void setTable(HashEntry[] newTable) { |
243 |
table = newTable; |
244 |
threshold = (int)(newTable.length * loadFactor); |
245 |
count = count; // write-volatile |
246 |
} |
247 |
|
248 |
/* Specialized implementations of map methods */ |
249 |
|
250 |
V get(K key, int hash) { |
251 |
if (count != 0) { // read-volatile |
252 |
HashEntry[] tab = table; |
253 |
int index = hash & (tab.length - 1); |
254 |
HashEntry<K,V> e = (HashEntry<K,V>) tab[index]; |
255 |
while (e != null) { |
256 |
if (e.hash == hash && key.equals(e.key)) |
257 |
return e.value; |
258 |
e = e.next; |
259 |
} |
260 |
} |
261 |
return null; |
262 |
} |
263 |
|
264 |
boolean containsKey(Object key, int hash) { |
265 |
if (count != 0) { // read-volatile |
266 |
HashEntry[] tab = table; |
267 |
int index = hash & (tab.length - 1); |
268 |
HashEntry<K,V> e = (HashEntry<K,V>) tab[index]; |
269 |
while (e != null) { |
270 |
if (e.hash == hash && key.equals(e.key)) |
271 |
return true; |
272 |
e = e.next; |
273 |
} |
274 |
} |
275 |
return false; |
276 |
} |
277 |
|
278 |
boolean containsValue(Object value) { |
279 |
if (count != 0) { // read-volatile |
280 |
HashEntry[] tab = table; |
281 |
int len = tab.length; |
282 |
for (int i = 0 ; i < len; i++) |
283 |
for (HashEntry<K,V> e = (HashEntry<K,V>)tab[i] ; e != null ; e = e.next) |
284 |
if (value.equals(e.value)) |
285 |
return true; |
286 |
} |
287 |
return false; |
288 |
} |
289 |
|
290 |
V put(K key, int hash, V value, boolean onlyIfAbsent) { |
291 |
lock(); |
292 |
try { |
293 |
int c = count; |
294 |
HashEntry[] tab = table; |
295 |
int index = hash & (tab.length - 1); |
296 |
HashEntry<K,V> first = (HashEntry<K,V>) tab[index]; |
297 |
|
298 |
for (HashEntry<K,V> e = first; e != null; e = (HashEntry<K,V>) e.next) { |
299 |
if (e.hash == hash && key.equals(e.key)) { |
300 |
V oldValue = e.value; |
301 |
if (!onlyIfAbsent) |
302 |
e.value = value; |
303 |
++modCount; |
304 |
count = c; // write-volatile |
305 |
return oldValue; |
306 |
} |
307 |
} |
308 |
|
309 |
tab[index] = new HashEntry<K,V>(hash, key, value, first); |
310 |
++modCount; |
311 |
++c; |
312 |
count = c; // write-volatile |
313 |
if (c > threshold) |
314 |
setTable(rehash(tab)); |
315 |
return null; |
316 |
} finally { |
317 |
unlock(); |
318 |
} |
319 |
} |
320 |
|
321 |
private HashEntry[] rehash(HashEntry[] oldTable) { |
322 |
int oldCapacity = oldTable.length; |
323 |
if (oldCapacity >= MAXIMUM_CAPACITY) |
324 |
return oldTable; |
325 |
|
326 |
/* |
327 |
* Reclassify nodes in each list to new Map. Because we are |
328 |
* using power-of-two expansion, the elements from each bin |
329 |
* must either stay at same index, or move with a power of two |
330 |
* offset. We eliminate unnecessary node creation by catching |
331 |
* cases where old nodes can be reused because their next |
332 |
* fields won't change. Statistically, at the default |
333 |
* threshhold, only about one-sixth of them need cloning when |
334 |
* a table doubles. The nodes they replace will be garbage |
335 |
* collectable as soon as they are no longer referenced by any |
336 |
* reader thread that may be in the midst of traversing table |
337 |
* right now. |
338 |
*/ |
339 |
|
340 |
HashEntry[] newTable = new HashEntry[oldCapacity << 1]; |
341 |
int sizeMask = newTable.length - 1; |
342 |
for (int i = 0; i < oldCapacity ; i++) { |
343 |
// We need to guarantee that any existing reads of old Map can |
344 |
// proceed. So we cannot yet null out each bin. |
345 |
HashEntry<K,V> e = (HashEntry<K,V>)oldTable[i]; |
346 |
|
347 |
if (e != null) { |
348 |
HashEntry<K,V> next = e.next; |
349 |
int idx = e.hash & sizeMask; |
350 |
|
351 |
// Single node on list |
352 |
if (next == null) |
353 |
newTable[idx] = e; |
354 |
|
355 |
else { |
356 |
// Reuse trailing consecutive sequence at same slot |
357 |
HashEntry<K,V> lastRun = e; |
358 |
int lastIdx = idx; |
359 |
for (HashEntry<K,V> last = next; |
360 |
last != null; |
361 |
last = last.next) { |
362 |
int k = last.hash & sizeMask; |
363 |
if (k != lastIdx) { |
364 |
lastIdx = k; |
365 |
lastRun = last; |
366 |
} |
367 |
} |
368 |
newTable[lastIdx] = lastRun; |
369 |
|
370 |
// Clone all remaining nodes |
371 |
for (HashEntry<K,V> p = e; p != lastRun; p = p.next) { |
372 |
int k = p.hash & sizeMask; |
373 |
newTable[k] = new HashEntry<K,V>(p.hash, |
374 |
p.key, |
375 |
p.value, |
376 |
(HashEntry<K,V>) newTable[k]); |
377 |
} |
378 |
} |
379 |
} |
380 |
} |
381 |
return newTable; |
382 |
} |
383 |
|
384 |
/** |
385 |
* Remove; match on key only if value null, else match both. |
386 |
*/ |
387 |
V remove(Object key, int hash, Object value) { |
388 |
lock(); |
389 |
try { |
390 |
int c = count; |
391 |
HashEntry[] tab = table; |
392 |
int index = hash & (tab.length - 1); |
393 |
HashEntry<K,V> first = (HashEntry<K,V>)tab[index]; |
394 |
|
395 |
HashEntry<K,V> e = first; |
396 |
for (;;) { |
397 |
if (e == null) |
398 |
return null; |
399 |
if (e.hash == hash && key.equals(e.key)) |
400 |
break; |
401 |
e = e.next; |
402 |
} |
403 |
|
404 |
V oldValue = e.value; |
405 |
if (value != null && !value.equals(oldValue)) |
406 |
return null; |
407 |
|
408 |
// All entries following removed node can stay in list, but |
409 |
// all preceeding ones need to be cloned. |
410 |
HashEntry<K,V> newFirst = e.next; |
411 |
for (HashEntry<K,V> p = first; p != e; p = p.next) |
412 |
newFirst = new HashEntry<K,V>(p.hash, p.key, |
413 |
p.value, newFirst); |
414 |
tab[index] = newFirst; |
415 |
++modCount; |
416 |
count = c-1; // write-volatile |
417 |
return oldValue; |
418 |
} finally { |
419 |
unlock(); |
420 |
} |
421 |
} |
422 |
|
423 |
void clear() { |
424 |
lock(); |
425 |
try { |
426 |
HashEntry[] tab = table; |
427 |
for (int i = 0; i < tab.length ; i++) |
428 |
tab[i] = null; |
429 |
++modCount; |
430 |
count = 0; // write-volatile |
431 |
} finally { |
432 |
unlock(); |
433 |
} |
434 |
} |
435 |
} |
436 |
|
437 |
/** |
438 |
* ConcurrentHashMap list entry. |
439 |
*/ |
440 |
private static class HashEntry<K,V> implements Entry<K,V> { |
441 |
private final K key; |
442 |
private V value; |
443 |
private final int hash; |
444 |
private final HashEntry<K,V> next; |
445 |
|
446 |
HashEntry(int hash, K key, V value, HashEntry<K,V> next) { |
447 |
this.value = value; |
448 |
this.hash = hash; |
449 |
this.key = key; |
450 |
this.next = next; |
451 |
} |
452 |
|
453 |
public K getKey() { |
454 |
return key; |
455 |
} |
456 |
|
457 |
public V getValue() { |
458 |
return value; |
459 |
} |
460 |
|
461 |
public V setValue(V newValue) { |
462 |
// We aren't required to, and don't provide any |
463 |
// visibility barriers for setting value. |
464 |
if (newValue == null) |
465 |
throw new NullPointerException(); |
466 |
V oldValue = this.value; |
467 |
this.value = newValue; |
468 |
return oldValue; |
469 |
} |
470 |
|
471 |
public boolean equals(Object o) { |
472 |
if (!(o instanceof Entry)) |
473 |
return false; |
474 |
Entry<K,V> e = (Entry<K,V>)o; |
475 |
return (key.equals(e.getKey()) && value.equals(e.getValue())); |
476 |
} |
477 |
|
478 |
public int hashCode() { |
479 |
return key.hashCode() ^ value.hashCode(); |
480 |
} |
481 |
|
482 |
public String toString() { |
483 |
return key + "=" + value; |
484 |
} |
485 |
} |
486 |
|
487 |
|
488 |
/* ---------------- Public operations -------------- */ |
489 |
|
490 |
/** |
491 |
* Constructs a new, empty map with the specified initial |
492 |
* capacity and the specified load factor. |
493 |
* |
494 |
* @param initialCapacity the initial capacity. The implementation |
495 |
* performs internal sizing to accommodate this many elements. |
496 |
* @param loadFactor the load factor threshold, used to control resizing. |
497 |
* @param concurrencyLevel the estimated number of concurrently |
498 |
* updating threads. The implementation performs internal sizing |
499 |
* to try to accommodate this many threads. |
500 |
* @throws IllegalArgumentException if the initial capacity is |
501 |
* negative or the load factor or concurrencyLevel are |
502 |
* nonpositive. |
503 |
*/ |
504 |
public ConcurrentHashMap(int initialCapacity, |
505 |
float loadFactor, int concurrencyLevel) { |
506 |
if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0) |
507 |
throw new IllegalArgumentException(); |
508 |
|
509 |
if (concurrencyLevel > MAX_SEGMENTS) |
510 |
concurrencyLevel = MAX_SEGMENTS; |
511 |
|
512 |
// Find power-of-two sizes best matching arguments |
513 |
int sshift = 0; |
514 |
int ssize = 1; |
515 |
while (ssize < concurrencyLevel) { |
516 |
++sshift; |
517 |
ssize <<= 1; |
518 |
} |
519 |
segmentShift = 32 - sshift; |
520 |
segmentMask = ssize - 1; |
521 |
this.segments = new Segment[ssize]; |
522 |
|
523 |
if (initialCapacity > MAXIMUM_CAPACITY) |
524 |
initialCapacity = MAXIMUM_CAPACITY; |
525 |
int c = initialCapacity / ssize; |
526 |
if (c * ssize < initialCapacity) |
527 |
++c; |
528 |
int cap = 1; |
529 |
while (cap < c) |
530 |
cap <<= 1; |
531 |
|
532 |
for (int i = 0; i < this.segments.length; ++i) |
533 |
this.segments[i] = new Segment<K,V>(cap, loadFactor); |
534 |
} |
535 |
|
536 |
/** |
537 |
* Constructs a new, empty map with the specified initial |
538 |
* capacity, and with default load factor and concurrencyLevel. |
539 |
* |
540 |
* @param initialCapacity The implementation performs internal |
541 |
* sizing to accommodate this many elements. |
542 |
* @throws IllegalArgumentException if the initial capacity of |
543 |
* elements is negative. |
544 |
*/ |
545 |
public ConcurrentHashMap(int initialCapacity) { |
546 |
this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS); |
547 |
} |
548 |
|
549 |
/** |
550 |
* Constructs a new, empty map with a default initial capacity, |
551 |
* load factor, and concurrencyLevel. |
552 |
*/ |
553 |
public ConcurrentHashMap() { |
554 |
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS); |
555 |
} |
556 |
|
557 |
/** |
558 |
* Constructs a new map with the same mappings as the given map. The |
559 |
* map is created with a capacity of twice the number of mappings in |
560 |
* the given map or 11 (whichever is greater), and a default load factor. |
561 |
*/ |
562 |
public <A extends K, B extends V> ConcurrentHashMap(Map<A,B> t) { |
563 |
this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1, |
564 |
11), |
565 |
DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS); |
566 |
putAll(t); |
567 |
} |
568 |
|
569 |
// inherit Map javadoc |
570 |
public boolean isEmpty() { |
571 |
/* |
572 |
* We need to keep track of per-segment modCounts to avoid ABA |
573 |
* problems in which an element in one segment was added and |
574 |
* in another removed during traversal, in which case the |
575 |
* table was never actually empty at any point. Note the |
576 |
* similar use of modCounts in the size() and containsValue() |
577 |
* methods, which are the only other methods also susceptible |
578 |
* to ABA problems. |
579 |
*/ |
580 |
int[] mc = new int[segments.length]; |
581 |
int mcsum = 0; |
582 |
for (int i = 0; i < segments.length; ++i) { |
583 |
if (segments[i].count != 0) |
584 |
return false; |
585 |
else |
586 |
mcsum += mc[i] = segments[i].modCount; |
587 |
} |
588 |
// If mcsum happens to be zero, then we know we got a snapshot |
589 |
// before any modifications at all were made. This is |
590 |
// probably common enough to bother tracking. |
591 |
if (mcsum != 0) { |
592 |
for (int i = 0; i < segments.length; ++i) { |
593 |
if (segments[i].count != 0 || |
594 |
mc[i] != segments[i].modCount) |
595 |
return false; |
596 |
} |
597 |
} |
598 |
return true; |
599 |
} |
600 |
|
601 |
// inherit Map javadoc |
602 |
public int size() { |
603 |
int[] mc = new int[segments.length]; |
604 |
for (;;) { |
605 |
long sum = 0; |
606 |
int mcsum = 0; |
607 |
for (int i = 0; i < segments.length; ++i) { |
608 |
sum += segments[i].count; |
609 |
mcsum += mc[i] = segments[i].modCount; |
610 |
} |
611 |
int check = 0; |
612 |
if (mcsum != 0) { |
613 |
for (int i = 0; i < segments.length; ++i) { |
614 |
check += segments[i].count; |
615 |
if (mc[i] != segments[i].modCount) { |
616 |
check = -1; // force retry |
617 |
break; |
618 |
} |
619 |
} |
620 |
} |
621 |
if (check == sum) { |
622 |
if (sum > Integer.MAX_VALUE) |
623 |
return Integer.MAX_VALUE; |
624 |
else |
625 |
return (int)sum; |
626 |
} |
627 |
} |
628 |
} |
629 |
|
630 |
|
631 |
/** |
632 |
* Returns the value to which the specified key is mapped in this table. |
633 |
* |
634 |
* @param key a key in the table. |
635 |
* @return the value to which the key is mapped in this table; |
636 |
* <tt>null</tt> if the key is not mapped to any value in |
637 |
* this table. |
638 |
* @throws NullPointerException if the key is |
639 |
* <tt>null</tt>. |
640 |
*/ |
641 |
public V get(Object key) { |
642 |
int hash = hash(key); // throws NullPointerException if key null |
643 |
return segmentFor(hash).get((K) key, hash); |
644 |
} |
645 |
|
646 |
/** |
647 |
* Tests if the specified object is a key in this table. |
648 |
* |
649 |
* @param key possible key. |
650 |
* @return <tt>true</tt> if and only if the specified object |
651 |
* is a key in this table, as determined by the |
652 |
* <tt>equals</tt> method; <tt>false</tt> otherwise. |
653 |
* @throws NullPointerException if the key is |
654 |
* <tt>null</tt>. |
655 |
*/ |
656 |
public boolean containsKey(Object key) { |
657 |
int hash = hash(key); // throws NullPointerException if key null |
658 |
return segmentFor(hash).containsKey(key, hash); |
659 |
} |
660 |
|
661 |
/** |
662 |
* Returns <tt>true</tt> if this map maps one or more keys to the |
663 |
* specified value. Note: This method requires a full internal |
664 |
* traversal of the hash table, and so is much slower than |
665 |
* method <tt>containsKey</tt>. |
666 |
* |
667 |
* @param value value whose presence in this map is to be tested. |
668 |
* @return <tt>true</tt> if this map maps one or more keys to the |
669 |
* specified value. |
670 |
* @throws NullPointerException if the value is <tt>null</tt>. |
671 |
*/ |
672 |
public boolean containsValue(Object value) { |
673 |
if (value == null) |
674 |
throw new NullPointerException(); |
675 |
|
676 |
int[] mc = new int[segments.length]; |
677 |
for (;;) { |
678 |
int sum = 0; |
679 |
int mcsum = 0; |
680 |
for (int i = 0; i < segments.length; ++i) { |
681 |
int c = segments[i].count; |
682 |
mcsum += mc[i] = segments[i].modCount; |
683 |
if (segments[i].containsValue(value)) |
684 |
return true; |
685 |
} |
686 |
boolean cleanSweep = true; |
687 |
if (mcsum != 0) { |
688 |
for (int i = 0; i < segments.length; ++i) { |
689 |
int c = segments[i].count; |
690 |
if (mc[i] != segments[i].modCount) { |
691 |
cleanSweep = false; |
692 |
break; |
693 |
} |
694 |
} |
695 |
} |
696 |
if (cleanSweep) |
697 |
return false; |
698 |
} |
699 |
} |
700 |
|
701 |
/** |
702 |
* Legacy method testing if some key maps into the specified value |
703 |
* in this table. This method is identical in functionality to |
704 |
* {@link #containsValue}, and exists solely to ensure |
705 |
* full compatibility with class {@link java.util.Hashtable}, |
706 |
* which supported this method prior to introduction of the |
707 |
* Java Collections framework. |
708 |
|
709 |
* @param value a value to search for. |
710 |
* @return <tt>true</tt> if and only if some key maps to the |
711 |
* <tt>value</tt> argument in this table as |
712 |
* determined by the <tt>equals</tt> method; |
713 |
* <tt>false</tt> otherwise. |
714 |
* @throws NullPointerException if the value is <tt>null</tt>. |
715 |
*/ |
716 |
public boolean contains(Object value) { |
717 |
return containsValue(value); |
718 |
} |
719 |
|
720 |
/** |
721 |
* Maps the specified <tt>key</tt> to the specified |
722 |
* <tt>value</tt> in this table. Neither the key nor the |
723 |
* value can be <tt>null</tt>. <p> |
724 |
* |
725 |
* The value can be retrieved by calling the <tt>get</tt> method |
726 |
* with a key that is equal to the original key. |
727 |
* |
728 |
* @param key the table key. |
729 |
* @param value the value. |
730 |
* @return the previous value of the specified key in this table, |
731 |
* or <tt>null</tt> if it did not have one. |
732 |
* @throws NullPointerException if the key or value is |
733 |
* <tt>null</tt>. |
734 |
*/ |
735 |
public V put(K key, V value) { |
736 |
if (value == null) |
737 |
throw new NullPointerException(); |
738 |
int hash = hash(key); |
739 |
return segmentFor(hash).put(key, hash, value, false); |
740 |
} |
741 |
|
742 |
/** |
743 |
* If the specified key is not already associated |
744 |
* with a value, associate it with the given value. |
745 |
* This is equivalent to |
746 |
* <pre> |
747 |
* if (!map.containsKey(key)) |
748 |
* return map.put(key, value); |
749 |
* else |
750 |
* return map.get(key); |
751 |
* </pre> |
752 |
* Except that the action is performed atomically. |
753 |
* @param key key with which the specified value is to be associated. |
754 |
* @param value value to be associated with the specified key. |
755 |
* @return previous value associated with specified key, or <tt>null</tt> |
756 |
* if there was no mapping for key. A <tt>null</tt> return can |
757 |
* also indicate that the map previously associated <tt>null</tt> |
758 |
* with the specified key, if the implementation supports |
759 |
* <tt>null</tt> values. |
760 |
* |
761 |
* @throws UnsupportedOperationException if the <tt>put</tt> operation is |
762 |
* not supported by this map. |
763 |
* @throws ClassCastException if the class of the specified key or value |
764 |
* prevents it from being stored in this map. |
765 |
* @throws NullPointerException if the specified key or value is |
766 |
* <tt>null</tt>. |
767 |
* |
768 |
**/ |
769 |
public V putIfAbsent(K key, V value) { |
770 |
if (value == null) |
771 |
throw new NullPointerException(); |
772 |
int hash = hash(key); |
773 |
return segmentFor(hash).put(key, hash, value, true); |
774 |
} |
775 |
|
776 |
|
777 |
/** |
778 |
* Copies all of the mappings from the specified map to this one. |
779 |
* |
780 |
* These mappings replace any mappings that this map had for any of the |
781 |
* keys currently in the specified Map. |
782 |
* |
783 |
* @param t Mappings to be stored in this map. |
784 |
*/ |
785 |
public void putAll(Map<? extends K, ? extends V> t) { |
786 |
for (Iterator<Map.Entry<? extends K, ? extends V>> it = (Iterator<Map.Entry<? extends K, ? extends V>>) t.entrySet().iterator(); it.hasNext(); ) { |
787 |
Entry<? extends K, ? extends V> e = it.next(); |
788 |
put(e.getKey(), e.getValue()); |
789 |
} |
790 |
} |
791 |
|
792 |
/** |
793 |
* Removes the key (and its corresponding value) from this |
794 |
* table. This method does nothing if the key is not in the table. |
795 |
* |
796 |
* @param key the key that needs to be removed. |
797 |
* @return the value to which the key had been mapped in this table, |
798 |
* or <tt>null</tt> if the key did not have a mapping. |
799 |
* @throws NullPointerException if the key is |
800 |
* <tt>null</tt>. |
801 |
*/ |
802 |
public V remove(Object key) { |
803 |
int hash = hash(key); |
804 |
return segmentFor(hash).remove(key, hash, null); |
805 |
} |
806 |
|
807 |
/** |
808 |
* Remove entry for key only if currently mapped to given value. |
809 |
* Acts as |
810 |
* <pre> |
811 |
* if (map.get(key).equals(value)) { |
812 |
* map.remove(key); |
813 |
* return true; |
814 |
* } else return false; |
815 |
* </pre> |
816 |
* except that the action is performed atomically. |
817 |
* @param key key with which the specified value is associated. |
818 |
* @param value value associated with the specified key. |
819 |
* @return true if the value was removed |
820 |
* @throws NullPointerException if the specified key is |
821 |
* <tt>null</tt>. |
822 |
*/ |
823 |
public boolean remove(Object key, Object value) { |
824 |
int hash = hash(key); |
825 |
return segmentFor(hash).remove(key, hash, value) != null; |
826 |
} |
827 |
|
828 |
/** |
829 |
* Removes all mappings from this map. |
830 |
*/ |
831 |
public void clear() { |
832 |
for (int i = 0; i < segments.length; ++i) |
833 |
segments[i].clear(); |
834 |
} |
835 |
|
836 |
|
837 |
/** |
838 |
* Returns a shallow copy of this |
839 |
* <tt>ConcurrentHashMap</tt> instance: the keys and |
840 |
* values themselves are not cloned. |
841 |
* |
842 |
* @return a shallow copy of this map. |
843 |
*/ |
844 |
public Object clone() { |
845 |
// We cannot call super.clone, since it would share final |
846 |
// segments array, and there's no way to reassign finals. |
847 |
|
848 |
float lf = segments[0].loadFactor; |
849 |
int segs = segments.length; |
850 |
int cap = (int)(size() / lf); |
851 |
if (cap < segs) cap = segs; |
852 |
ConcurrentHashMap<K,V> t = new ConcurrentHashMap<K,V>(cap, lf, segs); |
853 |
t.putAll(this); |
854 |
return t; |
855 |
} |
856 |
|
857 |
/** |
858 |
* Returns a set view of the keys contained in this map. The set is |
859 |
* backed by the map, so changes to the map are reflected in the set, and |
860 |
* vice-versa. The set supports element removal, which removes the |
861 |
* corresponding mapping from this map, via the <tt>Iterator.remove</tt>, |
862 |
* <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and |
863 |
* <tt>clear</tt> operations. It does not support the <tt>add</tt> or |
864 |
* <tt>addAll</tt> operations. |
865 |
* The returned <tt>iterator</tt> is a "weakly consistent" iterator that |
866 |
* will never throw {@link java.util.ConcurrentModificationException}, |
867 |
* and guarantees to traverse elements as they existed upon |
868 |
* construction of the iterator, and may (but is not guaranteed to) |
869 |
* reflect any modifications subsequent to construction. |
870 |
* |
871 |
* @return a set view of the keys contained in this map. |
872 |
*/ |
873 |
public Set<K> keySet() { |
874 |
Set<K> ks = keySet; |
875 |
return (ks != null) ? ks : (keySet = new KeySet()); |
876 |
} |
877 |
|
878 |
|
879 |
/** |
880 |
* Returns a collection view of the values contained in this map. The |
881 |
* collection is backed by the map, so changes to the map are reflected in |
882 |
* the collection, and vice-versa. The collection supports element |
883 |
* removal, which removes the corresponding mapping from this map, via the |
884 |
* <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>, |
885 |
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations. |
886 |
* It does not support the <tt>add</tt> or <tt>addAll</tt> operations. |
887 |
* The returned <tt>iterator</tt> is a "weakly consistent" iterator that |
888 |
* will never throw {@link java.util.ConcurrentModificationException}, |
889 |
* and guarantees to traverse elements as they existed upon |
890 |
* construction of the iterator, and may (but is not guaranteed to) |
891 |
* reflect any modifications subsequent to construction. |
892 |
* |
893 |
* @return a collection view of the values contained in this map. |
894 |
*/ |
895 |
public Collection<V> values() { |
896 |
Collection<V> vs = values; |
897 |
return (vs != null) ? vs : (values = new Values()); |
898 |
} |
899 |
|
900 |
|
901 |
/** |
902 |
* Returns a collection view of the mappings contained in this map. Each |
903 |
* element in the returned collection is a <tt>Map.Entry</tt>. The |
904 |
* collection is backed by the map, so changes to the map are reflected in |
905 |
* the collection, and vice-versa. The collection supports element |
906 |
* removal, which removes the corresponding mapping from the map, via the |
907 |
* <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>, |
908 |
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations. |
909 |
* It does not support the <tt>add</tt> or <tt>addAll</tt> operations. |
910 |
* The returned <tt>iterator</tt> is a "weakly consistent" iterator that |
911 |
* will never throw {@link java.util.ConcurrentModificationException}, |
912 |
* and guarantees to traverse elements as they existed upon |
913 |
* construction of the iterator, and may (but is not guaranteed to) |
914 |
* reflect any modifications subsequent to construction. |
915 |
* |
916 |
* @return a collection view of the mappings contained in this map. |
917 |
*/ |
918 |
public Set<Map.Entry<K,V>> entrySet() { |
919 |
Set<Map.Entry<K,V>> es = entrySet; |
920 |
return (es != null) ? es : (entrySet = (Set<Map.Entry<K,V>>) (Set) new EntrySet()); |
921 |
} |
922 |
|
923 |
|
924 |
/** |
925 |
* Returns an enumeration of the keys in this table. |
926 |
* |
927 |
* @return an enumeration of the keys in this table. |
928 |
* @see #keySet |
929 |
*/ |
930 |
public Enumeration<K> keys() { |
931 |
return new KeyIterator(); |
932 |
} |
933 |
|
934 |
/** |
935 |
* Returns an enumeration of the values in this table. |
936 |
* Use the Enumeration methods on the returned object to fetch the elements |
937 |
* sequentially. |
938 |
* |
939 |
* @return an enumeration of the values in this table. |
940 |
* @see #values |
941 |
*/ |
942 |
public Enumeration<V> elements() { |
943 |
return new ValueIterator(); |
944 |
} |
945 |
|
946 |
/* ---------------- Iterator Support -------------- */ |
947 |
|
948 |
private abstract class HashIterator { |
949 |
private int nextSegmentIndex; |
950 |
private int nextTableIndex; |
951 |
private HashEntry[] currentTable; |
952 |
private HashEntry<K, V> nextEntry; |
953 |
private HashEntry<K, V> lastReturned; |
954 |
|
955 |
private HashIterator() { |
956 |
nextSegmentIndex = segments.length - 1; |
957 |
nextTableIndex = -1; |
958 |
advance(); |
959 |
} |
960 |
|
961 |
public boolean hasMoreElements() { return hasNext(); } |
962 |
|
963 |
private void advance() { |
964 |
if (nextEntry != null && (nextEntry = nextEntry.next) != null) |
965 |
return; |
966 |
|
967 |
while (nextTableIndex >= 0) { |
968 |
if ( (nextEntry = (HashEntry<K,V>)currentTable[nextTableIndex--]) != null) |
969 |
return; |
970 |
} |
971 |
|
972 |
while (nextSegmentIndex >= 0) { |
973 |
Segment<K,V> seg = (Segment<K,V>)segments[nextSegmentIndex--]; |
974 |
if (seg.count != 0) { |
975 |
currentTable = seg.table; |
976 |
for (int j = currentTable.length - 1; j >= 0; --j) { |
977 |
if ( (nextEntry = (HashEntry<K,V>)currentTable[j]) != null) { |
978 |
nextTableIndex = j - 1; |
979 |
return; |
980 |
} |
981 |
} |
982 |
} |
983 |
} |
984 |
} |
985 |
|
986 |
public boolean hasNext() { return nextEntry != null; } |
987 |
|
988 |
HashEntry<K,V> nextEntry() { |
989 |
if (nextEntry == null) |
990 |
throw new NoSuchElementException(); |
991 |
lastReturned = nextEntry; |
992 |
advance(); |
993 |
return lastReturned; |
994 |
} |
995 |
|
996 |
public void remove() { |
997 |
if (lastReturned == null) |
998 |
throw new IllegalStateException(); |
999 |
ConcurrentHashMap.this.remove(lastReturned.key); |
1000 |
lastReturned = null; |
1001 |
} |
1002 |
} |
1003 |
|
1004 |
private class KeyIterator extends HashIterator implements Iterator<K>, Enumeration<K> { |
1005 |
public K next() { return super.nextEntry().key; } |
1006 |
public K nextElement() { return super.nextEntry().key; } |
1007 |
} |
1008 |
|
1009 |
private class ValueIterator extends HashIterator implements Iterator<V>, Enumeration<V> { |
1010 |
public V next() { return super.nextEntry().value; } |
1011 |
public V nextElement() { return super.nextEntry().value; } |
1012 |
} |
1013 |
|
1014 |
private class EntryIterator extends HashIterator implements Iterator<Entry<K,V>> { |
1015 |
public Map.Entry<K,V> next() { return super.nextEntry(); } |
1016 |
} |
1017 |
|
1018 |
private class KeySet extends AbstractSet<K> { |
1019 |
public Iterator<K> iterator() { |
1020 |
return new KeyIterator(); |
1021 |
} |
1022 |
public int size() { |
1023 |
return ConcurrentHashMap.this.size(); |
1024 |
} |
1025 |
public boolean contains(Object o) { |
1026 |
return ConcurrentHashMap.this.containsKey(o); |
1027 |
} |
1028 |
public boolean remove(Object o) { |
1029 |
return ConcurrentHashMap.this.remove(o) != null; |
1030 |
} |
1031 |
public void clear() { |
1032 |
ConcurrentHashMap.this.clear(); |
1033 |
} |
1034 |
} |
1035 |
|
1036 |
private class Values extends AbstractCollection<V> { |
1037 |
public Iterator<V> iterator() { |
1038 |
return new ValueIterator(); |
1039 |
} |
1040 |
public int size() { |
1041 |
return ConcurrentHashMap.this.size(); |
1042 |
} |
1043 |
public boolean contains(Object o) { |
1044 |
return ConcurrentHashMap.this.containsValue(o); |
1045 |
} |
1046 |
public void clear() { |
1047 |
ConcurrentHashMap.this.clear(); |
1048 |
} |
1049 |
} |
1050 |
|
1051 |
private class EntrySet extends AbstractSet<Map.Entry<K,V>> { |
1052 |
public Iterator<Map.Entry<K,V>> iterator() { |
1053 |
return new EntryIterator(); |
1054 |
} |
1055 |
public boolean contains(Object o) { |
1056 |
if (!(o instanceof Map.Entry)) |
1057 |
return false; |
1058 |
Map.Entry<K,V> e = (Map.Entry<K,V>)o; |
1059 |
V v = ConcurrentHashMap.this.get(e.getKey()); |
1060 |
return v != null && v.equals(e.getValue()); |
1061 |
} |
1062 |
public boolean remove(Object o) { |
1063 |
if (!(o instanceof Map.Entry)) |
1064 |
return false; |
1065 |
Map.Entry<K,V> e = (Map.Entry<K,V>)o; |
1066 |
return ConcurrentHashMap.this.remove(e.getKey(), e.getValue()); |
1067 |
} |
1068 |
public int size() { |
1069 |
return ConcurrentHashMap.this.size(); |
1070 |
} |
1071 |
public void clear() { |
1072 |
ConcurrentHashMap.this.clear(); |
1073 |
} |
1074 |
} |
1075 |
|
1076 |
/* ---------------- Serialization Support -------------- */ |
1077 |
|
1078 |
/** |
1079 |
* Save the state of the <tt>ConcurrentHashMap</tt> |
1080 |
* instance to a stream (i.e., |
1081 |
* serialize it). |
1082 |
* @param s the stream |
1083 |
* @serialData |
1084 |
* the key (Object) and value (Object) |
1085 |
* for each key-value mapping, followed by a null pair. |
1086 |
* The key-value mappings are emitted in no particular order. |
1087 |
*/ |
1088 |
private void writeObject(java.io.ObjectOutputStream s) throws IOException { |
1089 |
s.defaultWriteObject(); |
1090 |
|
1091 |
for (int k = 0; k < segments.length; ++k) { |
1092 |
Segment<K,V> seg = (Segment<K,V>)segments[k]; |
1093 |
seg.lock(); |
1094 |
try { |
1095 |
HashEntry[] tab = seg.table; |
1096 |
for (int i = 0; i < tab.length; ++i) { |
1097 |
for (HashEntry<K,V> e = (HashEntry<K,V>)tab[i]; e != null; e = e.next) { |
1098 |
s.writeObject(e.key); |
1099 |
s.writeObject(e.value); |
1100 |
} |
1101 |
} |
1102 |
} finally { |
1103 |
seg.unlock(); |
1104 |
} |
1105 |
} |
1106 |
s.writeObject(null); |
1107 |
s.writeObject(null); |
1108 |
} |
1109 |
|
1110 |
/** |
1111 |
* Reconstitute the <tt>ConcurrentHashMap</tt> |
1112 |
* instance from a stream (i.e., |
1113 |
* deserialize it). |
1114 |
* @param s the stream |
1115 |
*/ |
1116 |
private void readObject(java.io.ObjectInputStream s) |
1117 |
throws IOException, ClassNotFoundException { |
1118 |
s.defaultReadObject(); |
1119 |
|
1120 |
// Initialize each segment to be minimally sized, and let grow. |
1121 |
for (int i = 0; i < segments.length; ++i) { |
1122 |
segments[i].setTable(new HashEntry[1]); |
1123 |
} |
1124 |
|
1125 |
// Read the keys and values, and put the mappings in the table |
1126 |
for (;;) { |
1127 |
K key = (K) s.readObject(); |
1128 |
V value = (V) s.readObject(); |
1129 |
if (key == null) |
1130 |
break; |
1131 |
put(key, value); |
1132 |
} |
1133 |
} |
1134 |
} |
1135 |
|