ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ConcurrentHashMapV8.java
Revision: 1.9
Committed: Tue Aug 30 14:55:58 2011 UTC (12 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.8: +3 -4 lines
Log Message:
minor style touchups

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/publicdomain/zero/1.0/
5     */
6    
7     package jsr166e;
8     import jsr166e.LongAdder;
9     import java.util.Map;
10     import java.util.Set;
11     import java.util.Collection;
12     import java.util.AbstractMap;
13     import java.util.AbstractSet;
14     import java.util.AbstractCollection;
15     import java.util.Hashtable;
16     import java.util.HashMap;
17     import java.util.Iterator;
18     import java.util.Enumeration;
19     import java.util.ConcurrentModificationException;
20     import java.util.NoSuchElementException;
21     import java.util.concurrent.ConcurrentMap;
22     import java.io.Serializable;
23    
24     /**
25     * A hash table supporting full concurrency of retrievals and
26     * high expected concurrency for updates. This class obeys the
27     * same functional specification as {@link java.util.Hashtable}, and
28     * includes versions of methods corresponding to each method of
29     * {@code Hashtable}. However, even though all operations are
30     * thread-safe, retrieval operations do <em>not</em> entail locking,
31     * and there is <em>not</em> any support for locking the entire table
32     * in a way that prevents all access. This class is fully
33     * interoperable with {@code Hashtable} in programs that rely on its
34     * thread safety but not on its synchronization details.
35     *
36     * <p> Retrieval operations (including {@code get}) generally do not
37     * block, so may overlap with update operations (including {@code put}
38     * and {@code remove}). Retrievals reflect the results of the most
39     * recently <em>completed</em> update operations holding upon their
40     * onset. For aggregate operations such as {@code putAll} and {@code
41     * clear}, concurrent retrievals may reflect insertion or removal of
42     * only some entries. Similarly, Iterators and Enumerations return
43     * elements reflecting the state of the hash table at some point at or
44     * since the creation of the iterator/enumeration. They do
45     * <em>not</em> throw {@link ConcurrentModificationException}.
46     * However, iterators are designed to be used by only one thread at a
47     * time. Bear in mind that the results of aggregate status methods
48     * including {@code size}, {@code isEmpty}, and {@code containsValue}
49     * are typically useful only when a map is not undergoing concurrent
50     * updates in other threads. Otherwise the results of these methods
51     * reflect transient states that may be adequate for monitoring
52     * purposes, but not for program control.
53     *
54     * <p> Resizing this or any other kind of hash table is a relatively
55     * slow operation, so, when possible, it is a good idea to provide
56     * estimates of expected table sizes in constructors. Also, for
57 jsr166 1.7 * compatibility with previous versions of this class, constructors
58 dl 1.1 * may optionally specify an expected {@code concurrencyLevel} as an
59     * additional hint for internal sizing.
60     *
61     * <p>This class and its views and iterators implement all of the
62     * <em>optional</em> methods of the {@link Map} and {@link Iterator}
63     * interfaces.
64     *
65     * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
66     * does <em>not</em> allow {@code null} to be used as a key or value.
67     *
68     * <p>This class is a member of the
69     * <a href="{@docRoot}/../technotes/guides/collections/index.html">
70     * Java Collections Framework</a>.
71     *
72     * <p><em>jsr166e note: This class is a candidate replacement for
73     * java.util.concurrent.ConcurrentHashMap.<em>
74     *
75     * @since 1.5
76     * @author Doug Lea
77     * @param <K> the type of keys maintained by this map
78     * @param <V> the type of mapped values
79     */
80     public class ConcurrentHashMapV8<K, V>
81     implements ConcurrentMap<K, V>, Serializable {
82     private static final long serialVersionUID = 7249069246763182397L;
83    
84     /**
85     * A function computing a mapping from the given key to a value,
86 jsr166 1.8 * or {@code null} if there is no mapping. This is a place-holder
87     * for an upcoming JDK8 interface.
88 dl 1.1 */
89     public static interface MappingFunction<K, V> {
90     /**
91     * Returns a value for the given key, or null if there is no
92     * mapping. If this function throws an (unchecked) exception,
93     * the exception is rethrown to its caller, and no mapping is
94     * recorded. Because this function is invoked within
95     * atomicity control, the computation should be short and
96     * simple. The most common usage is to construct a new object
97     * serving as an initial mapped value.
98     *
99     * @param key the (non-null) key
100     * @return a value, or null if none
101     */
102     V map(K key);
103     }
104    
105     /*
106     * Overview:
107     *
108     * The primary design goal of this hash table is to maintain
109     * concurrent readability (typically method get(), but also
110     * iterators and related methods) while minimizing update
111     * contention.
112     *
113     * Each key-value mapping is held in a Node. Because Node fields
114     * can contain special values, they are defined using plain Object
115     * types. Similarly in turn, all internal methods that use them
116     * work off Object types. All public generic-typed methods relay
117     * in/out of these internal methods, supplying casts as needed.
118     *
119     * The table is lazily initialized to a power-of-two size upon the
120     * first insertion. Each bin in the table contains a (typically
121     * short) list of Nodes. Table accesses require volatile/atomic
122     * reads, writes, and CASes. Because there is no other way to
123     * arrange this without adding further indirections, we use
124     * intrinsics (sun.misc.Unsafe) operations. The lists of nodes
125     * within bins are always accurately traversable under volatile
126     * reads, so long as lookups check hash code and non-nullness of
127     * key and value before checking key equality. (All valid hash
128 dl 1.2 * codes are nonnegative. Negative values are reserved for special
129     * forwarding nodes; see below.)
130 dl 1.1 *
131     * A bin may be locked during update (insert, delete, and replace)
132     * operations. We do not want to waste the space required to
133     * associate a distinct lock object with each bin, so instead use
134     * the first node of a bin list itself as a lock, using builtin
135     * "synchronized" locks. These save space and we can live with
136     * only plain block-structured lock/unlock operations. Using the
137     * first node of a list as a lock does not by itself suffice
138     * though: When a node is locked, any update must first validate
139     * that it is still the first node, and retry if not. (Because new
140     * nodes are always appended to lists, once a node is first in a
141     * bin, it remains first until deleted or the bin becomes
142     * invalidated.) However, update operations can and usually do
143     * still traverse the bin until the point of update, which helps
144     * reduce cache misses on retries. This is a converse of sorts to
145     * the lazy locking technique described by Herlihy & Shavit. If
146     * there is no existing node during a put operation, then one can
147     * be CAS'ed in (without need for lock except in computeIfAbsent);
148     * the CAS serves as validation. This is on average the most
149 dl 1.5 * common case for put operations -- under random hash codes, the
150     * distribution of nodes in bins follows a Poisson distribution
151     * (see http://en.wikipedia.org/wiki/Poisson_distribution) with a
152     * parameter of 0.5 on average under the default loadFactor of
153     * 0.75. The expected number of locks covering different elements
154     * (i.e., bins with 2 or more nodes) is approximately 10% at
155     * steady state under default settings. Lock contention
156     * probability for two threads accessing arbitrary distinct
157     * elements is, roughly, 1 / (8 * #elements).
158 dl 1.1 *
159     * The table is resized when occupancy exceeds a threshold. Only
160     * a single thread performs the resize (using field "resizing", to
161     * arrange exclusion), but the table otherwise remains usable for
162     * both reads and updates. Resizing proceeds by transferring bins,
163     * one by one, from the table to the next table. Upon transfer,
164     * the old table bin contains only a special forwarding node (with
165     * negative hash code ("MOVED")) that contains the next table as
166     * its key. On encountering a forwarding node, access and update
167     * operations restart, using the new table. To ensure concurrent
168     * readability of traversals, transfers must proceed from the last
169     * bin (table.length - 1) up towards the first. Any traversal
170     * starting from the first bin can then arrange to move to the new
171     * table for the rest of the traversal without revisiting nodes.
172     * This constrains bin transfers to a particular order, and so can
173     * block indefinitely waiting for the next lock, and other threads
174     * cannot help with the transfer. However, expected stalls are
175     * infrequent enough to not warrant the additional overhead and
176     * complexity of access and iteration schemes that could admit
177     * out-of-order or concurrent bin transfers.
178     *
179 dl 1.2 * A similar traversal scheme (not yet implemented) can apply to
180     * partial traversals during partitioned aggregate operations.
181     * Also, read-only operations give up if ever forwarded to a null
182     * table, which provides support for shutdown-style clearing,
183     * which is also not currently implemented.
184 dl 1.1 *
185     * The element count is maintained using a LongAdder, which avoids
186     * contention on updates but can encounter cache thrashing if read
187     * too frequently during concurrent updates. To avoid reading so
188 dl 1.2 * often, resizing is normally attempted only upon adding to a bin
189     * already holding two or more nodes. Under the default threshold
190     * (0.75), and uniform hash distributions, the probability of this
191 dl 1.1 * occurring at threshold is around 13%, meaning that only about 1
192     * in 8 puts check threshold (and after resizing, many fewer do
193 dl 1.2 * so). But this approximation has high variance for small table
194     * sizes, so we check on any collision for sizes <= 64. Further,
195 jsr166 1.7 * to increase the probability that a resize occurs soon enough, we
196 dl 1.2 * offset the threshold (see THRESHOLD_OFFSET) by the expected
197     * number of puts between checks. This is currently set to 8, in
198     * accord with the default load factor. In practice, this is
199     * rarely overridden, and in any case is close enough to other
200 jsr166 1.7 * plausible values not to waste dynamic probability computation
201 dl 1.1 * for more precision.
202     */
203    
204     /* ---------------- Constants -------------- */
205    
206     /**
207     * The smallest allowed table capacity. Must be a power of 2, at
208     * least 2.
209     */
210     static final int MINIMUM_CAPACITY = 2;
211    
212     /**
213     * The largest allowed table capacity. Must be a power of 2, at
214     * most 1<<30.
215     */
216     static final int MAXIMUM_CAPACITY = 1 << 30;
217    
218     /**
219     * The default initial table capacity. Must be a power of 2, at
220 jsr166 1.9 * least MINIMUM_CAPACITY and at most MAXIMUM_CAPACITY.
221 dl 1.1 */
222     static final int DEFAULT_CAPACITY = 16;
223    
224     /**
225     * The default load factor for this table, used when not otherwise
226     * specified in a constructor.
227     */
228     static final float DEFAULT_LOAD_FACTOR = 0.75f;
229    
230     /**
231     * The default concurrency level for this table. Unused, but
232     * defined for compatibility with previous versions of this class.
233     */
234     static final int DEFAULT_CONCURRENCY_LEVEL = 16;
235    
236     /**
237 jsr166 1.7 * The count value to offset thresholds to compensate for checking
238 dl 1.1 * for resizing only when inserting into bins with two or more
239     * elements. See above for explanation.
240     */
241     static final int THRESHOLD_OFFSET = 8;
242    
243     /**
244     * Special node hash value indicating to use table in node.key
245     * Must be negative.
246     */
247     static final int MOVED = -1;
248    
249     /* ---------------- Fields -------------- */
250    
251     /**
252     * The array of bins. Lazily initialized upon first insertion.
253     * Size is always a power of two. Accessed directly by inner
254     * classes.
255     */
256     transient volatile Node[] table;
257    
258     /** The counter maintaining number of elements. */
259     private transient final LongAdder counter;
260     /** Nonzero when table is being initialized or resized. Updated via CAS. */
261     private transient volatile int resizing;
262     /** The target load factor for the table. */
263     private transient float loadFactor;
264     /** The next element count value upon which to resize the table. */
265     private transient int threshold;
266     /** The initial capacity of the table. */
267     private transient int initCap;
268    
269     // views
270     transient Set<K> keySet;
271     transient Set<Map.Entry<K,V>> entrySet;
272     transient Collection<V> values;
273    
274 jsr166 1.7 /** For serialization compatibility. Null unless serialized; see below */
275 dl 1.1 Segment<K,V>[] segments;
276    
277     /**
278     * Applies a supplemental hash function to a given hashCode, which
279     * defends against poor quality hash functions. The result must
280     * be non-negative, and for reasonable performance must have good
281     * avalanche properties; i.e., that each bit of the argument
282     * affects each bit (except sign bit) of the result.
283     */
284     private static final int spread(int h) {
285     // Apply base step of MurmurHash; see http://code.google.com/p/smhasher/
286     h ^= h >>> 16;
287     h *= 0x85ebca6b;
288     h ^= h >>> 13;
289     h *= 0xc2b2ae35;
290     return (h >>> 16) ^ (h & 0x7fffffff); // mask out sign bit
291     }
292    
293     /**
294     * Key-value entry. Note that this is never exported out as a
295     * user-visible Map.Entry.
296     */
297     static final class Node {
298     final int hash;
299     final Object key;
300     volatile Object val;
301     volatile Node next;
302    
303     Node(int hash, Object key, Object val, Node next) {
304     this.hash = hash;
305     this.key = key;
306     this.val = val;
307     this.next = next;
308     }
309     }
310    
311     /*
312 jsr166 1.7 * Volatile access methods are used for table elements as well as
313 dl 1.1 * elements of in-progress next table while resizing. Uses in
314     * access and update methods are null checked by callers, and
315     * implicitly bounds-checked, relying on the invariants that tab
316     * arrays have non-zero size, and all indices are masked with
317     * (tab.length - 1) which is never negative and always less than
318 dl 1.2 * length. The "relaxed" non-volatile forms are used only during
319     * table initialization. The only other usage is in
320     * HashIterator.advance, which performs explicit checks.
321 dl 1.1 */
322    
323     static final Node tabAt(Node[] tab, int i) { // used in HashIterator
324     return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
325     }
326    
327     private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
328     return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
329     }
330    
331     private static final void setTabAt(Node[] tab, int i, Node v) {
332     UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
333     }
334    
335 dl 1.2 private static final Node relaxedTabAt(Node[] tab, int i) {
336     return (Node)UNSAFE.getObject(tab, ((long)i<<ASHIFT)+ABASE);
337     }
338    
339     private static final void relaxedSetTabAt(Node[] tab, int i, Node v) {
340     UNSAFE.putObject(tab, ((long)i<<ASHIFT)+ABASE, v);
341     }
342    
343 dl 1.1 /* ---------------- Access and update operations -------------- */
344    
345 dl 1.2 /** Implementation for get and containsKey **/
346 jsr166 1.4 private final Object internalGet(Object k) {
347 dl 1.1 int h = spread(k.hashCode());
348     Node[] tab = table;
349     retry: while (tab != null) {
350     Node e = tabAt(tab, (tab.length - 1) & h);
351     while (e != null) {
352     int eh = e.hash;
353     if (eh == h) {
354     Object ek = e.key, ev = e.val;
355     if (ev != null && ek != null && (k == ek || k.equals(ek)))
356     return ev;
357     }
358 dl 1.2 else if (eh < 0) { // bin was moved during resize
359 dl 1.1 tab = (Node[])e.key;
360     continue retry;
361     }
362     e = e.next;
363     }
364     break;
365     }
366     return null;
367     }
368    
369 dl 1.2 /** Implementation for put and putIfAbsent **/
370 dl 1.1 private final Object internalPut(Object k, Object v, boolean replace) {
371     int h = spread(k.hashCode());
372     Object oldVal = null; // the previous value or null if none
373     Node[] tab = table;
374     for (;;) {
375     Node e; int i;
376     if (tab == null)
377     tab = grow(0);
378     else if ((e = tabAt(tab, i = (tab.length - 1) & h)) == null) {
379 dl 1.2 if (casTabAt(tab, i, null, new Node(h, k, v, null)))
380 dl 1.1 break;
381     }
382     else if (e.hash < 0)
383     tab = (Node[])e.key;
384     else {
385     boolean validated = false;
386     boolean checkSize = false;
387 jsr166 1.4 synchronized (e) {
388 dl 1.1 Node first = e;
389     for (;;) {
390     Object ek, ev;
391     if ((ev = e.val) == null)
392     break;
393     if (e.hash == h && (ek = e.key) != null &&
394     (k == ek || k.equals(ek))) {
395     if (tabAt(tab, i) == first) {
396     validated = true;
397     oldVal = ev;
398     if (replace)
399     e.val = v;
400     }
401     break;
402     }
403     Node last = e;
404     if ((e = e.next) == null) {
405     if (tabAt(tab, i) == first) {
406     validated = true;
407 dl 1.2 last.next = new Node(h, k, v, null);
408     if (last != first || tab.length <= 64)
409 dl 1.1 checkSize = true;
410     }
411     break;
412     }
413     }
414     }
415     if (validated) {
416     if (checkSize && tab.length < MAXIMUM_CAPACITY &&
417     resizing == 0 && counter.sum() >= threshold)
418     grow(0);
419     break;
420     }
421     }
422     }
423     if (oldVal == null)
424     counter.increment();
425     return oldVal;
426     }
427    
428     /**
429     * Covers the four public remove/replace methods: Replaces node
430     * value with v, conditional upon match of cv if non-null. If
431     * resulting value is null, delete.
432     */
433     private final Object internalReplace(Object k, Object v, Object cv) {
434     int h = spread(k.hashCode());
435     Object oldVal = null;
436     Node e; int i;
437     Node[] tab = table;
438     while (tab != null &&
439     (e = tabAt(tab, i = (tab.length - 1) & h)) != null) {
440     if (e.hash < 0)
441     tab = (Node[])e.key;
442     else {
443     boolean validated = false;
444     boolean deleted = false;
445 jsr166 1.4 synchronized (e) {
446 dl 1.1 Node pred = null;
447     Node first = e;
448     for (;;) {
449     Object ek, ev;
450     if ((ev = e.val) == null)
451     break;
452     if (e.hash == h && (ek = e.key) != null &&
453     (k == ek || k.equals(ek))) {
454     if (tabAt(tab, i) == first) {
455     validated = true;
456     if (cv == null || cv == ev || cv.equals(ev)) {
457     oldVal = ev;
458     if ((e.val = v) == null) {
459     deleted = true;
460     Node en = e.next;
461     if (pred != null)
462     pred.next = en;
463     else
464     setTabAt(tab, i, en);
465     }
466     }
467     }
468     break;
469     }
470     pred = e;
471     if ((e = e.next) == null) {
472     if (tabAt(tab, i) == first)
473     validated = true;
474     break;
475     }
476     }
477     }
478     if (validated) {
479     if (deleted)
480     counter.decrement();
481     break;
482     }
483     }
484     }
485     return oldVal;
486     }
487    
488 dl 1.2 /** Implementation for computeIfAbsent and compute */
489 dl 1.1 @SuppressWarnings("unchecked")
490 dl 1.2 private final V internalCompute(K k,
491     MappingFunction<? super K, ? extends V> f,
492     boolean replace) {
493 dl 1.1 int h = spread(k.hashCode());
494     V val = null;
495     boolean added = false;
496     boolean validated = false;
497     Node[] tab = table;
498     do {
499     Node e; int i;
500     if (tab == null)
501     tab = grow(0);
502     else if ((e = tabAt(tab, i = (tab.length - 1) & h)) == null) {
503 dl 1.2 Node node = new Node(h, k, null, null);
504 jsr166 1.4 synchronized (node) {
505 dl 1.1 if (casTabAt(tab, i, null, node)) {
506     validated = true;
507     try {
508     val = f.map(k);
509     if (val != null) {
510     node.val = val;
511     added = true;
512     }
513     } finally {
514     if (!added)
515     setTabAt(tab, i, null);
516     }
517     }
518     }
519     }
520     else if (e.hash < 0)
521     tab = (Node[])e.key;
522 dl 1.5 else if (Thread.holdsLock(e))
523     throw new IllegalStateException("Recursive map computation");
524 dl 1.1 else {
525     boolean checkSize = false;
526 jsr166 1.4 synchronized (e) {
527 dl 1.1 Node first = e;
528     for (;;) {
529     Object ek, ev;
530     if ((ev = e.val) == null)
531     break;
532     if (e.hash == h && (ek = e.key) != null &&
533     (k == ek || k.equals(ek))) {
534     if (tabAt(tab, i) == first) {
535     validated = true;
536 dl 1.2 if (replace && (ev = f.map(k)) != null)
537     e.val = ev;
538 dl 1.1 val = (V)ev;
539     }
540     break;
541     }
542     Node last = e;
543     if ((e = e.next) == null) {
544     if (tabAt(tab, i) == first) {
545     validated = true;
546     if ((val = f.map(k)) != null) {
547 dl 1.2 last.next = new Node(h, k, val, null);
548     added = true;
549     if (last != first || tab.length <= 64)
550 dl 1.1 checkSize = true;
551     }
552     }
553     break;
554     }
555     }
556     }
557     if (checkSize && tab.length < MAXIMUM_CAPACITY &&
558     resizing == 0 && counter.sum() >= threshold)
559     grow(0);
560     }
561     } while (!validated);
562     if (added)
563     counter.increment();
564     return val;
565     }
566    
567     /*
568     * Reclassifies nodes in each bin to new table. Because we are
569     * using power-of-two expansion, the elements from each bin must
570     * either stay at same index, or move with a power of two
571     * offset. We eliminate unnecessary node creation by catching
572     * cases where old nodes can be reused because their next fields
573     * won't change. Statistically, at the default threshold, only
574     * about one-sixth of them need cloning when a table doubles. The
575     * nodes they replace will be garbage collectable as soon as they
576     * are no longer referenced by any reader thread that may be in
577     * the midst of concurrently traversing table.
578     *
579     * Transfers are done from the bottom up to preserve iterator
580     * traversability. On each step, the old bin is locked,
581     * moved/copied, and then replaced with a forwarding node.
582     */
583     private static final void transfer(Node[] tab, Node[] nextTab) {
584     int n = tab.length;
585     int mask = nextTab.length - 1;
586     Node fwd = new Node(MOVED, nextTab, null, null);
587     for (int i = n - 1; i >= 0; --i) {
588     for (Node e;;) {
589     if ((e = tabAt(tab, i)) == null) {
590     if (casTabAt(tab, i, e, fwd))
591     break;
592     }
593     else {
594     boolean validated = false;
595 jsr166 1.4 synchronized (e) {
596 dl 1.1 int idx = e.hash & mask;
597     Node lastRun = e;
598     for (Node p = e.next; p != null; p = p.next) {
599     int j = p.hash & mask;
600     if (j != idx) {
601     idx = j;
602     lastRun = p;
603     }
604     }
605     if (tabAt(tab, i) == e) {
606     validated = true;
607 dl 1.2 relaxedSetTabAt(nextTab, idx, lastRun);
608 dl 1.1 for (Node p = e; p != lastRun; p = p.next) {
609     int h = p.hash;
610     int j = h & mask;
611 dl 1.2 Node r = relaxedTabAt(nextTab, j);
612     relaxedSetTabAt(nextTab, j,
613     new Node(h, p.key, p.val, r));
614 dl 1.1 }
615     setTabAt(tab, i, fwd);
616     }
617     }
618     if (validated)
619     break;
620     }
621     }
622     }
623     }
624    
625     /**
626     * If not already resizing, initializes or creates next table and
627     * transfers bins. Rechecks occupancy after a transfer to see if
628     * another resize is already needed because resizings are lagging
629     * additions.
630     *
631     * @param sizeHint overridden capacity target (nonzero only from putAll)
632     * @return current table
633     */
634     private final Node[] grow(int sizeHint) {
635     if (resizing == 0 &&
636     UNSAFE.compareAndSwapInt(this, resizingOffset, 0, 1)) {
637     try {
638     for (;;) {
639     int cap, n;
640 dl 1.2 Node[] tab = table;
641     if (tab == null) {
642 dl 1.1 int c = initCap;
643     if (c < sizeHint)
644     c = sizeHint;
645     if (c == DEFAULT_CAPACITY)
646     cap = c;
647     else if (c >= MAXIMUM_CAPACITY)
648     cap = MAXIMUM_CAPACITY;
649     else {
650     cap = MINIMUM_CAPACITY;
651     while (cap < c)
652     cap <<= 1;
653     }
654     }
655     else if ((n = tab.length) < MAXIMUM_CAPACITY &&
656     (sizeHint <= 0 || n < sizeHint))
657     cap = n << 1;
658     else
659     break;
660     threshold = (int)(cap * loadFactor) - THRESHOLD_OFFSET;
661     Node[] nextTab = new Node[cap];
662     if (tab != null)
663     transfer(tab, nextTab);
664     table = nextTab;
665 dl 1.2 if (tab == null || cap >= MAXIMUM_CAPACITY ||
666     (sizeHint > 0 && cap >= sizeHint) ||
667     counter.sum() < threshold)
668 dl 1.1 break;
669     }
670     } finally {
671     resizing = 0;
672     }
673     }
674 dl 1.2 else if (table == null)
675 dl 1.1 Thread.yield(); // lost initialization race; just spin
676 dl 1.2 return table;
677 dl 1.1 }
678    
679     /**
680 dl 1.2 * Implementation for putAll and constructor with Map
681     * argument. Tries to first override initial capacity or grow
682     * based on map size to pre-allocate table space.
683 dl 1.1 */
684     private final void internalPutAll(Map<? extends K, ? extends V> m) {
685     int s = m.size();
686 jsr166 1.4 grow((s >= (MAXIMUM_CAPACITY >>> 1)) ? s : s + (s >>> 1));
687 dl 1.1 for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
688     Object k = e.getKey();
689     Object v = e.getValue();
690     if (k == null || v == null)
691     throw new NullPointerException();
692     internalPut(k, v, true);
693     }
694     }
695    
696     /**
697 dl 1.2 * Implementation for clear. Steps through each bin, removing all nodes.
698 dl 1.1 */
699     private final void internalClear() {
700 dl 1.2 long deletions = 0L;
701 dl 1.1 int i = 0;
702     Node[] tab = table;
703     while (tab != null && i < tab.length) {
704     Node e = tabAt(tab, i);
705     if (e == null)
706     ++i;
707     else if (e.hash < 0)
708     tab = (Node[])e.key;
709     else {
710     boolean validated = false;
711 jsr166 1.4 synchronized (e) {
712 dl 1.1 if (tabAt(tab, i) == e) {
713     validated = true;
714     do {
715     if (e.val != null) {
716     e.val = null;
717 dl 1.2 ++deletions;
718 dl 1.1 }
719     } while ((e = e.next) != null);
720     setTabAt(tab, i, null);
721     }
722     }
723 dl 1.2 if (validated) {
724 dl 1.1 ++i;
725 dl 1.2 if (deletions > THRESHOLD_OFFSET) { // bound lag in counts
726     counter.add(-deletions);
727     deletions = 0L;
728     }
729     }
730 dl 1.1 }
731     }
732 dl 1.2 if (deletions != 0L)
733     counter.add(-deletions);
734 dl 1.1 }
735    
736     /**
737     * Base class for key, value, and entry iterators, plus internal
738     * implementations of public traversal-based methods, to avoid
739     * duplicating traversal code.
740     */
741     class HashIterator {
742     private Node next; // the next entry to return
743     private Node[] tab; // current table; updated if resized
744     private Node lastReturned; // the last entry returned, for remove
745     private Object nextVal; // cached value of next
746     private int index; // index of bin to use next
747     private int baseIndex; // current index of initial table
748     private final int baseSize; // initial table size
749    
750     HashIterator() {
751     Node[] t = tab = table;
752     if (t == null)
753     baseSize = 0;
754     else {
755     baseSize = t.length;
756     advance(null);
757     }
758     }
759    
760     public final boolean hasNext() { return next != null; }
761     public final boolean hasMoreElements() { return next != null; }
762    
763     /**
764     * Advances next. Normally, iteration proceeds bin-by-bin
765     * traversing lists. However, if the table has been resized,
766     * then all future steps must traverse both the bin at the
767     * current index as well as at (index + baseSize); and so on
768     * for further resizings. To paranoically cope with potential
769     * (improper) sharing of iterators across threads, table reads
770     * are bounds-checked.
771     */
772     final void advance(Node e) {
773     for (;;) {
774     Node[] t; int i; // for bounds checks
775     if (e != null) {
776     Object ek = e.key, ev = e.val;
777     if (ev != null && ek != null) {
778     nextVal = ev;
779     next = e;
780     break;
781     }
782     e = e.next;
783     }
784     else if (baseIndex < baseSize && (t = tab) != null &&
785     t.length > (i = index) && i >= 0) {
786     if ((e = tabAt(t, i)) != null && e.hash < 0) {
787     tab = (Node[])e.key;
788     e = null;
789     }
790     else if (i + baseSize < t.length)
791     index += baseSize; // visit forwarded upper slots
792     else
793     index = ++baseIndex;
794     }
795     else {
796     next = null;
797     break;
798     }
799     }
800     }
801    
802     final Object nextKey() {
803     Node e = next;
804     if (e == null)
805     throw new NoSuchElementException();
806     Object k = e.key;
807     advance((lastReturned = e).next);
808     return k;
809     }
810    
811     final Object nextValue() {
812     Node e = next;
813     if (e == null)
814     throw new NoSuchElementException();
815     Object v = nextVal;
816     advance((lastReturned = e).next);
817     return v;
818     }
819    
820     final WriteThroughEntry nextEntry() {
821     Node e = next;
822     if (e == null)
823     throw new NoSuchElementException();
824     WriteThroughEntry entry =
825     new WriteThroughEntry(e.key, nextVal);
826     advance((lastReturned = e).next);
827     return entry;
828     }
829    
830     public final void remove() {
831     if (lastReturned == null)
832     throw new IllegalStateException();
833     ConcurrentHashMapV8.this.remove(lastReturned.key);
834     lastReturned = null;
835     }
836    
837     /** Helper for serialization */
838     final void writeEntries(java.io.ObjectOutputStream s)
839     throws java.io.IOException {
840     Node e;
841     while ((e = next) != null) {
842     s.writeObject(e.key);
843     s.writeObject(nextVal);
844     advance(e.next);
845     }
846     }
847    
848     /** Helper for containsValue */
849     final boolean containsVal(Object value) {
850     if (value != null) {
851     Node e;
852     while ((e = next) != null) {
853     Object v = nextVal;
854     if (value == v || value.equals(v))
855     return true;
856     advance(e.next);
857     }
858     }
859     return false;
860     }
861    
862     /** Helper for Map.hashCode */
863     final int mapHashCode() {
864     int h = 0;
865     Node e;
866     while ((e = next) != null) {
867     h += e.key.hashCode() ^ nextVal.hashCode();
868     advance(e.next);
869     }
870     return h;
871     }
872    
873     /** Helper for Map.toString */
874     final String mapToString() {
875     Node e = next;
876     if (e == null)
877     return "{}";
878     StringBuilder sb = new StringBuilder();
879     sb.append('{');
880     for (;;) {
881     sb.append(e.key == this ? "(this Map)" : e.key);
882     sb.append('=');
883     sb.append(nextVal == this ? "(this Map)" : nextVal);
884     advance(e.next);
885     if ((e = next) != null)
886     sb.append(',').append(' ');
887     else
888     return sb.append('}').toString();
889     }
890     }
891     }
892    
893     /* ---------------- Public operations -------------- */
894    
895     /**
896     * Creates a new, empty map with the specified initial
897     * capacity, load factor and concurrency level.
898     *
899     * @param initialCapacity the initial capacity. The implementation
900     * performs internal sizing to accommodate this many elements.
901     * @param loadFactor the load factor threshold, used to control resizing.
902     * Resizing may be performed when the average number of elements per
903     * bin exceeds this threshold.
904     * @param concurrencyLevel the estimated number of concurrently
905     * updating threads. The implementation may use this value as
906     * a sizing hint.
907     * @throws IllegalArgumentException if the initial capacity is
908     * negative or the load factor or concurrencyLevel are
909     * nonpositive.
910     */
911     public ConcurrentHashMapV8(int initialCapacity,
912 jsr166 1.9 float loadFactor, int concurrencyLevel) {
913 dl 1.1 if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
914     throw new IllegalArgumentException();
915     this.initCap = initialCapacity;
916     this.loadFactor = loadFactor;
917     this.counter = new LongAdder();
918     }
919    
920     /**
921     * Creates a new, empty map with the specified initial capacity
922     * and load factor and with the default concurrencyLevel (16).
923     *
924     * @param initialCapacity The implementation performs internal
925     * sizing to accommodate this many elements.
926     * @param loadFactor the load factor threshold, used to control resizing.
927     * Resizing may be performed when the average number of elements per
928     * bin exceeds this threshold.
929     * @throws IllegalArgumentException if the initial capacity of
930     * elements is negative or the load factor is nonpositive
931     *
932     * @since 1.6
933     */
934     public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
935     this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
936     }
937    
938     /**
939     * Creates a new, empty map with the specified initial capacity,
940     * and with default load factor (0.75) and concurrencyLevel (16).
941     *
942     * @param initialCapacity the initial capacity. The implementation
943     * performs internal sizing to accommodate this many elements.
944     * @throws IllegalArgumentException if the initial capacity of
945     * elements is negative.
946     */
947     public ConcurrentHashMapV8(int initialCapacity) {
948     this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
949     }
950    
951     /**
952     * Creates a new, empty map with a default initial capacity (16),
953     * load factor (0.75) and concurrencyLevel (16).
954     */
955     public ConcurrentHashMapV8() {
956     this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
957     }
958    
959     /**
960     * Creates a new map with the same mappings as the given map.
961     * The map is created with a capacity of 1.5 times the number
962     * of mappings in the given map or 16 (whichever is greater),
963     * and a default load factor (0.75) and concurrencyLevel (16).
964     *
965     * @param m the map
966     */
967     public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
968     this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
969     if (m == null)
970     throw new NullPointerException();
971     internalPutAll(m);
972     }
973    
974     /**
975     * Returns {@code true} if this map contains no key-value mappings.
976     *
977     * @return {@code true} if this map contains no key-value mappings
978     */
979     public boolean isEmpty() {
980 dl 1.2 return counter.sum() <= 0L; // ignore transient negative values
981 dl 1.1 }
982    
983     /**
984     * Returns the number of key-value mappings in this map. If the
985     * map contains more than {@code Integer.MAX_VALUE} elements, returns
986     * {@code Integer.MAX_VALUE}.
987     *
988     * @return the number of key-value mappings in this map
989     */
990     public int size() {
991     long n = counter.sum();
992 jsr166 1.6 return ((n >>> 31) == 0) ? (int)n : (n < 0L) ? 0 : Integer.MAX_VALUE;
993 dl 1.1 }
994    
995     /**
996     * Returns the value to which the specified key is mapped,
997     * or {@code null} if this map contains no mapping for the key.
998     *
999     * <p>More formally, if this map contains a mapping from a key
1000     * {@code k} to a value {@code v} such that {@code key.equals(k)},
1001     * then this method returns {@code v}; otherwise it returns
1002     * {@code null}. (There can be at most one such mapping.)
1003     *
1004     * @throws NullPointerException if the specified key is null
1005     */
1006     @SuppressWarnings("unchecked")
1007     public V get(Object key) {
1008     if (key == null)
1009     throw new NullPointerException();
1010     return (V)internalGet(key);
1011     }
1012    
1013     /**
1014     * Tests if the specified object is a key in this table.
1015     *
1016     * @param key possible key
1017     * @return {@code true} if and only if the specified object
1018     * is a key in this table, as determined by the
1019     * {@code equals} method; {@code false} otherwise.
1020     * @throws NullPointerException if the specified key is null
1021     */
1022     public boolean containsKey(Object key) {
1023     if (key == null)
1024     throw new NullPointerException();
1025     return internalGet(key) != null;
1026     }
1027    
1028     /**
1029     * Returns {@code true} if this map maps one or more keys to the
1030     * specified value. Note: This method requires a full internal
1031     * traversal of the hash table, and so is much slower than
1032     * method {@code containsKey}.
1033     *
1034     * @param value value whose presence in this map is to be tested
1035     * @return {@code true} if this map maps one or more keys to the
1036     * specified value
1037     * @throws NullPointerException if the specified value is null
1038     */
1039     public boolean containsValue(Object value) {
1040     if (value == null)
1041     throw new NullPointerException();
1042     return new HashIterator().containsVal(value);
1043     }
1044    
1045     /**
1046     * Legacy method testing if some key maps into the specified value
1047     * in this table. This method is identical in functionality to
1048     * {@link #containsValue}, and exists solely to ensure
1049     * full compatibility with class {@link java.util.Hashtable},
1050     * which supported this method prior to introduction of the
1051     * Java Collections framework.
1052     *
1053     * @param value a value to search for
1054     * @return {@code true} if and only if some key maps to the
1055     * {@code value} argument in this table as
1056     * determined by the {@code equals} method;
1057     * {@code false} otherwise
1058     * @throws NullPointerException if the specified value is null
1059     */
1060     public boolean contains(Object value) {
1061     return containsValue(value);
1062     }
1063    
1064     /**
1065     * Maps the specified key to the specified value in this table.
1066     * Neither the key nor the value can be null.
1067     *
1068     * <p> The value can be retrieved by calling the {@code get} method
1069     * with a key that is equal to the original key.
1070     *
1071     * @param key key with which the specified value is to be associated
1072     * @param value value to be associated with the specified key
1073     * @return the previous value associated with {@code key}, or
1074     * {@code null} if there was no mapping for {@code key}
1075     * @throws NullPointerException if the specified key or value is null
1076     */
1077     @SuppressWarnings("unchecked")
1078     public V put(K key, V value) {
1079     if (key == null || value == null)
1080     throw new NullPointerException();
1081     return (V)internalPut(key, value, true);
1082     }
1083    
1084     /**
1085     * {@inheritDoc}
1086     *
1087     * @return the previous value associated with the specified key,
1088     * or {@code null} if there was no mapping for the key
1089     * @throws NullPointerException if the specified key or value is null
1090     */
1091     @SuppressWarnings("unchecked")
1092     public V putIfAbsent(K key, V value) {
1093     if (key == null || value == null)
1094     throw new NullPointerException();
1095     return (V)internalPut(key, value, false);
1096     }
1097    
1098     /**
1099     * Copies all of the mappings from the specified map to this one.
1100     * These mappings replace any mappings that this map had for any of the
1101     * keys currently in the specified map.
1102     *
1103     * @param m mappings to be stored in this map
1104     */
1105     public void putAll(Map<? extends K, ? extends V> m) {
1106     if (m == null)
1107     throw new NullPointerException();
1108     internalPutAll(m);
1109     }
1110    
1111     /**
1112     * If the specified key is not already associated with a value,
1113     * computes its value using the given mappingFunction, and if
1114     * non-null, enters it into the map. This is equivalent to
1115     *
1116     * <pre>
1117     * if (map.containsKey(key))
1118     * return map.get(key);
1119     * value = mappingFunction.map(key);
1120     * if (value != null)
1121 dl 1.2 * map.put(key, value);
1122     * return value;
1123 dl 1.1 * </pre>
1124     *
1125     * except that the action is performed atomically. Some attempted
1126 dl 1.5 * update operations on this map by other threads may be blocked
1127     * while computation is in progress, so the computation should be
1128     * short and simple, and must not attempt to update any other
1129     * mappings of this Map. The most appropriate usage is to
1130     * construct a new object serving as an initial mapped value, or
1131     * memoized result, as in:
1132     * <pre>{@code
1133     * map.computeIfAbsent(key, new MappingFunction<K, V>() {
1134     * public V map(K k) { return new Value(f(k)); }};
1135     * }</pre>
1136 dl 1.1 *
1137     * @param key key with which the specified value is to be associated
1138     * @param mappingFunction the function to compute a value
1139     * @return the current (existing or computed) value associated with
1140     * the specified key, or {@code null} if the computation
1141     * returned {@code null}.
1142     * @throws NullPointerException if the specified key or mappingFunction
1143     * is null,
1144 dl 1.5 * @throws IllegalStateException if the computation detectably
1145     * attempts a recursive update to this map that would
1146     * otherwise never complete.
1147 dl 1.1 * @throws RuntimeException or Error if the mappingFunction does so,
1148     * in which case the mapping is left unestablished.
1149     */
1150     public V computeIfAbsent(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
1151     if (key == null || mappingFunction == null)
1152     throw new NullPointerException();
1153 dl 1.2 return internalCompute(key, mappingFunction, false);
1154     }
1155    
1156     /**
1157 dl 1.5 * Computes the value associated with the given key using the given
1158 dl 1.2 * mappingFunction, and if non-null, enters it into the map. This
1159     * is equivalent to
1160     *
1161     * <pre>
1162     * value = mappingFunction.map(key);
1163     * if (value != null)
1164     * map.put(key, value);
1165     * else
1166 dl 1.5 * value = map.get(key);
1167     * return value;
1168 dl 1.2 * </pre>
1169     *
1170     * except that the action is performed atomically. Some attempted
1171 dl 1.5 * update operations on this map by other threads may be blocked
1172     * while computation is in progress, so the computation should be
1173     * short and simple, and must not attempt to update any other
1174     * mappings of this Map.
1175 dl 1.2 *
1176     * @param key key with which the specified value is to be associated
1177     * @param mappingFunction the function to compute a value
1178     * @return the current value associated with
1179     * the specified key, or {@code null} if the computation
1180     * returned {@code null} and the value was not otherwise present.
1181     * @throws NullPointerException if the specified key or mappingFunction
1182     * is null,
1183 dl 1.5 * @throws IllegalStateException if the computation detectably
1184     * attempts a recursive update to this map that would
1185     * otherwise never complete.
1186 dl 1.2 * @throws RuntimeException or Error if the mappingFunction does so,
1187     * in which case the mapping is unchanged.
1188     */
1189     public V compute(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
1190     if (key == null || mappingFunction == null)
1191     throw new NullPointerException();
1192     return internalCompute(key, mappingFunction, true);
1193 dl 1.1 }
1194    
1195     /**
1196     * Removes the key (and its corresponding value) from this map.
1197     * This method does nothing if the key is not in the map.
1198     *
1199     * @param key the key that needs to be removed
1200     * @return the previous value associated with {@code key}, or
1201     * {@code null} if there was no mapping for {@code key}
1202     * @throws NullPointerException if the specified key is null
1203     */
1204     @SuppressWarnings("unchecked")
1205     public V remove(Object key) {
1206     if (key == null)
1207     throw new NullPointerException();
1208 jsr166 1.3 return (V)internalReplace(key, null, null);
1209 dl 1.1 }
1210    
1211     /**
1212     * {@inheritDoc}
1213     *
1214     * @throws NullPointerException if the specified key is null
1215     */
1216     public boolean remove(Object key, Object value) {
1217     if (key == null)
1218     throw new NullPointerException();
1219     if (value == null)
1220     return false;
1221     return internalReplace(key, null, value) != null;
1222     }
1223    
1224     /**
1225     * {@inheritDoc}
1226     *
1227     * @throws NullPointerException if any of the arguments are null
1228     */
1229     public boolean replace(K key, V oldValue, V newValue) {
1230     if (key == null || oldValue == null || newValue == null)
1231     throw new NullPointerException();
1232 jsr166 1.3 return internalReplace(key, newValue, oldValue) != null;
1233 dl 1.1 }
1234    
1235     /**
1236     * {@inheritDoc}
1237     *
1238     * @return the previous value associated with the specified key,
1239     * or {@code null} if there was no mapping for the key
1240     * @throws NullPointerException if the specified key or value is null
1241     */
1242     @SuppressWarnings("unchecked")
1243     public V replace(K key, V value) {
1244     if (key == null || value == null)
1245     throw new NullPointerException();
1246 jsr166 1.3 return (V)internalReplace(key, value, null);
1247 dl 1.1 }
1248    
1249     /**
1250     * Removes all of the mappings from this map.
1251     */
1252     public void clear() {
1253     internalClear();
1254     }
1255    
1256     /**
1257     * Returns a {@link Set} view of the keys contained in this map.
1258     * The set is backed by the map, so changes to the map are
1259     * reflected in the set, and vice-versa. The set supports element
1260     * removal, which removes the corresponding mapping from this map,
1261     * via the {@code Iterator.remove}, {@code Set.remove},
1262     * {@code removeAll}, {@code retainAll}, and {@code clear}
1263     * operations. It does not support the {@code add} or
1264     * {@code addAll} operations.
1265     *
1266     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1267     * that will never throw {@link ConcurrentModificationException},
1268     * and guarantees to traverse elements as they existed upon
1269     * construction of the iterator, and may (but is not guaranteed to)
1270     * reflect any modifications subsequent to construction.
1271     */
1272     public Set<K> keySet() {
1273     Set<K> ks = keySet;
1274     return (ks != null) ? ks : (keySet = new KeySet());
1275     }
1276    
1277     /**
1278     * Returns a {@link Collection} view of the values contained in this map.
1279     * The collection is backed by the map, so changes to the map are
1280     * reflected in the collection, and vice-versa. The collection
1281     * supports element removal, which removes the corresponding
1282     * mapping from this map, via the {@code Iterator.remove},
1283     * {@code Collection.remove}, {@code removeAll},
1284     * {@code retainAll}, and {@code clear} operations. It does not
1285     * support the {@code add} or {@code addAll} operations.
1286     *
1287     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1288     * that will never throw {@link ConcurrentModificationException},
1289     * and guarantees to traverse elements as they existed upon
1290     * construction of the iterator, and may (but is not guaranteed to)
1291     * reflect any modifications subsequent to construction.
1292     */
1293     public Collection<V> values() {
1294     Collection<V> vs = values;
1295     return (vs != null) ? vs : (values = new Values());
1296     }
1297    
1298     /**
1299     * Returns a {@link Set} view of the mappings contained in this map.
1300     * The set is backed by the map, so changes to the map are
1301     * reflected in the set, and vice-versa. The set supports element
1302     * removal, which removes the corresponding mapping from the map,
1303     * via the {@code Iterator.remove}, {@code Set.remove},
1304     * {@code removeAll}, {@code retainAll}, and {@code clear}
1305     * operations. It does not support the {@code add} or
1306     * {@code addAll} operations.
1307     *
1308     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1309     * that will never throw {@link ConcurrentModificationException},
1310     * and guarantees to traverse elements as they existed upon
1311     * construction of the iterator, and may (but is not guaranteed to)
1312     * reflect any modifications subsequent to construction.
1313     */
1314     public Set<Map.Entry<K,V>> entrySet() {
1315     Set<Map.Entry<K,V>> es = entrySet;
1316     return (es != null) ? es : (entrySet = new EntrySet());
1317     }
1318    
1319     /**
1320     * Returns an enumeration of the keys in this table.
1321     *
1322     * @return an enumeration of the keys in this table
1323     * @see #keySet()
1324     */
1325     public Enumeration<K> keys() {
1326     return new KeyIterator();
1327     }
1328    
1329     /**
1330     * Returns an enumeration of the values in this table.
1331     *
1332     * @return an enumeration of the values in this table
1333     * @see #values()
1334     */
1335     public Enumeration<V> elements() {
1336     return new ValueIterator();
1337     }
1338    
1339     /**
1340 dl 1.2 * Returns the hash code value for this {@link Map}, i.e.,
1341     * the sum of, for each key-value pair in the map,
1342     * {@code key.hashCode() ^ value.hashCode()}.
1343     *
1344     * @return the hash code value for this map
1345 dl 1.1 */
1346     public int hashCode() {
1347     return new HashIterator().mapHashCode();
1348     }
1349    
1350     /**
1351 dl 1.2 * Returns a string representation of this map. The string
1352     * representation consists of a list of key-value mappings (in no
1353     * particular order) enclosed in braces ("{@code {}}"). Adjacent
1354     * mappings are separated by the characters {@code ", "} (comma
1355     * and space). Each key-value mapping is rendered as the key
1356     * followed by an equals sign ("{@code =}") followed by the
1357     * associated value.
1358     *
1359     * @return a string representation of this map
1360 dl 1.1 */
1361     public String toString() {
1362     return new HashIterator().mapToString();
1363     }
1364    
1365     /**
1366 dl 1.2 * Compares the specified object with this map for equality.
1367     * Returns {@code true} if the given object is a map with the same
1368     * mappings as this map. This operation may return misleading
1369     * results if either map is concurrently modified during execution
1370     * of this method.
1371     *
1372     * @param o object to be compared for equality with this map
1373     * @return {@code true} if the specified object is equal to this map
1374 dl 1.1 */
1375     public boolean equals(Object o) {
1376     if (o == this)
1377     return true;
1378     if (!(o instanceof Map))
1379     return false;
1380     Map<?,?> m = (Map<?,?>) o;
1381     try {
1382     for (Map.Entry<K,V> e : this.entrySet())
1383     if (! e.getValue().equals(m.get(e.getKey())))
1384     return false;
1385     for (Map.Entry<?,?> e : m.entrySet()) {
1386     Object k = e.getKey();
1387     Object v = e.getValue();
1388     if (k == null || v == null || !v.equals(get(k)))
1389     return false;
1390     }
1391     return true;
1392     } catch (ClassCastException unused) {
1393     return false;
1394     } catch (NullPointerException unused) {
1395     return false;
1396     }
1397     }
1398    
1399     /**
1400     * Custom Entry class used by EntryIterator.next(), that relays
1401     * setValue changes to the underlying map.
1402     */
1403     final class WriteThroughEntry extends AbstractMap.SimpleEntry<K,V> {
1404     @SuppressWarnings("unchecked")
1405     WriteThroughEntry(Object k, Object v) {
1406     super((K)k, (V)v);
1407     }
1408    
1409     /**
1410     * Sets our entry's value and writes through to the map. The
1411     * value to return is somewhat arbitrary here. Since a
1412     * WriteThroughEntry does not necessarily track asynchronous
1413     * changes, the most recent "previous" value could be
1414     * different from what we return (or could even have been
1415     * removed in which case the put will re-establish). We do not
1416     * and cannot guarantee more.
1417     */
1418     public V setValue(V value) {
1419     if (value == null) throw new NullPointerException();
1420     V v = super.setValue(value);
1421     ConcurrentHashMapV8.this.put(getKey(), value);
1422     return v;
1423     }
1424     }
1425    
1426     final class KeyIterator extends HashIterator
1427     implements Iterator<K>, Enumeration<K> {
1428     @SuppressWarnings("unchecked")
1429     public final K next() { return (K)super.nextKey(); }
1430     @SuppressWarnings("unchecked")
1431     public final K nextElement() { return (K)super.nextKey(); }
1432     }
1433    
1434     final class ValueIterator extends HashIterator
1435     implements Iterator<V>, Enumeration<V> {
1436     @SuppressWarnings("unchecked")
1437     public final V next() { return (V)super.nextValue(); }
1438     @SuppressWarnings("unchecked")
1439     public final V nextElement() { return (V)super.nextValue(); }
1440     }
1441    
1442     final class EntryIterator extends HashIterator
1443     implements Iterator<Entry<K,V>> {
1444     public final Map.Entry<K,V> next() { return super.nextEntry(); }
1445     }
1446    
1447     final class KeySet extends AbstractSet<K> {
1448     public int size() {
1449     return ConcurrentHashMapV8.this.size();
1450     }
1451     public boolean isEmpty() {
1452     return ConcurrentHashMapV8.this.isEmpty();
1453     }
1454     public void clear() {
1455     ConcurrentHashMapV8.this.clear();
1456     }
1457     public Iterator<K> iterator() {
1458     return new KeyIterator();
1459     }
1460     public boolean contains(Object o) {
1461     return ConcurrentHashMapV8.this.containsKey(o);
1462     }
1463     public boolean remove(Object o) {
1464     return ConcurrentHashMapV8.this.remove(o) != null;
1465     }
1466     }
1467    
1468     final class Values extends AbstractCollection<V> {
1469     public int size() {
1470     return ConcurrentHashMapV8.this.size();
1471     }
1472     public boolean isEmpty() {
1473     return ConcurrentHashMapV8.this.isEmpty();
1474     }
1475     public void clear() {
1476     ConcurrentHashMapV8.this.clear();
1477     }
1478     public Iterator<V> iterator() {
1479     return new ValueIterator();
1480     }
1481     public boolean contains(Object o) {
1482     return ConcurrentHashMapV8.this.containsValue(o);
1483     }
1484     }
1485    
1486     final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1487     public int size() {
1488     return ConcurrentHashMapV8.this.size();
1489     }
1490     public boolean isEmpty() {
1491     return ConcurrentHashMapV8.this.isEmpty();
1492     }
1493     public void clear() {
1494     ConcurrentHashMapV8.this.clear();
1495     }
1496     public Iterator<Map.Entry<K,V>> iterator() {
1497     return new EntryIterator();
1498     }
1499     public boolean contains(Object o) {
1500     if (!(o instanceof Map.Entry))
1501     return false;
1502     Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1503     V v = ConcurrentHashMapV8.this.get(e.getKey());
1504     return v != null && v.equals(e.getValue());
1505     }
1506     public boolean remove(Object o) {
1507     if (!(o instanceof Map.Entry))
1508     return false;
1509     Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1510     return ConcurrentHashMapV8.this.remove(e.getKey(), e.getValue());
1511     }
1512     }
1513    
1514     /* ---------------- Serialization Support -------------- */
1515    
1516     /**
1517     * Helper class used in previous version, declared for the sake of
1518     * serialization compatibility
1519     */
1520     static class Segment<K,V> extends java.util.concurrent.locks.ReentrantLock
1521     implements Serializable {
1522     private static final long serialVersionUID = 2249069246763182397L;
1523     final float loadFactor;
1524     Segment(float lf) { this.loadFactor = lf; }
1525     }
1526    
1527     /**
1528     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
1529     * stream (i.e., serializes it).
1530     * @param s the stream
1531     * @serialData
1532     * the key (Object) and value (Object)
1533     * for each key-value mapping, followed by a null pair.
1534     * The key-value mappings are emitted in no particular order.
1535     */
1536     @SuppressWarnings("unchecked")
1537     private void writeObject(java.io.ObjectOutputStream s)
1538     throws java.io.IOException {
1539     if (segments == null) { // for serialization compatibility
1540     segments = (Segment<K,V>[])
1541     new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1542     for (int i = 0; i < segments.length; ++i)
1543     segments[i] = new Segment<K,V>(loadFactor);
1544     }
1545     s.defaultWriteObject();
1546     new HashIterator().writeEntries(s);
1547     s.writeObject(null);
1548     s.writeObject(null);
1549     segments = null; // throw away
1550     }
1551    
1552     /**
1553 jsr166 1.9 * Reconstitutes the instance from a stream (that is, deserializes it).
1554 dl 1.1 * @param s the stream
1555     */
1556     @SuppressWarnings("unchecked")
1557     private void readObject(java.io.ObjectInputStream s)
1558     throws java.io.IOException, ClassNotFoundException {
1559     s.defaultReadObject();
1560     // find load factor in a segment, if one exists
1561     if (segments != null && segments.length != 0)
1562     this.loadFactor = segments[0].loadFactor;
1563     else
1564     this.loadFactor = DEFAULT_LOAD_FACTOR;
1565     this.initCap = DEFAULT_CAPACITY;
1566     LongAdder ct = new LongAdder(); // force final field write
1567     UNSAFE.putObjectVolatile(this, counterOffset, ct);
1568     this.segments = null; // unneeded
1569    
1570     // Read the keys and values, and put the mappings in the table
1571     for (;;) {
1572     K key = (K) s.readObject();
1573     V value = (V) s.readObject();
1574     if (key == null)
1575     break;
1576     put(key, value);
1577     }
1578     }
1579    
1580     // Unsafe mechanics
1581     private static final sun.misc.Unsafe UNSAFE;
1582     private static final long counterOffset;
1583     private static final long resizingOffset;
1584     private static final long ABASE;
1585     private static final int ASHIFT;
1586    
1587     static {
1588     int ss;
1589     try {
1590     UNSAFE = getUnsafe();
1591     Class<?> k = ConcurrentHashMapV8.class;
1592     counterOffset = UNSAFE.objectFieldOffset
1593     (k.getDeclaredField("counter"));
1594     resizingOffset = UNSAFE.objectFieldOffset
1595     (k.getDeclaredField("resizing"));
1596     Class<?> sc = Node[].class;
1597     ABASE = UNSAFE.arrayBaseOffset(sc);
1598     ss = UNSAFE.arrayIndexScale(sc);
1599     } catch (Exception e) {
1600     throw new Error(e);
1601     }
1602     if ((ss & (ss-1)) != 0)
1603     throw new Error("data type scale not a power of two");
1604     ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
1605     }
1606    
1607     /**
1608     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
1609     * Replace with a simple call to Unsafe.getUnsafe when integrating
1610     * into a jdk.
1611     *
1612     * @return a sun.misc.Unsafe
1613     */
1614     private static sun.misc.Unsafe getUnsafe() {
1615     try {
1616     return sun.misc.Unsafe.getUnsafe();
1617     } catch (SecurityException se) {
1618     try {
1619     return java.security.AccessController.doPrivileged
1620     (new java.security
1621     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1622     public sun.misc.Unsafe run() throws Exception {
1623     java.lang.reflect.Field f = sun.misc
1624     .Unsafe.class.getDeclaredField("theUnsafe");
1625     f.setAccessible(true);
1626     return (sun.misc.Unsafe) f.get(null);
1627     }});
1628     } catch (java.security.PrivilegedActionException e) {
1629     throw new RuntimeException("Could not initialize intrinsics",
1630     e.getCause());
1631     }
1632     }
1633     }
1634    
1635     }