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