ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ConcurrentHashMapV8.java
Revision: 1.40
Committed: Sat Jun 9 17:02:07 2012 UTC (11 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.39: +1 -1 lines
Log Message:
typo

File Contents

# Content
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 // Snapshot Tue Jun 5 14:56:09 2012 Doug Lea (dl at altair)
8
9 package jsr166e;
10 import jsr166e.LongAdder;
11 import java.util.Arrays;
12 import java.util.Map;
13 import java.util.Set;
14 import java.util.Collection;
15 import java.util.AbstractMap;
16 import java.util.AbstractSet;
17 import java.util.AbstractCollection;
18 import java.util.Hashtable;
19 import java.util.HashMap;
20 import java.util.Iterator;
21 import java.util.Enumeration;
22 import java.util.ConcurrentModificationException;
23 import java.util.NoSuchElementException;
24 import java.util.concurrent.ConcurrentMap;
25 import java.util.concurrent.ThreadLocalRandom;
26 import java.util.concurrent.locks.LockSupport;
27 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
28 import java.io.Serializable;
29
30 /**
31 * A hash table supporting full concurrency of retrievals and
32 * high expected concurrency for updates. This class obeys the
33 * same functional specification as {@link java.util.Hashtable}, and
34 * includes versions of methods corresponding to each method of
35 * {@code Hashtable}. However, even though all operations are
36 * thread-safe, retrieval operations do <em>not</em> entail locking,
37 * and there is <em>not</em> any support for locking the entire table
38 * in a way that prevents all access. This class is fully
39 * interoperable with {@code Hashtable} in programs that rely on its
40 * thread safety but not on its synchronization details.
41 *
42 * <p> Retrieval operations (including {@code get}) generally do not
43 * block, so may overlap with update operations (including {@code put}
44 * and {@code remove}). Retrievals reflect the results of the most
45 * recently <em>completed</em> update operations holding upon their
46 * onset. For aggregate operations such as {@code putAll} and {@code
47 * clear}, concurrent retrievals may reflect insertion or removal of
48 * only some entries. Similarly, Iterators and Enumerations return
49 * elements reflecting the state of the hash table at some point at or
50 * since the creation of the iterator/enumeration. They do
51 * <em>not</em> throw {@link ConcurrentModificationException}.
52 * However, iterators are designed to be used by only one thread at a
53 * time. Bear in mind that the results of aggregate status methods
54 * including {@code size}, {@code isEmpty}, and {@code containsValue}
55 * are typically useful only when a map is not undergoing concurrent
56 * updates in other threads. Otherwise the results of these methods
57 * reflect transient states that may be adequate for monitoring
58 * or estimation purposes, but not for program control.
59 *
60 * <p> The table is dynamically expanded when there are too many
61 * collisions (i.e., keys that have distinct hash codes but fall into
62 * the same slot modulo the table size), with the expected average
63 * effect of maintaining roughly two bins per mapping (corresponding
64 * to a 0.75 load factor threshold for resizing). There may be much
65 * variance around this average as mappings are added and removed, but
66 * overall, this maintains a commonly accepted time/space tradeoff for
67 * hash tables. However, resizing this or any other kind of hash
68 * table may be a relatively slow operation. When possible, it is a
69 * good idea to provide a size estimate as an optional {@code
70 * initialCapacity} constructor argument. An additional optional
71 * {@code loadFactor} constructor argument provides a further means of
72 * customizing initial table capacity by specifying the table density
73 * to be used in calculating the amount of space to allocate for the
74 * given number of elements. Also, for compatibility with previous
75 * versions of this class, constructors may optionally specify an
76 * expected {@code concurrencyLevel} as an additional hint for
77 * internal sizing. Note that using many keys with exactly the same
78 * {@code hashCode()} is a sure way to slow down performance of any
79 * hash table.
80 *
81 * <p>This class and its views and iterators implement all of the
82 * <em>optional</em> methods of the {@link Map} and {@link Iterator}
83 * interfaces.
84 *
85 * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
86 * does <em>not</em> allow {@code null} to be used as a key or value.
87 *
88 * <p>This class is a member of the
89 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
90 * Java Collections Framework</a>.
91 *
92 * <p><em>jsr166e note: This class is a candidate replacement for
93 * java.util.concurrent.ConcurrentHashMap.<em>
94 *
95 * @since 1.5
96 * @author Doug Lea
97 * @param <K> the type of keys maintained by this map
98 * @param <V> the type of mapped values
99 */
100 public class ConcurrentHashMapV8<K, V>
101 implements ConcurrentMap<K, V>, Serializable {
102 private static final long serialVersionUID = 7249069246763182397L;
103
104 /**
105 * A function computing a mapping from the given key to a value.
106 * This is a place-holder for an upcoming JDK8 interface.
107 */
108 public static interface MappingFunction<K, V> {
109 /**
110 * Returns a non-null value for the given key.
111 *
112 * @param key the (non-null) key
113 * @return a non-null value
114 */
115 V map(K key);
116 }
117
118 /**
119 * A function computing a new mapping given a key and its current
120 * mapped value (or {@code null} if there is no current
121 * mapping). This is a place-holder for an upcoming JDK8
122 * interface.
123 */
124 public static interface RemappingFunction<K, V> {
125 /**
126 * Returns a new value given a key and its current value.
127 *
128 * @param key the (non-null) key
129 * @param value the current value, or null if there is no mapping
130 * @return a non-null value
131 */
132 V remap(K key, V value);
133 }
134
135 /*
136 * Overview:
137 *
138 * The primary design goal of this hash table is to maintain
139 * concurrent readability (typically method get(), but also
140 * iterators and related methods) while minimizing update
141 * contention. Secondary goals are to keep space consumption about
142 * the same or better than java.util.HashMap, and to support high
143 * initial insertion rates on an empty table by many threads.
144 *
145 * Each key-value mapping is held in a Node. Because Node fields
146 * can contain special values, they are defined using plain Object
147 * types. Similarly in turn, all internal methods that use them
148 * work off Object types. And similarly, so do the internal
149 * methods of auxiliary iterator and view classes. All public
150 * generic typed methods relay in/out of these internal methods,
151 * supplying null-checks and casts as needed. This also allows
152 * many of the public methods to be factored into a smaller number
153 * of internal methods (although sadly not so for the five
154 * variants of put-related operations). The validation-based
155 * approach explained below leads to a lot of code sprawl because
156 * retry-control precludes factoring into smaller methods.
157 *
158 * The table is lazily initialized to a power-of-two size upon the
159 * first insertion. Each bin in the table normally contains a
160 * list of Nodes (most often, the list has only zero or one Node).
161 * Table accesses require volatile/atomic reads, writes, and
162 * CASes. Because there is no other way to arrange this without
163 * adding further indirections, we use intrinsics
164 * (sun.misc.Unsafe) operations. The lists of nodes within bins
165 * are always accurately traversable under volatile reads, so long
166 * as lookups check hash code and non-nullness of value before
167 * checking key equality.
168 *
169 * We use the top two bits of Node hash fields for control
170 * purposes -- they are available anyway because of addressing
171 * constraints. As explained further below, these top bits are
172 * used as follows:
173 * 00 - Normal
174 * 01 - Locked
175 * 11 - Locked and may have a thread waiting for lock
176 * 10 - Node is a forwarding node
177 *
178 * The lower 30 bits of each Node's hash field contain a
179 * transformation of the key's hash code, except for forwarding
180 * nodes, for which the lower bits are zero (and so always have
181 * hash field == MOVED).
182 *
183 * Insertion (via put or its variants) of the first node in an
184 * empty bin is performed by just CASing it to the bin. This is
185 * by far the most common case for put operations under most
186 * key/hash distributions. Other update operations (insert,
187 * delete, and replace) require locks. We do not want to waste
188 * the space required to associate a distinct lock object with
189 * each bin, so instead use the first node of a bin list itself as
190 * a lock. Blocking support for these locks relies on the builtin
191 * "synchronized" monitors. However, we also need a tryLock
192 * construction, so we overlay these by using bits of the Node
193 * hash field for lock control (see above), and so normally use
194 * builtin monitors only for blocking and signalling using
195 * wait/notifyAll constructions. See Node.tryAwaitLock.
196 *
197 * Using the first node of a list as a lock does not by itself
198 * suffice though: When a node is locked, any update must first
199 * validate that it is still the first node after locking it, and
200 * retry if not. Because new nodes are always appended to lists,
201 * once a node is first in a bin, it remains first until deleted
202 * or the bin becomes invalidated (upon resizing). However,
203 * operations that only conditionally update may inspect nodes
204 * until the point of update. This is a converse of sorts to the
205 * lazy locking technique described by Herlihy & Shavit.
206 *
207 * The main disadvantage of per-bin locks is that other update
208 * operations on other nodes in a bin list protected by the same
209 * lock can stall, for example when user equals() or mapping
210 * functions take a long time. However, statistically, under
211 * random hash codes, this is not a common problem. Ideally, the
212 * frequency of nodes in bins follows a Poisson distribution
213 * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
214 * parameter of about 0.5 on average, given the resizing threshold
215 * of 0.75, although with a large variance because of resizing
216 * granularity. Ignoring variance, the expected occurrences of
217 * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The
218 * first values are:
219 *
220 * 0: 0.60653066
221 * 1: 0.30326533
222 * 2: 0.07581633
223 * 3: 0.01263606
224 * 4: 0.00157952
225 * 5: 0.00015795
226 * 6: 0.00001316
227 * 7: 0.00000094
228 * 8: 0.00000006
229 * more: less than 1 in ten million
230 *
231 * Lock contention probability for two threads accessing distinct
232 * elements is roughly 1 / (8 * #elements) under random hashes.
233 *
234 * Actual hash code distributions encountered in practice
235 * sometimes deviate significantly from uniform randomness. This
236 * includes the case when N > (1<<30), so some keys MUST collide.
237 * Similarly for dumb or hostile usages in which multiple keys are
238 * designed to have identical hash codes. Also, although we guard
239 * against the worst effects of this (see method spread), sets of
240 * hashes may differ only in bits that do not impact their bin
241 * index for a given power-of-two mask. So we use a secondary
242 * strategy that applies when the number of nodes in a bin exceeds
243 * a threshold, and at least one of the keys implements
244 * Comparable. These TreeBins use a balanced tree to hold nodes
245 * (a specialized form of red-black trees), bounding search time
246 * to O(log N). Each search step in a TreeBin is around twice as
247 * slow as in a regular list, but given that N cannot exceed
248 * (1<<64) (before running out of addresses) this bounds search
249 * steps, lock hold times, etc, to reasonable constants (roughly
250 * 100 nodes inspected per operation worst case) so long as keys
251 * are Comparable (which is very common -- String, Long, etc).
252 * TreeBin nodes (TreeNodes) also maintain the same "next"
253 * traversal pointers as regular nodes, so can be traversed in
254 * iterators in the same way.
255 *
256 * The table is resized when occupancy exceeds a percentage
257 * threshold (nominally, 0.75, but see below). Only a single
258 * thread performs the resize (using field "sizeCtl", to arrange
259 * exclusion), but the table otherwise remains usable for reads
260 * and updates. Resizing proceeds by transferring bins, one by
261 * one, from the table to the next table. Because we are using
262 * power-of-two expansion, the elements from each bin must either
263 * stay at same index, or move with a power of two offset. We
264 * eliminate unnecessary node creation by catching cases where old
265 * nodes can be reused because their next fields won't change. On
266 * average, only about one-sixth of them need cloning when a table
267 * doubles. The nodes they replace will be garbage collectable as
268 * soon as they are no longer referenced by any reader thread that
269 * may be in the midst of concurrently traversing table. Upon
270 * transfer, the old table bin contains only a special forwarding
271 * node (with hash field "MOVED") that contains the next table as
272 * its key. On encountering a forwarding node, access and update
273 * operations restart, using the new table.
274 *
275 * Each bin transfer requires its bin lock. However, unlike other
276 * cases, a transfer can skip a bin if it fails to acquire its
277 * lock, and revisit it later (unless it is a TreeBin). Method
278 * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
279 * have been skipped because of failure to acquire a lock, and
280 * blocks only if none are available (i.e., only very rarely).
281 * The transfer operation must also ensure that all accessible
282 * bins in both the old and new table are usable by any traversal.
283 * When there are no lock acquisition failures, this is arranged
284 * simply by proceeding from the last bin (table.length - 1) up
285 * towards the first. Upon seeing a forwarding node, traversals
286 * (see class InternalIterator) arrange to move to the new table
287 * without revisiting nodes. However, when any node is skipped
288 * during a transfer, all earlier table bins may have become
289 * visible, so are initialized with a reverse-forwarding node back
290 * to the old table until the new ones are established. (This
291 * sometimes requires transiently locking a forwarding node, which
292 * is possible under the above encoding.) These more expensive
293 * mechanics trigger only when necessary.
294 *
295 * The traversal scheme also applies to partial traversals of
296 * ranges of bins (via an alternate InternalIterator constructor)
297 * to support partitioned aggregate operations (that are not
298 * otherwise implemented yet). Also, read-only operations give up
299 * if ever forwarded to a null table, which provides support for
300 * shutdown-style clearing, which is also not currently
301 * implemented.
302 *
303 * Lazy table initialization minimizes footprint until first use,
304 * and also avoids resizings when the first operation is from a
305 * putAll, constructor with map argument, or deserialization.
306 * These cases attempt to override the initial capacity settings,
307 * but harmlessly fail to take effect in cases of races.
308 *
309 * The element count is maintained using a LongAdder, which avoids
310 * contention on updates but can encounter cache thrashing if read
311 * too frequently during concurrent access. To avoid reading so
312 * often, resizing is attempted either when a bin lock is
313 * contended, or upon adding to a bin already holding two or more
314 * nodes (checked before adding in the xIfAbsent methods, after
315 * adding in others). Under uniform hash distributions, the
316 * probability of this occurring at threshold is around 13%,
317 * meaning that only about 1 in 8 puts check threshold (and after
318 * resizing, many fewer do so). But this approximation has high
319 * variance for small table sizes, so we check on any collision
320 * for sizes <= 64. The bulk putAll operation further reduces
321 * contention by only committing count updates upon these size
322 * checks.
323 *
324 * Maintaining API and serialization compatibility with previous
325 * versions of this class introduces several oddities. Mainly: We
326 * leave untouched but unused constructor arguments refering to
327 * concurrencyLevel. We accept a loadFactor constructor argument,
328 * but apply it only to initial table capacity (which is the only
329 * time that we can guarantee to honor it.) We also declare an
330 * unused "Segment" class that is instantiated in minimal form
331 * only when serializing.
332 */
333
334 /* ---------------- Constants -------------- */
335
336 /**
337 * The largest possible table capacity. This value must be
338 * exactly 1<<30 to stay within Java array allocation and indexing
339 * bounds for power of two table sizes, and is further required
340 * because the top two bits of 32bit hash fields are used for
341 * control purposes.
342 */
343 private static final int MAXIMUM_CAPACITY = 1 << 30;
344
345 /**
346 * The default initial table capacity. Must be a power of 2
347 * (i.e., at least 1) and at most MAXIMUM_CAPACITY.
348 */
349 private static final int DEFAULT_CAPACITY = 16;
350
351 /**
352 * The largest possible (non-power of two) array size.
353 * Needed by toArray and related methods.
354 */
355 static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
356
357 /**
358 * The default concurrency level for this table. Unused but
359 * defined for compatibility with previous versions of this class.
360 */
361 private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
362
363 /**
364 * The load factor for this table. Overrides of this value in
365 * constructors affect only the initial table capacity. The
366 * actual floating point value isn't normally used -- it is
367 * simpler to use expressions such as {@code n - (n >>> 2)} for
368 * the associated resizing threshold.
369 */
370 private static final float LOAD_FACTOR = 0.75f;
371
372 /**
373 * The buffer size for skipped bins during transfers. The
374 * value is arbitrary but should be large enough to avoid
375 * most locking stalls during resizes.
376 */
377 private static final int TRANSFER_BUFFER_SIZE = 32;
378
379 /**
380 * The bin count threshold for using a tree rather than list for a
381 * bin. The value reflects the approximate break-even point for
382 * using tree-based operations.
383 */
384 private static final int TREE_THRESHOLD = 8;
385
386 /*
387 * Encodings for special uses of Node hash fields. See above for
388 * explanation.
389 */
390 static final int MOVED = 0x80000000; // hash field for forwarding nodes
391 static final int LOCKED = 0x40000000; // set/tested only as a bit
392 static final int WAITING = 0xc0000000; // both bits set/tested together
393 static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
394
395 /* ---------------- Fields -------------- */
396
397 /**
398 * The array of bins. Lazily initialized upon first insertion.
399 * Size is always a power of two. Accessed directly by iterators.
400 */
401 transient volatile Node[] table;
402
403 /**
404 * The counter maintaining number of elements.
405 */
406 private transient final LongAdder counter;
407
408 /**
409 * Table initialization and resizing control. When negative, the
410 * table is being initialized or resized. Otherwise, when table is
411 * null, holds the initial table size to use upon creation, or 0
412 * for default. After initialization, holds the next element count
413 * value upon which to resize the table.
414 */
415 private transient volatile int sizeCtl;
416
417 // views
418 private transient KeySet<K,V> keySet;
419 private transient Values<K,V> values;
420 private transient EntrySet<K,V> entrySet;
421
422 /** For serialization compatibility. Null unless serialized; see below */
423 private Segment<K,V>[] segments;
424
425 /* ---------------- Table element access -------------- */
426
427 /*
428 * Volatile access methods are used for table elements as well as
429 * elements of in-progress next table while resizing. Uses are
430 * null checked by callers, and implicitly bounds-checked, relying
431 * on the invariants that tab arrays have non-zero size, and all
432 * indices are masked with (tab.length - 1) which is never
433 * negative and always less than length. Note that, to be correct
434 * wrt arbitrary concurrency errors by users, bounds checks must
435 * operate on local variables, which accounts for some odd-looking
436 * inline assignments below.
437 */
438
439 static final Node tabAt(Node[] tab, int i) { // used by InternalIterator
440 return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
441 }
442
443 private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
444 return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
445 }
446
447 private static final void setTabAt(Node[] tab, int i, Node v) {
448 UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
449 }
450
451 /* ---------------- Nodes -------------- */
452
453 /**
454 * Key-value entry. Note that this is never exported out as a
455 * user-visible Map.Entry (see WriteThroughEntry and SnapshotEntry
456 * below). Nodes with a hash field of MOVED are special, and do
457 * not contain user keys or values. Otherwise, keys are never
458 * null, and null val fields indicate that a node is in the
459 * process of being deleted or created. For purposes of read-only
460 * access, a key may be read before a val, but can only be used
461 * after checking val to be non-null.
462 */
463 static class Node {
464 volatile int hash;
465 final Object key;
466 volatile Object val;
467 volatile Node next;
468
469 Node(int hash, Object key, Object val, Node next) {
470 this.hash = hash;
471 this.key = key;
472 this.val = val;
473 this.next = next;
474 }
475
476 /** CompareAndSet the hash field */
477 final boolean casHash(int cmp, int val) {
478 return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
479 }
480
481 /** The number of spins before blocking for a lock */
482 static final int MAX_SPINS =
483 Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
484
485 /**
486 * Spins a while if LOCKED bit set and this node is the first
487 * of its bin, and then sets WAITING bits on hash field and
488 * blocks (once) if they are still set. It is OK for this
489 * method to return even if lock is not available upon exit,
490 * which enables these simple single-wait mechanics.
491 *
492 * The corresponding signalling operation is performed within
493 * callers: Upon detecting that WAITING has been set when
494 * unlocking lock (via a failed CAS from non-waiting LOCKED
495 * state), unlockers acquire the sync lock and perform a
496 * notifyAll.
497 */
498 final void tryAwaitLock(Node[] tab, int i) {
499 if (tab != null && i >= 0 && i < tab.length) { // bounds check
500 int r = ThreadLocalRandom.current().nextInt(); // randomize spins
501 int spins = MAX_SPINS, h;
502 while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
503 if (spins >= 0) {
504 r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
505 if (r >= 0 && --spins == 0)
506 Thread.yield(); // yield before block
507 }
508 else if (casHash(h, h | WAITING)) {
509 synchronized (this) {
510 if (tabAt(tab, i) == this &&
511 (hash & WAITING) == WAITING) {
512 try {
513 wait();
514 } catch (InterruptedException ie) {
515 Thread.currentThread().interrupt();
516 }
517 }
518 else
519 notifyAll(); // possibly won race vs signaller
520 }
521 break;
522 }
523 }
524 }
525 }
526
527 // Unsafe mechanics for casHash
528 private static final sun.misc.Unsafe UNSAFE;
529 private static final long hashOffset;
530
531 static {
532 try {
533 UNSAFE = getUnsafe();
534 Class<?> k = Node.class;
535 hashOffset = UNSAFE.objectFieldOffset
536 (k.getDeclaredField("hash"));
537 } catch (Exception e) {
538 throw new Error(e);
539 }
540 }
541 }
542
543 /* ---------------- TreeBins -------------- */
544
545 /**
546 * Nodes for use in TreeBins
547 */
548 static final class TreeNode extends Node {
549 TreeNode parent; // red-black tree links
550 TreeNode left;
551 TreeNode right;
552 TreeNode prev; // needed to unlink next upon deletion
553 boolean red;
554
555 TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
556 super(hash, key, val, next);
557 this.parent = parent;
558 }
559 }
560
561 /**
562 * A specialized form of red-black tree for use in bins
563 * whose size exceeds a threshold.
564 *
565 * TreeBins use a special form of comparison for search and
566 * related operations (which is the main reason we cannot use
567 * existing collections such as TreeMaps). TreeBins contain
568 * Comparable elements, but may contain others, as well as
569 * elements that are Comparable but not necessarily Comparable<T>
570 * for the same T, so we cannot invoke compareTo among them. To
571 * handle this, the tree is ordered primarily by hash value, then
572 * by getClass().getName() order, and then by Comparator order
573 * among elements of the same class. On lookup at a node, if
574 * non-Comparable, both left and right children may need to be
575 * searched in the case of tied hash values. (This corresponds to
576 * the full list search that would be necessary if all elements
577 * were non-Comparable and had tied hashes.)
578 *
579 * TreeBins also maintain a separate locking discipline than
580 * regular bins. Because they are forwarded via special MOVED
581 * nodes at bin heads (which can never change once established),
582 * we cannot use use those nodes as locks. Instead, TreeBin
583 * extends AbstractQueuedSynchronizer to support a simple form of
584 * read-write lock. For update operations and table validation,
585 * the exclusive form of lock behaves in the same way as bin-head
586 * locks. However, lookups use shared read-lock mechanics to allow
587 * multiple readers in the absence of writers. Additionally,
588 * these lookups do not ever block: While the lock is not
589 * available, they proceed along the slow traversal path (via
590 * next-pointers) until the lock becomes available or the list is
591 * exhausted, whichever comes first. (These cases are not fast,
592 * but maximize aggregate expected throughput.) The AQS mechanics
593 * for doing this are straightforward. The lock state is held as
594 * AQS getState(). Read counts are negative; the write count (1)
595 * is positive. There are no signalling preferences among readers
596 * and writers. Since we don't need to export full Lock API, we
597 * just override the minimal AQS methods and use them directly.
598 */
599 static final class TreeBin extends AbstractQueuedSynchronizer {
600 private static final long serialVersionUID = 2249069246763182397L;
601 TreeNode root; // root of tree
602 TreeNode first; // head of next-pointer list
603
604 /* AQS overrides */
605 public final boolean isHeldExclusively() { return getState() > 0; }
606 public final boolean tryAcquire(int ignore) {
607 if (compareAndSetState(0, 1)) {
608 setExclusiveOwnerThread(Thread.currentThread());
609 return true;
610 }
611 return false;
612 }
613 public final boolean tryRelease(int ignore) {
614 setExclusiveOwnerThread(null);
615 setState(0);
616 return true;
617 }
618 public final int tryAcquireShared(int ignore) {
619 for (int c;;) {
620 if ((c = getState()) > 0)
621 return -1;
622 if (compareAndSetState(c, c -1))
623 return 1;
624 }
625 }
626 public final boolean tryReleaseShared(int ignore) {
627 int c;
628 do {} while (!compareAndSetState(c = getState(), c + 1));
629 return c == -1;
630 }
631
632 /**
633 * Return the TreeNode (or null if not found) for the given key
634 * starting at given root.
635 */
636 @SuppressWarnings("unchecked") // suppress Comparable cast warning
637 final TreeNode getTreeNode(int h, Object k, TreeNode p) {
638 Class<?> c = k.getClass();
639 while (p != null) {
640 int dir, ph; Object pk; Class<?> pc; TreeNode r;
641 if (h < (ph = p.hash))
642 dir = -1;
643 else if (h > ph)
644 dir = 1;
645 else if ((pk = p.key) == k || k.equals(pk))
646 return p;
647 else if (c != (pc = pk.getClass()))
648 dir = c.getName().compareTo(pc.getName());
649 else if (k instanceof Comparable)
650 dir = ((Comparable)k).compareTo((Comparable)pk);
651 else
652 dir = 0;
653 TreeNode pr = p.right;
654 if (dir > 0)
655 p = pr;
656 else if (dir == 0 && pr != null && h >= pr.hash &&
657 (r = getTreeNode(h, k, pr)) != null)
658 return r;
659 else
660 p = p.left;
661 }
662 return null;
663 }
664
665 /**
666 * Wrapper for getTreeNode used by CHM.get. Tries to obtain
667 * read-lock to call getTreeNode, but during failure to get
668 * lock, searches along next links.
669 */
670 final Object getValue(int h, Object k) {
671 Node r = null;
672 int c = getState(); // Must read lock state first
673 for (Node e = first; e != null; e = e.next) {
674 if (c <= 0 && compareAndSetState(c, c - 1)) {
675 try {
676 r = getTreeNode(h, k, root);
677 } finally {
678 releaseShared(0);
679 }
680 break;
681 }
682 else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
683 r = e;
684 break;
685 }
686 else
687 c = getState();
688 }
689 return r == null ? null : r.val;
690 }
691
692 /**
693 * Find or add a node
694 * @return null if added
695 */
696 @SuppressWarnings("unchecked") // suppress Comparable cast warning
697 final TreeNode putTreeNode(int h, Object k, Object v) {
698 Class<?> c = k.getClass();
699 TreeNode p = root;
700 int dir = 0;
701 if (p != null) {
702 for (;;) {
703 int ph; Object pk; Class<?> pc; TreeNode r;
704 if (h < (ph = p.hash))
705 dir = -1;
706 else if (h > ph)
707 dir = 1;
708 else if ((pk = p.key) == k || k.equals(pk))
709 return p;
710 else if (c != (pc = (pk = p.key).getClass()))
711 dir = c.getName().compareTo(pc.getName());
712 else if (k instanceof Comparable)
713 dir = ((Comparable)k).compareTo((Comparable)pk);
714 else
715 dir = 0;
716 TreeNode pr = p.right, pl;
717 if (dir > 0) {
718 if (pr == null)
719 break;
720 p = pr;
721 }
722 else if (dir == 0 && pr != null && h >= pr.hash &&
723 (r = getTreeNode(h, k, pr)) != null)
724 return r;
725 else if ((pl = p.left) == null)
726 break;
727 else
728 p = pl;
729 }
730 }
731 TreeNode f = first;
732 TreeNode r = first = new TreeNode(h, k, v, f, p);
733 if (p == null)
734 root = r;
735 else {
736 if (dir <= 0)
737 p.left = r;
738 else
739 p.right = r;
740 if (f != null)
741 f.prev = r;
742 fixAfterInsertion(r);
743 }
744 return null;
745 }
746
747 /**
748 * Removes the given node, that must be present before this
749 * call. This is messier than typical red-black deletion code
750 * because we cannot swap the contents of an interior node
751 * with a leaf successor that is pinned by "next" pointers
752 * that are accessible independently of lock. So instead we
753 * swap the tree linkages.
754 */
755 final void deleteTreeNode(TreeNode p) {
756 TreeNode next = (TreeNode)p.next; // unlink traversal pointers
757 TreeNode pred = p.prev;
758 if (pred == null)
759 first = next;
760 else
761 pred.next = next;
762 if (next != null)
763 next.prev = pred;
764 TreeNode replacement;
765 TreeNode pl = p.left;
766 TreeNode pr = p.right;
767 if (pl != null && pr != null) {
768 TreeNode s = pr;
769 while (s.left != null) // find successor
770 s = s.left;
771 boolean c = s.red; s.red = p.red; p.red = c; // swap colors
772 TreeNode sr = s.right;
773 TreeNode pp = p.parent;
774 if (s == pr) { // p was s's direct parent
775 p.parent = s;
776 s.right = p;
777 }
778 else {
779 TreeNode sp = s.parent;
780 if ((p.parent = sp) != null) {
781 if (s == sp.left)
782 sp.left = p;
783 else
784 sp.right = p;
785 }
786 if ((s.right = pr) != null)
787 pr.parent = s;
788 }
789 p.left = null;
790 if ((p.right = sr) != null)
791 sr.parent = p;
792 if ((s.left = pl) != null)
793 pl.parent = s;
794 if ((s.parent = pp) == null)
795 root = s;
796 else if (p == pp.left)
797 pp.left = s;
798 else
799 pp.right = s;
800 replacement = sr;
801 }
802 else
803 replacement = (pl != null) ? pl : pr;
804 TreeNode pp = p.parent;
805 if (replacement == null) {
806 if (pp == null) {
807 root = null;
808 return;
809 }
810 replacement = p;
811 }
812 else {
813 replacement.parent = pp;
814 if (pp == null)
815 root = replacement;
816 else if (p == pp.left)
817 pp.left = replacement;
818 else
819 pp.right = replacement;
820 p.left = p.right = p.parent = null;
821 }
822 if (!p.red)
823 fixAfterDeletion(replacement);
824 if (p == replacement && (pp = p.parent) != null) {
825 if (p == pp.left) // detach pointers
826 pp.left = null;
827 else if (p == pp.right)
828 pp.right = null;
829 p.parent = null;
830 }
831 }
832
833 // CLR code updated from pre-jdk-collections version at
834 // http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java
835
836 /** From CLR */
837 private void rotateLeft(TreeNode p) {
838 if (p != null) {
839 TreeNode r = p.right, pp, rl;
840 if ((rl = p.right = r.left) != null)
841 rl.parent = p;
842 if ((pp = r.parent = p.parent) == null)
843 root = r;
844 else if (pp.left == p)
845 pp.left = r;
846 else
847 pp.right = r;
848 r.left = p;
849 p.parent = r;
850 }
851 }
852
853 /** From CLR */
854 private void rotateRight(TreeNode p) {
855 if (p != null) {
856 TreeNode l = p.left, pp, lr;
857 if ((lr = p.left = l.right) != null)
858 lr.parent = p;
859 if ((pp = l.parent = p.parent) == null)
860 root = l;
861 else if (pp.right == p)
862 pp.right = l;
863 else
864 pp.left = l;
865 l.right = p;
866 p.parent = l;
867 }
868 }
869
870 /** From CLR */
871 private void fixAfterInsertion(TreeNode x) {
872 x.red = true;
873 TreeNode xp, xpp;
874 while (x != null && (xp = x.parent) != null && xp.red &&
875 (xpp = xp.parent) != null) {
876 TreeNode xppl = xpp.left;
877 if (xp == xppl) {
878 TreeNode y = xpp.right;
879 if (y != null && y.red) {
880 y.red = false;
881 xp.red = false;
882 xpp.red = true;
883 x = xpp;
884 }
885 else {
886 if (x == xp.right) {
887 x = xp;
888 rotateLeft(x);
889 xpp = (xp = x.parent) == null ? null : xp.parent;
890 }
891 if (xp != null) {
892 xp.red = false;
893 if (xpp != null) {
894 xpp.red = true;
895 rotateRight(xpp);
896 }
897 }
898 }
899 }
900 else {
901 TreeNode y = xppl;
902 if (y != null && y.red) {
903 y.red = false;
904 xp.red = false;
905 xpp.red = true;
906 x = xpp;
907 }
908 else {
909 if (x == xp.left) {
910 x = xp;
911 rotateRight(x);
912 xpp = (xp = x.parent) == null ? null : xp.parent;
913 }
914 if (xp != null) {
915 xp.red = false;
916 if (xpp != null) {
917 xpp.red = true;
918 rotateLeft(xpp);
919 }
920 }
921 }
922 }
923 }
924 TreeNode r = root;
925 if (r != null && r.red)
926 r.red = false;
927 }
928
929 /** From CLR */
930 private void fixAfterDeletion(TreeNode x) {
931 while (x != null) {
932 TreeNode xp, xpl;
933 if (x.red || (xp = x.parent) == null) {
934 x.red = false;
935 break;
936 }
937 if (x == (xpl = xp.left)) {
938 TreeNode sib = xp.right;
939 if (sib != null && sib.red) {
940 sib.red = false;
941 xp.red = true;
942 rotateLeft(xp);
943 sib = (xp = x.parent) == null ? null : xp.right;
944 }
945 if (sib == null)
946 x = xp;
947 else {
948 TreeNode sl = sib.left, sr = sib.right;
949 if ((sr == null || !sr.red) &&
950 (sl == null || !sl.red)) {
951 sib.red = true;
952 x = xp;
953 }
954 else {
955 if (sr == null || !sr.red) {
956 if (sl != null)
957 sl.red = false;
958 sib.red = true;
959 rotateRight(sib);
960 sib = (xp = x.parent) == null ? null : xp.right;
961 }
962 if (sib != null) {
963 sib.red = (xp == null) ? false : xp.red;
964 if ((sr = sib.right) != null)
965 sr.red = false;
966 }
967 if (xp != null) {
968 xp.red = false;
969 rotateLeft(xp);
970 }
971 x = root;
972 }
973 }
974 }
975 else { // symmetric
976 TreeNode sib = xpl;
977 if (sib != null && sib.red) {
978 sib.red = false;
979 xp.red = true;
980 rotateRight(xp);
981 sib = (xp = x.parent) == null ? null : xp.left;
982 }
983 if (sib == null)
984 x = xp;
985 else {
986 TreeNode sl = sib.left, sr = sib.right;
987 if ((sl == null || !sl.red) &&
988 (sr == null || !sr.red)) {
989 sib.red = true;
990 x = xp;
991 }
992 else {
993 if (sl == null || !sl.red) {
994 if (sr != null)
995 sr.red = false;
996 sib.red = true;
997 rotateLeft(sib);
998 sib = (xp = x.parent) == null ? null : xp.left;
999 }
1000 if (sib != null) {
1001 sib.red = (xp == null) ? false : xp.red;
1002 if ((sl = sib.left) != null)
1003 sl.red = false;
1004 }
1005 if (xp != null) {
1006 xp.red = false;
1007 rotateRight(xp);
1008 }
1009 x = root;
1010 }
1011 }
1012 }
1013 }
1014 }
1015 }
1016
1017 /* ---------------- Collision reduction methods -------------- */
1018
1019 /**
1020 * Spreads higher bits to lower, and also forces top 2 bits to 0.
1021 * Because the table uses power-of-two masking, sets of hashes
1022 * that vary only in bits above the current mask will always
1023 * collide. (Among known examples are sets of Float keys holding
1024 * consecutive whole numbers in small tables.) To counter this,
1025 * we apply a transform that spreads the impact of higher bits
1026 * downward. There is a tradeoff between speed, utility, and
1027 * quality of bit-spreading. Because many common sets of hashes
1028 * are already reasonably distributed across bits (so don't benefit
1029 * from spreading), and because we use trees to handle large sets
1030 * of collisions in bins, we don't need excessively high quality.
1031 */
1032 private static final int spread(int h) {
1033 h ^= (h >>> 18) ^ (h >>> 12);
1034 return (h ^ (h >>> 10)) & HASH_BITS;
1035 }
1036
1037 /**
1038 * Replaces a list bin with a tree bin. Call only when locked.
1039 * Fails to replace if the given key is non-comparable or table
1040 * is, or needs, resizing.
1041 */
1042 private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1043 if ((key instanceof Comparable) &&
1044 (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
1045 TreeBin t = new TreeBin();
1046 for (Node e = tabAt(tab, index); e != null; e = e.next)
1047 t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
1048 setTabAt(tab, index, new Node(MOVED, t, null, null));
1049 }
1050 }
1051
1052 /* ---------------- Internal access and update methods -------------- */
1053
1054 /** Implementation for get and containsKey */
1055 private final Object internalGet(Object k) {
1056 int h = spread(k.hashCode());
1057 retry: for (Node[] tab = table; tab != null;) {
1058 Node e, p; Object ek, ev; int eh; // locals to read fields once
1059 for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1060 if ((eh = e.hash) == MOVED) {
1061 if ((ek = e.key) instanceof TreeBin) // search TreeBin
1062 return ((TreeBin)ek).getValue(h, k);
1063 else { // restart with new table
1064 tab = (Node[])ek;
1065 continue retry;
1066 }
1067 }
1068 else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1069 ((ek = e.key) == k || k.equals(ek)))
1070 return ev;
1071 }
1072 break;
1073 }
1074 return null;
1075 }
1076
1077 /**
1078 * Implementation for the four public remove/replace methods:
1079 * Replaces node value with v, conditional upon match of cv if
1080 * non-null. If resulting value is null, delete.
1081 */
1082 private final Object internalReplace(Object k, Object v, Object cv) {
1083 int h = spread(k.hashCode());
1084 Object oldVal = null;
1085 for (Node[] tab = table;;) {
1086 Node f; int i, fh; Object fk;
1087 if (tab == null ||
1088 (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1089 break;
1090 else if ((fh = f.hash) == MOVED) {
1091 if ((fk = f.key) instanceof TreeBin) {
1092 TreeBin t = (TreeBin)fk;
1093 boolean validated = false;
1094 boolean deleted = false;
1095 t.acquire(0);
1096 try {
1097 if (tabAt(tab, i) == f) {
1098 validated = true;
1099 TreeNode p = t.getTreeNode(h, k, t.root);
1100 if (p != null) {
1101 Object pv = p.val;
1102 if (cv == null || cv == pv || cv.equals(pv)) {
1103 oldVal = pv;
1104 if ((p.val = v) == null) {
1105 deleted = true;
1106 t.deleteTreeNode(p);
1107 }
1108 }
1109 }
1110 }
1111 } finally {
1112 t.release(0);
1113 }
1114 if (validated) {
1115 if (deleted)
1116 counter.add(-1L);
1117 break;
1118 }
1119 }
1120 else
1121 tab = (Node[])fk;
1122 }
1123 else if ((fh & HASH_BITS) != h && f.next == null) // precheck
1124 break; // rules out possible existence
1125 else if ((fh & LOCKED) != 0) {
1126 checkForResize(); // try resizing if can't get lock
1127 f.tryAwaitLock(tab, i);
1128 }
1129 else if (f.casHash(fh, fh | LOCKED)) {
1130 boolean validated = false;
1131 boolean deleted = false;
1132 try {
1133 if (tabAt(tab, i) == f) {
1134 validated = true;
1135 for (Node e = f, pred = null;;) {
1136 Object ek, ev;
1137 if ((e.hash & HASH_BITS) == h &&
1138 ((ev = e.val) != null) &&
1139 ((ek = e.key) == k || k.equals(ek))) {
1140 if (cv == null || cv == ev || cv.equals(ev)) {
1141 oldVal = ev;
1142 if ((e.val = v) == null) {
1143 deleted = true;
1144 Node en = e.next;
1145 if (pred != null)
1146 pred.next = en;
1147 else
1148 setTabAt(tab, i, en);
1149 }
1150 }
1151 break;
1152 }
1153 pred = e;
1154 if ((e = e.next) == null)
1155 break;
1156 }
1157 }
1158 } finally {
1159 if (!f.casHash(fh | LOCKED, fh)) {
1160 f.hash = fh;
1161 synchronized (f) { f.notifyAll(); };
1162 }
1163 }
1164 if (validated) {
1165 if (deleted)
1166 counter.add(-1L);
1167 break;
1168 }
1169 }
1170 }
1171 return oldVal;
1172 }
1173
1174 /*
1175 * Internal versions of the five insertion methods, each a
1176 * little more complicated than the last. All have
1177 * the same basic structure as the first (internalPut):
1178 * 1. If table uninitialized, create
1179 * 2. If bin empty, try to CAS new node
1180 * 3. If bin stale, use new table
1181 * 4. if bin converted to TreeBin, validate and relay to TreeBin methods
1182 * 5. Lock and validate; if valid, scan and add or update
1183 *
1184 * The others interweave other checks and/or alternative actions:
1185 * * Plain put checks for and performs resize after insertion.
1186 * * putIfAbsent prescans for mapping without lock (and fails to add
1187 * if present), which also makes pre-emptive resize checks worthwhile.
1188 * * computeIfAbsent extends form used in putIfAbsent with additional
1189 * mechanics to deal with, calls, potential exceptions and null
1190 * returns from function call.
1191 * * compute uses the same function-call mechanics, but without
1192 * the prescans
1193 * * putAll attempts to pre-allocate enough table space
1194 * and more lazily performs count updates and checks.
1195 *
1196 * Someday when details settle down a bit more, it might be worth
1197 * some factoring to reduce sprawl.
1198 */
1199
1200 /** Implementation for put */
1201 private final Object internalPut(Object k, Object v) {
1202 int h = spread(k.hashCode());
1203 int count = 0;
1204 for (Node[] tab = table;;) {
1205 int i; Node f; int fh; Object fk;
1206 if (tab == null)
1207 tab = initTable();
1208 else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1209 if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1210 break; // no lock when adding to empty bin
1211 }
1212 else if ((fh = f.hash) == MOVED) {
1213 if ((fk = f.key) instanceof TreeBin) {
1214 TreeBin t = (TreeBin)fk;
1215 Object oldVal = null;
1216 t.acquire(0);
1217 try {
1218 if (tabAt(tab, i) == f) {
1219 count = 2;
1220 TreeNode p = t.putTreeNode(h, k, v);
1221 if (p != null) {
1222 oldVal = p.val;
1223 p.val = v;
1224 }
1225 }
1226 } finally {
1227 t.release(0);
1228 }
1229 if (count != 0) {
1230 if (oldVal != null)
1231 return oldVal;
1232 break;
1233 }
1234 }
1235 else
1236 tab = (Node[])fk;
1237 }
1238 else if ((fh & LOCKED) != 0) {
1239 checkForResize();
1240 f.tryAwaitLock(tab, i);
1241 }
1242 else if (f.casHash(fh, fh | LOCKED)) {
1243 Object oldVal = null;
1244 try { // needed in case equals() throws
1245 if (tabAt(tab, i) == f) {
1246 count = 1;
1247 for (Node e = f;; ++count) {
1248 Object ek, ev;
1249 if ((e.hash & HASH_BITS) == h &&
1250 (ev = e.val) != null &&
1251 ((ek = e.key) == k || k.equals(ek))) {
1252 oldVal = ev;
1253 e.val = v;
1254 break;
1255 }
1256 Node last = e;
1257 if ((e = e.next) == null) {
1258 last.next = new Node(h, k, v, null);
1259 if (count >= TREE_THRESHOLD)
1260 replaceWithTreeBin(tab, i, k);
1261 break;
1262 }
1263 }
1264 }
1265 } finally { // unlock and signal if needed
1266 if (!f.casHash(fh | LOCKED, fh)) {
1267 f.hash = fh;
1268 synchronized (f) { f.notifyAll(); };
1269 }
1270 }
1271 if (count != 0) {
1272 if (oldVal != null)
1273 return oldVal;
1274 if (tab.length <= 64)
1275 count = 2;
1276 break;
1277 }
1278 }
1279 }
1280 counter.add(1L);
1281 if (count > 1)
1282 checkForResize();
1283 return null;
1284 }
1285
1286 /** Implementation for putIfAbsent */
1287 private final Object internalPutIfAbsent(Object k, Object v) {
1288 int h = spread(k.hashCode());
1289 int count = 0;
1290 for (Node[] tab = table;;) {
1291 int i; Node f; int fh; Object fk, fv;
1292 if (tab == null)
1293 tab = initTable();
1294 else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1295 if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1296 break;
1297 }
1298 else if ((fh = f.hash) == MOVED) {
1299 if ((fk = f.key) instanceof TreeBin) {
1300 TreeBin t = (TreeBin)fk;
1301 Object oldVal = null;
1302 t.acquire(0);
1303 try {
1304 if (tabAt(tab, i) == f) {
1305 count = 2;
1306 TreeNode p = t.putTreeNode(h, k, v);
1307 if (p != null)
1308 oldVal = p.val;
1309 }
1310 } finally {
1311 t.release(0);
1312 }
1313 if (count != 0) {
1314 if (oldVal != null)
1315 return oldVal;
1316 break;
1317 }
1318 }
1319 else
1320 tab = (Node[])fk;
1321 }
1322 else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1323 ((fk = f.key) == k || k.equals(fk)))
1324 return fv;
1325 else {
1326 Node g = f.next;
1327 if (g != null) { // at least 2 nodes -- search and maybe resize
1328 for (Node e = g;;) {
1329 Object ek, ev;
1330 if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1331 ((ek = e.key) == k || k.equals(ek)))
1332 return ev;
1333 if ((e = e.next) == null) {
1334 checkForResize();
1335 break;
1336 }
1337 }
1338 }
1339 if (((fh = f.hash) & LOCKED) != 0) {
1340 checkForResize();
1341 f.tryAwaitLock(tab, i);
1342 }
1343 else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1344 Object oldVal = null;
1345 try {
1346 if (tabAt(tab, i) == f) {
1347 count = 1;
1348 for (Node e = f;; ++count) {
1349 Object ek, ev;
1350 if ((e.hash & HASH_BITS) == h &&
1351 (ev = e.val) != null &&
1352 ((ek = e.key) == k || k.equals(ek))) {
1353 oldVal = ev;
1354 break;
1355 }
1356 Node last = e;
1357 if ((e = e.next) == null) {
1358 last.next = new Node(h, k, v, null);
1359 if (count >= TREE_THRESHOLD)
1360 replaceWithTreeBin(tab, i, k);
1361 break;
1362 }
1363 }
1364 }
1365 } finally {
1366 if (!f.casHash(fh | LOCKED, fh)) {
1367 f.hash = fh;
1368 synchronized (f) { f.notifyAll(); };
1369 }
1370 }
1371 if (count != 0) {
1372 if (oldVal != null)
1373 return oldVal;
1374 if (tab.length <= 64)
1375 count = 2;
1376 break;
1377 }
1378 }
1379 }
1380 }
1381 counter.add(1L);
1382 if (count > 1)
1383 checkForResize();
1384 return null;
1385 }
1386
1387 /** Implementation for computeIfAbsent */
1388 private final Object internalComputeIfAbsent(K k,
1389 MappingFunction<? super K, ?> mf) {
1390 int h = spread(k.hashCode());
1391 Object val = null;
1392 int count = 0;
1393 for (Node[] tab = table;;) {
1394 Node f; int i, fh; Object fk, fv;
1395 if (tab == null)
1396 tab = initTable();
1397 else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1398 Node node = new Node(fh = h | LOCKED, k, null, null);
1399 if (casTabAt(tab, i, null, node)) {
1400 count = 1;
1401 try {
1402 if ((val = mf.map(k)) != null)
1403 node.val = val;
1404 } finally {
1405 if (val == null)
1406 setTabAt(tab, i, null);
1407 if (!node.casHash(fh, h)) {
1408 node.hash = h;
1409 synchronized (node) { node.notifyAll(); };
1410 }
1411 }
1412 }
1413 if (count != 0)
1414 break;
1415 }
1416 else if ((fh = f.hash) == MOVED) {
1417 if ((fk = f.key) instanceof TreeBin) {
1418 TreeBin t = (TreeBin)fk;
1419 boolean added = false;
1420 t.acquire(0);
1421 try {
1422 if (tabAt(tab, i) == f) {
1423 count = 1;
1424 TreeNode p = t.getTreeNode(h, k, t.root);
1425 if (p != null)
1426 val = p.val;
1427 else if ((val = mf.map(k)) != null) {
1428 added = true;
1429 count = 2;
1430 t.putTreeNode(h, k, val);
1431 }
1432 }
1433 } finally {
1434 t.release(0);
1435 }
1436 if (count != 0) {
1437 if (!added)
1438 return val;
1439 break;
1440 }
1441 }
1442 else
1443 tab = (Node[])fk;
1444 }
1445 else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1446 ((fk = f.key) == k || k.equals(fk)))
1447 return fv;
1448 else {
1449 Node g = f.next;
1450 if (g != null) {
1451 for (Node e = g;;) {
1452 Object ek, ev;
1453 if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1454 ((ek = e.key) == k || k.equals(ek)))
1455 return ev;
1456 if ((e = e.next) == null) {
1457 checkForResize();
1458 break;
1459 }
1460 }
1461 }
1462 if (((fh = f.hash) & LOCKED) != 0) {
1463 checkForResize();
1464 f.tryAwaitLock(tab, i);
1465 }
1466 else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1467 boolean added = false;
1468 try {
1469 if (tabAt(tab, i) == f) {
1470 count = 1;
1471 for (Node e = f;; ++count) {
1472 Object ek, ev;
1473 if ((e.hash & HASH_BITS) == h &&
1474 (ev = e.val) != null &&
1475 ((ek = e.key) == k || k.equals(ek))) {
1476 val = ev;
1477 break;
1478 }
1479 Node last = e;
1480 if ((e = e.next) == null) {
1481 if ((val = mf.map(k)) != null) {
1482 added = true;
1483 last.next = new Node(h, k, val, null);
1484 if (count >= TREE_THRESHOLD)
1485 replaceWithTreeBin(tab, i, k);
1486 }
1487 break;
1488 }
1489 }
1490 }
1491 } finally {
1492 if (!f.casHash(fh | LOCKED, fh)) {
1493 f.hash = fh;
1494 synchronized (f) { f.notifyAll(); };
1495 }
1496 }
1497 if (count != 0) {
1498 if (!added)
1499 return val;
1500 if (tab.length <= 64)
1501 count = 2;
1502 break;
1503 }
1504 }
1505 }
1506 }
1507 if (val == null)
1508 throw new NullPointerException();
1509 counter.add(1L);
1510 if (count > 1)
1511 checkForResize();
1512 return val;
1513 }
1514
1515 /** Implementation for compute */
1516 @SuppressWarnings("unchecked")
1517 private final Object internalCompute(K k,
1518 RemappingFunction<? super K, V> mf) {
1519 int h = spread(k.hashCode());
1520 Object val = null;
1521 boolean added = false;
1522 int count = 0;
1523 for (Node[] tab = table;;) {
1524 Node f; int i, fh; Object fk;
1525 if (tab == null)
1526 tab = initTable();
1527 else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1528 Node node = new Node(fh = h | LOCKED, k, null, null);
1529 if (casTabAt(tab, i, null, node)) {
1530 try {
1531 count = 1;
1532 if ((val = mf.remap(k, null)) != null) {
1533 node.val = val;
1534 added = true;
1535 }
1536 } finally {
1537 if (!added)
1538 setTabAt(tab, i, null);
1539 if (!node.casHash(fh, h)) {
1540 node.hash = h;
1541 synchronized (node) { node.notifyAll(); };
1542 }
1543 }
1544 }
1545 if (count != 0)
1546 break;
1547 }
1548 else if ((fh = f.hash) == MOVED) {
1549 if ((fk = f.key) instanceof TreeBin) {
1550 TreeBin t = (TreeBin)fk;
1551 t.acquire(0);
1552 try {
1553 if (tabAt(tab, i) == f) {
1554 count = 1;
1555 TreeNode p = t.getTreeNode(h, k, t.root);
1556 Object pv = (p == null) ? null : p.val;
1557 if ((val = mf.remap(k, (V)pv)) != null) {
1558 if (p != null)
1559 p.val = val;
1560 else {
1561 count = 2;
1562 added = true;
1563 t.putTreeNode(h, k, val);
1564 }
1565 }
1566 }
1567 } finally {
1568 t.release(0);
1569 }
1570 if (count != 0)
1571 break;
1572 }
1573 else
1574 tab = (Node[])fk;
1575 }
1576 else if ((fh & LOCKED) != 0) {
1577 checkForResize();
1578 f.tryAwaitLock(tab, i);
1579 }
1580 else if (f.casHash(fh, fh | LOCKED)) {
1581 try {
1582 if (tabAt(tab, i) == f) {
1583 count = 1;
1584 for (Node e = f;; ++count) {
1585 Object ek, ev;
1586 if ((e.hash & HASH_BITS) == h &&
1587 (ev = e.val) != null &&
1588 ((ek = e.key) == k || k.equals(ek))) {
1589 val = mf.remap(k, (V)ev);
1590 if (val != null)
1591 e.val = val;
1592 break;
1593 }
1594 Node last = e;
1595 if ((e = e.next) == null) {
1596 if ((val = mf.remap(k, null)) != null) {
1597 last.next = new Node(h, k, val, null);
1598 added = true;
1599 if (count >= TREE_THRESHOLD)
1600 replaceWithTreeBin(tab, i, k);
1601 }
1602 break;
1603 }
1604 }
1605 }
1606 } finally {
1607 if (!f.casHash(fh | LOCKED, fh)) {
1608 f.hash = fh;
1609 synchronized (f) { f.notifyAll(); };
1610 }
1611 }
1612 if (count != 0) {
1613 if (tab.length <= 64)
1614 count = 2;
1615 break;
1616 }
1617 }
1618 }
1619 if (val == null)
1620 throw new NullPointerException();
1621 if (added) {
1622 counter.add(1L);
1623 if (count > 1)
1624 checkForResize();
1625 }
1626 return val;
1627 }
1628
1629 /** Implementation for putAll */
1630 private final void internalPutAll(Map<?, ?> m) {
1631 tryPresize(m.size());
1632 long delta = 0L; // number of uncommitted additions
1633 boolean npe = false; // to throw exception on exit for nulls
1634 try { // to clean up counts on other exceptions
1635 for (Map.Entry<?, ?> entry : m.entrySet()) {
1636 Object k, v;
1637 if (entry == null || (k = entry.getKey()) == null ||
1638 (v = entry.getValue()) == null) {
1639 npe = true;
1640 break;
1641 }
1642 int h = spread(k.hashCode());
1643 for (Node[] tab = table;;) {
1644 int i; Node f; int fh; Object fk;
1645 if (tab == null)
1646 tab = initTable();
1647 else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1648 if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1649 ++delta;
1650 break;
1651 }
1652 }
1653 else if ((fh = f.hash) == MOVED) {
1654 if ((fk = f.key) instanceof TreeBin) {
1655 TreeBin t = (TreeBin)fk;
1656 boolean validated = false;
1657 t.acquire(0);
1658 try {
1659 if (tabAt(tab, i) == f) {
1660 validated = true;
1661 TreeNode p = t.getTreeNode(h, k, t.root);
1662 if (p != null)
1663 p.val = v;
1664 else {
1665 t.putTreeNode(h, k, v);
1666 ++delta;
1667 }
1668 }
1669 } finally {
1670 t.release(0);
1671 }
1672 if (validated)
1673 break;
1674 }
1675 else
1676 tab = (Node[])fk;
1677 }
1678 else if ((fh & LOCKED) != 0) {
1679 counter.add(delta);
1680 delta = 0L;
1681 checkForResize();
1682 f.tryAwaitLock(tab, i);
1683 }
1684 else if (f.casHash(fh, fh | LOCKED)) {
1685 int count = 0;
1686 try {
1687 if (tabAt(tab, i) == f) {
1688 count = 1;
1689 for (Node e = f;; ++count) {
1690 Object ek, ev;
1691 if ((e.hash & HASH_BITS) == h &&
1692 (ev = e.val) != null &&
1693 ((ek = e.key) == k || k.equals(ek))) {
1694 e.val = v;
1695 break;
1696 }
1697 Node last = e;
1698 if ((e = e.next) == null) {
1699 ++delta;
1700 last.next = new Node(h, k, v, null);
1701 if (count >= TREE_THRESHOLD)
1702 replaceWithTreeBin(tab, i, k);
1703 break;
1704 }
1705 }
1706 }
1707 } finally {
1708 if (!f.casHash(fh | LOCKED, fh)) {
1709 f.hash = fh;
1710 synchronized (f) { f.notifyAll(); };
1711 }
1712 }
1713 if (count != 0) {
1714 if (count > 1) {
1715 counter.add(delta);
1716 delta = 0L;
1717 checkForResize();
1718 }
1719 break;
1720 }
1721 }
1722 }
1723 }
1724 } finally {
1725 if (delta != 0)
1726 counter.add(delta);
1727 }
1728 if (npe)
1729 throw new NullPointerException();
1730 }
1731
1732 /* ---------------- Table Initialization and Resizing -------------- */
1733
1734 /**
1735 * Returns a power of two table size for the given desired capacity.
1736 * See Hackers Delight, sec 3.2
1737 */
1738 private static final int tableSizeFor(int c) {
1739 int n = c - 1;
1740 n |= n >>> 1;
1741 n |= n >>> 2;
1742 n |= n >>> 4;
1743 n |= n >>> 8;
1744 n |= n >>> 16;
1745 return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
1746 }
1747
1748 /**
1749 * Initializes table, using the size recorded in sizeCtl.
1750 */
1751 private final Node[] initTable() {
1752 Node[] tab; int sc;
1753 while ((tab = table) == null) {
1754 if ((sc = sizeCtl) < 0)
1755 Thread.yield(); // lost initialization race; just spin
1756 else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1757 try {
1758 if ((tab = table) == null) {
1759 int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1760 tab = table = new Node[n];
1761 sc = n - (n >>> 2);
1762 }
1763 } finally {
1764 sizeCtl = sc;
1765 }
1766 break;
1767 }
1768 }
1769 return tab;
1770 }
1771
1772 /**
1773 * If table is too small and not already resizing, creates next
1774 * table and transfers bins. Rechecks occupancy after a transfer
1775 * to see if another resize is already needed because resizings
1776 * are lagging additions.
1777 */
1778 private final void checkForResize() {
1779 Node[] tab; int n, sc;
1780 while ((tab = table) != null &&
1781 (n = tab.length) < MAXIMUM_CAPACITY &&
1782 (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1783 UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1784 try {
1785 if (tab == table) {
1786 table = rebuild(tab);
1787 sc = (n << 1) - (n >>> 1);
1788 }
1789 } finally {
1790 sizeCtl = sc;
1791 }
1792 }
1793 }
1794
1795 /**
1796 * Tries to presize table to accommodate the given number of elements.
1797 *
1798 * @param size number of elements (doesn't need to be perfectly accurate)
1799 */
1800 private final void tryPresize(int size) {
1801 int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1802 tableSizeFor(size + (size >>> 1) + 1);
1803 int sc;
1804 while ((sc = sizeCtl) >= 0) {
1805 Node[] tab = table; int n;
1806 if (tab == null || (n = tab.length) == 0) {
1807 n = (sc > c) ? sc : c;
1808 if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1809 try {
1810 if (table == tab) {
1811 table = new Node[n];
1812 sc = n - (n >>> 2);
1813 }
1814 } finally {
1815 sizeCtl = sc;
1816 }
1817 }
1818 }
1819 else if (c <= sc || n >= MAXIMUM_CAPACITY)
1820 break;
1821 else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1822 try {
1823 if (table == tab) {
1824 table = rebuild(tab);
1825 sc = (n << 1) - (n >>> 1);
1826 }
1827 } finally {
1828 sizeCtl = sc;
1829 }
1830 }
1831 }
1832 }
1833
1834 /*
1835 * Moves and/or copies the nodes in each bin to new table. See
1836 * above for explanation.
1837 *
1838 * @return the new table
1839 */
1840 private static final Node[] rebuild(Node[] tab) {
1841 int n = tab.length;
1842 Node[] nextTab = new Node[n << 1];
1843 Node fwd = new Node(MOVED, nextTab, null, null);
1844 int[] buffer = null; // holds bins to revisit; null until needed
1845 Node rev = null; // reverse forwarder; null until needed
1846 int nbuffered = 0; // the number of bins in buffer list
1847 int bufferIndex = 0; // buffer index of current buffered bin
1848 int bin = n - 1; // current non-buffered bin or -1 if none
1849
1850 for (int i = bin;;) { // start upwards sweep
1851 int fh; Node f;
1852 if ((f = tabAt(tab, i)) == null) {
1853 if (bin >= 0) { // no lock needed (or available)
1854 if (!casTabAt(tab, i, f, fwd))
1855 continue;
1856 }
1857 else { // transiently use a locked forwarding node
1858 Node g = new Node(MOVED|LOCKED, nextTab, null, null);
1859 if (!casTabAt(tab, i, f, g))
1860 continue;
1861 setTabAt(nextTab, i, null);
1862 setTabAt(nextTab, i + n, null);
1863 setTabAt(tab, i, fwd);
1864 if (!g.casHash(MOVED|LOCKED, MOVED)) {
1865 g.hash = MOVED;
1866 synchronized (g) { g.notifyAll(); }
1867 }
1868 }
1869 }
1870 else if ((fh = f.hash) == MOVED) {
1871 Object fk = f.key;
1872 if (fk instanceof TreeBin) {
1873 TreeBin t = (TreeBin)fk;
1874 boolean validated = false;
1875 t.acquire(0);
1876 try {
1877 if (tabAt(tab, i) == f) {
1878 validated = true;
1879 splitTreeBin(nextTab, i, t);
1880 setTabAt(tab, i, fwd);
1881 }
1882 } finally {
1883 t.release(0);
1884 }
1885 if (!validated)
1886 continue;
1887 }
1888 }
1889 else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
1890 boolean validated = false;
1891 try { // split to lo and hi lists; copying as needed
1892 if (tabAt(tab, i) == f) {
1893 validated = true;
1894 splitBin(nextTab, i, f);
1895 setTabAt(tab, i, fwd);
1896 }
1897 } finally {
1898 if (!f.casHash(fh | LOCKED, fh)) {
1899 f.hash = fh;
1900 synchronized (f) { f.notifyAll(); };
1901 }
1902 }
1903 if (!validated)
1904 continue;
1905 }
1906 else {
1907 if (buffer == null) // initialize buffer for revisits
1908 buffer = new int[TRANSFER_BUFFER_SIZE];
1909 if (bin < 0 && bufferIndex > 0) {
1910 int j = buffer[--bufferIndex];
1911 buffer[bufferIndex] = i;
1912 i = j; // swap with another bin
1913 continue;
1914 }
1915 if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
1916 f.tryAwaitLock(tab, i);
1917 continue; // no other options -- block
1918 }
1919 if (rev == null) // initialize reverse-forwarder
1920 rev = new Node(MOVED, tab, null, null);
1921 if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
1922 continue; // recheck before adding to list
1923 buffer[nbuffered++] = i;
1924 setTabAt(nextTab, i, rev); // install place-holders
1925 setTabAt(nextTab, i + n, rev);
1926 }
1927
1928 if (bin > 0)
1929 i = --bin;
1930 else if (buffer != null && nbuffered > 0) {
1931 bin = -1;
1932 i = buffer[bufferIndex = --nbuffered];
1933 }
1934 else
1935 return nextTab;
1936 }
1937 }
1938
1939 /**
1940 * Split a normal bin with list headed by e into lo and hi parts;
1941 * install in given table
1942 */
1943 private static void splitBin(Node[] nextTab, int i, Node e) {
1944 int bit = nextTab.length >>> 1; // bit to split on
1945 int runBit = e.hash & bit;
1946 Node lastRun = e, lo = null, hi = null;
1947 for (Node p = e.next; p != null; p = p.next) {
1948 int b = p.hash & bit;
1949 if (b != runBit) {
1950 runBit = b;
1951 lastRun = p;
1952 }
1953 }
1954 if (runBit == 0)
1955 lo = lastRun;
1956 else
1957 hi = lastRun;
1958 for (Node p = e; p != lastRun; p = p.next) {
1959 int ph = p.hash & HASH_BITS;
1960 Object pk = p.key, pv = p.val;
1961 if ((ph & bit) == 0)
1962 lo = new Node(ph, pk, pv, lo);
1963 else
1964 hi = new Node(ph, pk, pv, hi);
1965 }
1966 setTabAt(nextTab, i, lo);
1967 setTabAt(nextTab, i + bit, hi);
1968 }
1969
1970 /**
1971 * Split a tree bin into lo and hi parts; install in given table
1972 */
1973 private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
1974 int bit = nextTab.length >>> 1;
1975 TreeBin lt = new TreeBin();
1976 TreeBin ht = new TreeBin();
1977 int lc = 0, hc = 0;
1978 for (Node e = t.first; e != null; e = e.next) {
1979 int h = e.hash & HASH_BITS;
1980 Object k = e.key, v = e.val;
1981 if ((h & bit) == 0) {
1982 ++lc;
1983 lt.putTreeNode(h, k, v);
1984 }
1985 else {
1986 ++hc;
1987 ht.putTreeNode(h, k, v);
1988 }
1989 }
1990 Node ln, hn; // throw away trees if too small
1991 if (lc <= (TREE_THRESHOLD >>> 1)) {
1992 ln = null;
1993 for (Node p = lt.first; p != null; p = p.next)
1994 ln = new Node(p.hash, p.key, p.val, ln);
1995 }
1996 else
1997 ln = new Node(MOVED, lt, null, null);
1998 setTabAt(nextTab, i, ln);
1999 if (hc <= (TREE_THRESHOLD >>> 1)) {
2000 hn = null;
2001 for (Node p = ht.first; p != null; p = p.next)
2002 hn = new Node(p.hash, p.key, p.val, hn);
2003 }
2004 else
2005 hn = new Node(MOVED, ht, null, null);
2006 setTabAt(nextTab, i + bit, hn);
2007 }
2008
2009 /**
2010 * Implementation for clear. Steps through each bin, removing all
2011 * nodes.
2012 */
2013 private final void internalClear() {
2014 long delta = 0L; // negative number of deletions
2015 int i = 0;
2016 Node[] tab = table;
2017 while (tab != null && i < tab.length) {
2018 int fh; Object fk;
2019 Node f = tabAt(tab, i);
2020 if (f == null)
2021 ++i;
2022 else if ((fh = f.hash) == MOVED) {
2023 if ((fk = f.key) instanceof TreeBin) {
2024 TreeBin t = (TreeBin)fk;
2025 t.acquire(0);
2026 try {
2027 if (tabAt(tab, i) == f) {
2028 for (Node p = t.first; p != null; p = p.next) {
2029 p.val = null;
2030 --delta;
2031 }
2032 t.first = null;
2033 t.root = null;
2034 ++i;
2035 }
2036 } finally {
2037 t.release(0);
2038 }
2039 }
2040 else
2041 tab = (Node[])fk;
2042 }
2043 else if ((fh & LOCKED) != 0) {
2044 counter.add(delta); // opportunistically update count
2045 delta = 0L;
2046 f.tryAwaitLock(tab, i);
2047 }
2048 else if (f.casHash(fh, fh | LOCKED)) {
2049 try {
2050 if (tabAt(tab, i) == f) {
2051 for (Node e = f; e != null; e = e.next) {
2052 e.val = null;
2053 --delta;
2054 }
2055 setTabAt(tab, i, null);
2056 ++i;
2057 }
2058 } finally {
2059 if (!f.casHash(fh | LOCKED, fh)) {
2060 f.hash = fh;
2061 synchronized (f) { f.notifyAll(); };
2062 }
2063 }
2064 }
2065 }
2066 if (delta != 0)
2067 counter.add(delta);
2068 }
2069
2070 /* ----------------Table Traversal -------------- */
2071
2072 /**
2073 * Encapsulates traversal for methods such as containsValue; also
2074 * serves as a base class for other iterators.
2075 *
2076 * At each step, the iterator snapshots the key ("nextKey") and
2077 * value ("nextVal") of a valid node (i.e., one that, at point of
2078 * snapshot, has a non-null user value). Because val fields can
2079 * change (including to null, indicating deletion), field nextVal
2080 * might not be accurate at point of use, but still maintains the
2081 * weak consistency property of holding a value that was once
2082 * valid.
2083 *
2084 * Internal traversals directly access these fields, as in:
2085 * {@code while (it.next != null) { process(it.nextKey); it.advance(); }}
2086 *
2087 * Exported iterators (subclasses of ViewIterator) extract key,
2088 * value, or key-value pairs as return values of Iterator.next(),
2089 * and encapsulate the it.next check as hasNext();
2090 *
2091 * The iterator visits once each still-valid node that was
2092 * reachable upon iterator construction. It might miss some that
2093 * were added to a bin after the bin was visited, which is OK wrt
2094 * consistency guarantees. Maintaining this property in the face
2095 * of possible ongoing resizes requires a fair amount of
2096 * bookkeeping state that is difficult to optimize away amidst
2097 * volatile accesses. Even so, traversal maintains reasonable
2098 * throughput.
2099 *
2100 * Normally, iteration proceeds bin-by-bin traversing lists.
2101 * However, if the table has been resized, then all future steps
2102 * must traverse both the bin at the current index as well as at
2103 * (index + baseSize); and so on for further resizings. To
2104 * paranoically cope with potential sharing by users of iterators
2105 * across threads, iteration terminates if a bounds checks fails
2106 * for a table read.
2107 *
2108 * The range-based constructor enables creation of parallel
2109 * range-splitting traversals. (Not yet implemented.)
2110 */
2111 static class InternalIterator {
2112 Node next; // the next entry to use
2113 Node last; // the last entry used
2114 Object nextKey; // cached key field of next
2115 Object nextVal; // cached val field of next
2116 Node[] tab; // current table; updated if resized
2117 int index; // index of bin to use next
2118 int baseIndex; // current index of initial table
2119 final int baseLimit; // index bound for initial table
2120 final int baseSize; // initial table size
2121
2122 /** Creates iterator for all entries in the table. */
2123 InternalIterator(Node[] tab) {
2124 this.tab = tab;
2125 baseLimit = baseSize = (tab == null) ? 0 : tab.length;
2126 index = baseIndex = 0;
2127 next = null;
2128 advance();
2129 }
2130
2131 /** Creates iterator for the given range of the table */
2132 InternalIterator(Node[] tab, int lo, int hi) {
2133 this.tab = tab;
2134 baseSize = (tab == null) ? 0 : tab.length;
2135 baseLimit = (hi <= baseSize) ? hi : baseSize;
2136 index = baseIndex = (lo >= 0) ? lo : 0;
2137 next = null;
2138 advance();
2139 }
2140
2141 /** Advances next. See above for explanation. */
2142 final void advance() {
2143 Node e = last = next;
2144 outer: do {
2145 if (e != null) // advance past used/skipped node
2146 e = e.next;
2147 while (e == null) { // get to next non-null bin
2148 Node[] t; int b, i, n; Object ek; // checks must use locals
2149 if ((b = baseIndex) >= baseLimit || (i = index) < 0 ||
2150 (t = tab) == null || i >= (n = t.length))
2151 break outer;
2152 else if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2153 if ((ek = e.key) instanceof TreeBin)
2154 e = ((TreeBin)ek).first;
2155 else {
2156 tab = (Node[])ek;
2157 continue; // restarts due to null val
2158 }
2159 } // visit upper slots if present
2160 index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2161 }
2162 nextKey = e.key;
2163 } while ((nextVal = e.val) == null);// skip deleted or special nodes
2164 next = e;
2165 }
2166 }
2167
2168 /* ---------------- Public operations -------------- */
2169
2170 /**
2171 * Creates a new, empty map with the default initial table size (16),
2172 */
2173 public ConcurrentHashMapV8() {
2174 this.counter = new LongAdder();
2175 }
2176
2177 /**
2178 * Creates a new, empty map with an initial table size
2179 * accommodating the specified number of elements without the need
2180 * to dynamically resize.
2181 *
2182 * @param initialCapacity The implementation performs internal
2183 * sizing to accommodate this many elements.
2184 * @throws IllegalArgumentException if the initial capacity of
2185 * elements is negative
2186 */
2187 public ConcurrentHashMapV8(int initialCapacity) {
2188 if (initialCapacity < 0)
2189 throw new IllegalArgumentException();
2190 int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2191 MAXIMUM_CAPACITY :
2192 tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2193 this.counter = new LongAdder();
2194 this.sizeCtl = cap;
2195 }
2196
2197 /**
2198 * Creates a new map with the same mappings as the given map.
2199 *
2200 * @param m the map
2201 */
2202 public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2203 this.counter = new LongAdder();
2204 this.sizeCtl = DEFAULT_CAPACITY;
2205 internalPutAll(m);
2206 }
2207
2208 /**
2209 * Creates a new, empty map with an initial table size based on
2210 * the given number of elements ({@code initialCapacity}) and
2211 * initial table density ({@code loadFactor}).
2212 *
2213 * @param initialCapacity the initial capacity. The implementation
2214 * performs internal sizing to accommodate this many elements,
2215 * given the specified load factor.
2216 * @param loadFactor the load factor (table density) for
2217 * establishing the initial table size
2218 * @throws IllegalArgumentException if the initial capacity of
2219 * elements is negative or the load factor is nonpositive
2220 *
2221 * @since 1.6
2222 */
2223 public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
2224 this(initialCapacity, loadFactor, 1);
2225 }
2226
2227 /**
2228 * Creates a new, empty map with an initial table size based on
2229 * the given number of elements ({@code initialCapacity}), table
2230 * density ({@code loadFactor}), and number of concurrently
2231 * updating threads ({@code concurrencyLevel}).
2232 *
2233 * @param initialCapacity the initial capacity. The implementation
2234 * performs internal sizing to accommodate this many elements,
2235 * given the specified load factor.
2236 * @param loadFactor the load factor (table density) for
2237 * establishing the initial table size
2238 * @param concurrencyLevel the estimated number of concurrently
2239 * updating threads. The implementation may use this value as
2240 * a sizing hint.
2241 * @throws IllegalArgumentException if the initial capacity is
2242 * negative or the load factor or concurrencyLevel are
2243 * nonpositive
2244 */
2245 public ConcurrentHashMapV8(int initialCapacity,
2246 float loadFactor, int concurrencyLevel) {
2247 if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2248 throw new IllegalArgumentException();
2249 if (initialCapacity < concurrencyLevel) // Use at least as many bins
2250 initialCapacity = concurrencyLevel; // as estimated threads
2251 long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2252 int cap = ((size >= (long)MAXIMUM_CAPACITY) ?
2253 MAXIMUM_CAPACITY: tableSizeFor((int)size));
2254 this.counter = new LongAdder();
2255 this.sizeCtl = cap;
2256 }
2257
2258 /**
2259 * {@inheritDoc}
2260 */
2261 public boolean isEmpty() {
2262 return counter.sum() <= 0L; // ignore transient negative values
2263 }
2264
2265 /**
2266 * {@inheritDoc}
2267 */
2268 public int size() {
2269 long n = counter.sum();
2270 return ((n < 0L) ? 0 :
2271 (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2272 (int)n);
2273 }
2274
2275 final long longSize() { // accurate version of size needed for views
2276 long n = counter.sum();
2277 return (n < 0L) ? 0L : n;
2278 }
2279
2280 /**
2281 * Returns the value to which the specified key is mapped,
2282 * or {@code null} if this map contains no mapping for the key.
2283 *
2284 * <p>More formally, if this map contains a mapping from a key
2285 * {@code k} to a value {@code v} such that {@code key.equals(k)},
2286 * then this method returns {@code v}; otherwise it returns
2287 * {@code null}. (There can be at most one such mapping.)
2288 *
2289 * @throws NullPointerException if the specified key is null
2290 */
2291 @SuppressWarnings("unchecked")
2292 public V get(Object key) {
2293 if (key == null)
2294 throw new NullPointerException();
2295 return (V)internalGet(key);
2296 }
2297
2298 /**
2299 * Tests if the specified object is a key in this table.
2300 *
2301 * @param key possible key
2302 * @return {@code true} if and only if the specified object
2303 * is a key in this table, as determined by the
2304 * {@code equals} method; {@code false} otherwise
2305 * @throws NullPointerException if the specified key is null
2306 */
2307 public boolean containsKey(Object key) {
2308 if (key == null)
2309 throw new NullPointerException();
2310 return internalGet(key) != null;
2311 }
2312
2313 /**
2314 * Returns {@code true} if this map maps one or more keys to the
2315 * specified value. Note: This method may require a full traversal
2316 * of the map, and is much slower than method {@code containsKey}.
2317 *
2318 * @param value value whose presence in this map is to be tested
2319 * @return {@code true} if this map maps one or more keys to the
2320 * specified value
2321 * @throws NullPointerException if the specified value is null
2322 */
2323 public boolean containsValue(Object value) {
2324 if (value == null)
2325 throw new NullPointerException();
2326 Object v;
2327 InternalIterator it = new InternalIterator(table);
2328 while (it.next != null) {
2329 if ((v = it.nextVal) == value || value.equals(v))
2330 return true;
2331 it.advance();
2332 }
2333 return false;
2334 }
2335
2336 /**
2337 * Legacy method testing if some key maps into the specified value
2338 * in this table. This method is identical in functionality to
2339 * {@link #containsValue}, and exists solely to ensure
2340 * full compatibility with class {@link java.util.Hashtable},
2341 * which supported this method prior to introduction of the
2342 * Java Collections framework.
2343 *
2344 * @param value a value to search for
2345 * @return {@code true} if and only if some key maps to the
2346 * {@code value} argument in this table as
2347 * determined by the {@code equals} method;
2348 * {@code false} otherwise
2349 * @throws NullPointerException if the specified value is null
2350 */
2351 public boolean contains(Object value) {
2352 return containsValue(value);
2353 }
2354
2355 /**
2356 * Maps the specified key to the specified value in this table.
2357 * Neither the key nor the value can be null.
2358 *
2359 * <p> The value can be retrieved by calling the {@code get} method
2360 * with a key that is equal to the original key.
2361 *
2362 * @param key key with which the specified value is to be associated
2363 * @param value value to be associated with the specified key
2364 * @return the previous value associated with {@code key}, or
2365 * {@code null} if there was no mapping for {@code key}
2366 * @throws NullPointerException if the specified key or value is null
2367 */
2368 @SuppressWarnings("unchecked")
2369 public V put(K key, V value) {
2370 if (key == null || value == null)
2371 throw new NullPointerException();
2372 return (V)internalPut(key, value);
2373 }
2374
2375 /**
2376 * {@inheritDoc}
2377 *
2378 * @return the previous value associated with the specified key,
2379 * or {@code null} if there was no mapping for the key
2380 * @throws NullPointerException if the specified key or value is null
2381 */
2382 @SuppressWarnings("unchecked")
2383 public V putIfAbsent(K key, V value) {
2384 if (key == null || value == null)
2385 throw new NullPointerException();
2386 return (V)internalPutIfAbsent(key, value);
2387 }
2388
2389 /**
2390 * Copies all of the mappings from the specified map to this one.
2391 * These mappings replace any mappings that this map had for any of the
2392 * keys currently in the specified map.
2393 *
2394 * @param m mappings to be stored in this map
2395 */
2396 public void putAll(Map<? extends K, ? extends V> m) {
2397 internalPutAll(m);
2398 }
2399
2400 /**
2401 * If the specified key is not already associated with a value,
2402 * computes its value using the given mappingFunction and
2403 * enters it into the map. This is equivalent to
2404 * <pre> {@code
2405 * if (map.containsKey(key))
2406 * return map.get(key);
2407 * value = mappingFunction.map(key);
2408 * map.put(key, value);
2409 * return value;}</pre>
2410 *
2411 * except that the action is performed atomically. If the
2412 * function returns {@code null} (in which case a {@code
2413 * NullPointerException} is thrown), or the function itself throws
2414 * an (unchecked) exception, the exception is rethrown to its
2415 * caller, and no mapping is recorded. Some attempted update
2416 * operations on this map by other threads may be blocked while
2417 * computation is in progress, so the computation should be short
2418 * and simple, and must not attempt to update any other mappings
2419 * of this Map. The most appropriate usage is to construct a new
2420 * object serving as an initial mapped value, or memoized result,
2421 * as in:
2422 *
2423 * <pre> {@code
2424 * map.computeIfAbsent(key, new MappingFunction<K, V>() {
2425 * public V map(K k) { return new Value(f(k)); }});}</pre>
2426 *
2427 * @param key key with which the specified value is to be associated
2428 * @param mappingFunction the function to compute a value
2429 * @return the current (existing or computed) value associated with
2430 * the specified key.
2431 * @throws NullPointerException if the specified key, mappingFunction,
2432 * or computed value is null
2433 * @throws IllegalStateException if the computation detectably
2434 * attempts a recursive update to this map that would
2435 * otherwise never complete
2436 * @throws RuntimeException or Error if the mappingFunction does so,
2437 * in which case the mapping is left unestablished
2438 */
2439 @SuppressWarnings("unchecked")
2440 public V computeIfAbsent(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
2441 if (key == null || mappingFunction == null)
2442 throw new NullPointerException();
2443 return (V)internalComputeIfAbsent(key, mappingFunction);
2444 }
2445
2446 /**
2447 * Computes and enters a new mapping value given a key and
2448 * its current mapped value (or {@code null} if there is no current
2449 * mapping). This is equivalent to
2450 * <pre> {@code
2451 * map.put(key, remappingFunction.remap(key, map.get(key));
2452 * }</pre>
2453 *
2454 * except that the action is performed atomically. If the
2455 * function returns {@code null} (in which case a {@code
2456 * NullPointerException} is thrown), or the function itself throws
2457 * an (unchecked) exception, the exception is rethrown to its
2458 * caller, and current mapping is left unchanged. Some attempted
2459 * update operations on this map by other threads may be blocked
2460 * while computation is in progress, so the computation should be
2461 * short and simple, and must not attempt to update any other
2462 * mappings of this Map. For example, to either create or
2463 * append new messages to a value mapping:
2464 *
2465 * <pre> {@code
2466 * Map<Key, String> map = ...;
2467 * final String msg = ...;
2468 * map.compute(key, new RemappingFunction<Key, String>() {
2469 * public String remap(Key k, String v) {
2470 * return (v == null) ? msg : v + msg;});}}</pre>
2471 *
2472 * @param key key with which the specified value is to be associated
2473 * @param remappingFunction the function to compute a value
2474 * @return the new value associated with
2475 * the specified key.
2476 * @throws NullPointerException if the specified key or remappingFunction
2477 * or computed value is null
2478 * @throws IllegalStateException if the computation detectably
2479 * attempts a recursive update to this map that would
2480 * otherwise never complete
2481 * @throws RuntimeException or Error if the remappingFunction does so,
2482 * in which case the mapping is unchanged
2483 */
2484 @SuppressWarnings("unchecked")
2485 public V compute(K key, RemappingFunction<? super K, V> remappingFunction) {
2486 if (key == null || remappingFunction == null)
2487 throw new NullPointerException();
2488 return (V)internalCompute(key, remappingFunction);
2489 }
2490
2491 /**
2492 * Removes the key (and its corresponding value) from this map.
2493 * This method does nothing if the key is not in the map.
2494 *
2495 * @param key the key that needs to be removed
2496 * @return the previous value associated with {@code key}, or
2497 * {@code null} if there was no mapping for {@code key}
2498 * @throws NullPointerException if the specified key is null
2499 */
2500 @SuppressWarnings("unchecked")
2501 public V remove(Object key) {
2502 if (key == null)
2503 throw new NullPointerException();
2504 return (V)internalReplace(key, null, null);
2505 }
2506
2507 /**
2508 * {@inheritDoc}
2509 *
2510 * @throws NullPointerException if the specified key is null
2511 */
2512 public boolean remove(Object key, Object value) {
2513 if (key == null)
2514 throw new NullPointerException();
2515 if (value == null)
2516 return false;
2517 return internalReplace(key, null, value) != null;
2518 }
2519
2520 /**
2521 * {@inheritDoc}
2522 *
2523 * @throws NullPointerException if any of the arguments are null
2524 */
2525 public boolean replace(K key, V oldValue, V newValue) {
2526 if (key == null || oldValue == null || newValue == null)
2527 throw new NullPointerException();
2528 return internalReplace(key, newValue, oldValue) != null;
2529 }
2530
2531 /**
2532 * {@inheritDoc}
2533 *
2534 * @return the previous value associated with the specified key,
2535 * or {@code null} if there was no mapping for the key
2536 * @throws NullPointerException if the specified key or value is null
2537 */
2538 @SuppressWarnings("unchecked")
2539 public V replace(K key, V value) {
2540 if (key == null || value == null)
2541 throw new NullPointerException();
2542 return (V)internalReplace(key, value, null);
2543 }
2544
2545 /**
2546 * Removes all of the mappings from this map.
2547 */
2548 public void clear() {
2549 internalClear();
2550 }
2551
2552 /**
2553 * Returns a {@link Set} view of the keys contained in this map.
2554 * The set is backed by the map, so changes to the map are
2555 * reflected in the set, and vice-versa. The set supports element
2556 * removal, which removes the corresponding mapping from this map,
2557 * via the {@code Iterator.remove}, {@code Set.remove},
2558 * {@code removeAll}, {@code retainAll}, and {@code clear}
2559 * operations. It does not support the {@code add} or
2560 * {@code addAll} operations.
2561 *
2562 * <p>The view's {@code iterator} is a "weakly consistent" iterator
2563 * that will never throw {@link ConcurrentModificationException},
2564 * and guarantees to traverse elements as they existed upon
2565 * construction of the iterator, and may (but is not guaranteed to)
2566 * reflect any modifications subsequent to construction.
2567 */
2568 public Set<K> keySet() {
2569 KeySet<K,V> ks = keySet;
2570 return (ks != null) ? ks : (keySet = new KeySet<K,V>(this));
2571 }
2572
2573 /**
2574 * Returns a {@link Collection} view of the values contained in this map.
2575 * The collection is backed by the map, so changes to the map are
2576 * reflected in the collection, and vice-versa. The collection
2577 * supports element removal, which removes the corresponding
2578 * mapping from this map, via the {@code Iterator.remove},
2579 * {@code Collection.remove}, {@code removeAll},
2580 * {@code retainAll}, and {@code clear} operations. It does not
2581 * support the {@code add} or {@code addAll} operations.
2582 *
2583 * <p>The view's {@code iterator} is a "weakly consistent" iterator
2584 * that will never throw {@link ConcurrentModificationException},
2585 * and guarantees to traverse elements as they existed upon
2586 * construction of the iterator, and may (but is not guaranteed to)
2587 * reflect any modifications subsequent to construction.
2588 */
2589 public Collection<V> values() {
2590 Values<K,V> vs = values;
2591 return (vs != null) ? vs : (values = new Values<K,V>(this));
2592 }
2593
2594 /**
2595 * Returns a {@link Set} view of the mappings contained in this map.
2596 * The set is backed by the map, so changes to the map are
2597 * reflected in the set, and vice-versa. The set supports element
2598 * removal, which removes the corresponding mapping from the map,
2599 * via the {@code Iterator.remove}, {@code Set.remove},
2600 * {@code removeAll}, {@code retainAll}, and {@code clear}
2601 * operations. It does not support the {@code add} or
2602 * {@code addAll} operations.
2603 *
2604 * <p>The view's {@code iterator} is a "weakly consistent" iterator
2605 * that will never throw {@link ConcurrentModificationException},
2606 * and guarantees to traverse elements as they existed upon
2607 * construction of the iterator, and may (but is not guaranteed to)
2608 * reflect any modifications subsequent to construction.
2609 */
2610 public Set<Map.Entry<K,V>> entrySet() {
2611 EntrySet<K,V> es = entrySet;
2612 return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
2613 }
2614
2615 /**
2616 * Returns an enumeration of the keys in this table.
2617 *
2618 * @return an enumeration of the keys in this table
2619 * @see #keySet()
2620 */
2621 public Enumeration<K> keys() {
2622 return new KeyIterator<K,V>(this);
2623 }
2624
2625 /**
2626 * Returns an enumeration of the values in this table.
2627 *
2628 * @return an enumeration of the values in this table
2629 * @see #values()
2630 */
2631 public Enumeration<V> elements() {
2632 return new ValueIterator<K,V>(this);
2633 }
2634
2635 /**
2636 * Returns the hash code value for this {@link Map}, i.e.,
2637 * the sum of, for each key-value pair in the map,
2638 * {@code key.hashCode() ^ value.hashCode()}.
2639 *
2640 * @return the hash code value for this map
2641 */
2642 public int hashCode() {
2643 int h = 0;
2644 InternalIterator it = new InternalIterator(table);
2645 while (it.next != null) {
2646 h += it.nextKey.hashCode() ^ it.nextVal.hashCode();
2647 it.advance();
2648 }
2649 return h;
2650 }
2651
2652 /**
2653 * Returns a string representation of this map. The string
2654 * representation consists of a list of key-value mappings (in no
2655 * particular order) enclosed in braces ("{@code {}}"). Adjacent
2656 * mappings are separated by the characters {@code ", "} (comma
2657 * and space). Each key-value mapping is rendered as the key
2658 * followed by an equals sign ("{@code =}") followed by the
2659 * associated value.
2660 *
2661 * @return a string representation of this map
2662 */
2663 public String toString() {
2664 InternalIterator it = new InternalIterator(table);
2665 StringBuilder sb = new StringBuilder();
2666 sb.append('{');
2667 if (it.next != null) {
2668 for (;;) {
2669 Object k = it.nextKey, v = it.nextVal;
2670 sb.append(k == this ? "(this Map)" : k);
2671 sb.append('=');
2672 sb.append(v == this ? "(this Map)" : v);
2673 it.advance();
2674 if (it.next == null)
2675 break;
2676 sb.append(',').append(' ');
2677 }
2678 }
2679 return sb.append('}').toString();
2680 }
2681
2682 /**
2683 * Compares the specified object with this map for equality.
2684 * Returns {@code true} if the given object is a map with the same
2685 * mappings as this map. This operation may return misleading
2686 * results if either map is concurrently modified during execution
2687 * of this method.
2688 *
2689 * @param o object to be compared for equality with this map
2690 * @return {@code true} if the specified object is equal to this map
2691 */
2692 public boolean equals(Object o) {
2693 if (o != this) {
2694 if (!(o instanceof Map))
2695 return false;
2696 Map<?,?> m = (Map<?,?>) o;
2697 InternalIterator it = new InternalIterator(table);
2698 while (it.next != null) {
2699 Object val = it.nextVal;
2700 Object v = m.get(it.nextKey);
2701 if (v == null || (v != val && !v.equals(val)))
2702 return false;
2703 it.advance();
2704 }
2705 for (Map.Entry<?,?> e : m.entrySet()) {
2706 Object mk, mv, v;
2707 if ((mk = e.getKey()) == null ||
2708 (mv = e.getValue()) == null ||
2709 (v = internalGet(mk)) == null ||
2710 (mv != v && !mv.equals(v)))
2711 return false;
2712 }
2713 }
2714 return true;
2715 }
2716
2717 /* ----------------Iterators -------------- */
2718
2719 /**
2720 * Base class for key, value, and entry iterators. Adds a map
2721 * reference to InternalIterator to support Iterator.remove.
2722 */
2723 static abstract class ViewIterator<K,V> extends InternalIterator {
2724 final ConcurrentHashMapV8<K, V> map;
2725 ViewIterator(ConcurrentHashMapV8<K, V> map) {
2726 super(map.table);
2727 this.map = map;
2728 }
2729
2730 public final void remove() {
2731 if (last == null)
2732 throw new IllegalStateException();
2733 map.remove(last.key);
2734 last = null;
2735 }
2736
2737 public final boolean hasNext() { return next != null; }
2738 public final boolean hasMoreElements() { return next != null; }
2739 }
2740
2741 static final class KeyIterator<K,V> extends ViewIterator<K,V>
2742 implements Iterator<K>, Enumeration<K> {
2743 KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
2744
2745 @SuppressWarnings("unchecked")
2746 public final K next() {
2747 if (next == null)
2748 throw new NoSuchElementException();
2749 Object k = nextKey;
2750 advance();
2751 return (K)k;
2752 }
2753
2754 public final K nextElement() { return next(); }
2755 }
2756
2757 static final class ValueIterator<K,V> extends ViewIterator<K,V>
2758 implements Iterator<V>, Enumeration<V> {
2759 ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
2760
2761 @SuppressWarnings("unchecked")
2762 public final V next() {
2763 if (next == null)
2764 throw new NoSuchElementException();
2765 Object v = nextVal;
2766 advance();
2767 return (V)v;
2768 }
2769
2770 public final V nextElement() { return next(); }
2771 }
2772
2773 static final class EntryIterator<K,V> extends ViewIterator<K,V>
2774 implements Iterator<Map.Entry<K,V>> {
2775 EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
2776
2777 @SuppressWarnings("unchecked")
2778 public final Map.Entry<K,V> next() {
2779 if (next == null)
2780 throw new NoSuchElementException();
2781 Object k = nextKey;
2782 Object v = nextVal;
2783 advance();
2784 return new WriteThroughEntry<K,V>((K)k, (V)v, map);
2785 }
2786 }
2787
2788 static final class SnapshotEntryIterator<K,V> extends ViewIterator<K,V>
2789 implements Iterator<Map.Entry<K,V>> {
2790 SnapshotEntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
2791
2792 @SuppressWarnings("unchecked")
2793 public final Map.Entry<K,V> next() {
2794 if (next == null)
2795 throw new NoSuchElementException();
2796 Object k = nextKey;
2797 Object v = nextVal;
2798 advance();
2799 return new SnapshotEntry<K,V>((K)k, (V)v);
2800 }
2801 }
2802
2803 /**
2804 * Base of writeThrough and Snapshot entry classes
2805 */
2806 static abstract class MapEntry<K,V> implements Map.Entry<K, V> {
2807 final K key; // non-null
2808 V val; // non-null
2809 MapEntry(K key, V val) { this.key = key; this.val = val; }
2810 public final K getKey() { return key; }
2811 public final V getValue() { return val; }
2812 public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
2813 public final String toString(){ return key + "=" + val; }
2814
2815 public final boolean equals(Object o) {
2816 Object k, v; Map.Entry<?,?> e;
2817 return ((o instanceof Map.Entry) &&
2818 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
2819 (v = e.getValue()) != null &&
2820 (k == key || k.equals(key)) &&
2821 (v == val || v.equals(val)));
2822 }
2823
2824 public abstract V setValue(V value);
2825 }
2826
2827 /**
2828 * Entry used by EntryIterator.next(), that relays setValue
2829 * changes to the underlying map.
2830 */
2831 static final class WriteThroughEntry<K,V> extends MapEntry<K,V>
2832 implements Map.Entry<K, V> {
2833 final ConcurrentHashMapV8<K, V> map;
2834 WriteThroughEntry(K key, V val, ConcurrentHashMapV8<K, V> map) {
2835 super(key, val);
2836 this.map = map;
2837 }
2838
2839 /**
2840 * Sets our entry's value and writes through to the map. The
2841 * value to return is somewhat arbitrary here. Since a
2842 * WriteThroughEntry does not necessarily track asynchronous
2843 * changes, the most recent "previous" value could be
2844 * different from what we return (or could even have been
2845 * removed in which case the put will re-establish). We do not
2846 * and cannot guarantee more.
2847 */
2848 public final V setValue(V value) {
2849 if (value == null) throw new NullPointerException();
2850 V v = val;
2851 val = value;
2852 map.put(key, value);
2853 return v;
2854 }
2855 }
2856
2857 /**
2858 * Internal version of entry, that doesn't write though changes
2859 */
2860 static final class SnapshotEntry<K,V> extends MapEntry<K,V>
2861 implements Map.Entry<K, V> {
2862 SnapshotEntry(K key, V val) { super(key, val); }
2863 public final V setValue(V value) { // only locally update
2864 if (value == null) throw new NullPointerException();
2865 V v = val;
2866 val = value;
2867 return v;
2868 }
2869 }
2870
2871 /* ----------------Views -------------- */
2872
2873 /**
2874 * Base class for views. This is done mainly to allow adding
2875 * customized parallel traversals (not yet implemented.)
2876 */
2877 static abstract class MapView<K, V> {
2878 final ConcurrentHashMapV8<K, V> map;
2879 MapView(ConcurrentHashMapV8<K, V> map) { this.map = map; }
2880 public final int size() { return map.size(); }
2881 public final boolean isEmpty() { return map.isEmpty(); }
2882 public final void clear() { map.clear(); }
2883
2884 // implementations below rely on concrete classes supplying these
2885 abstract Iterator<?> iter();
2886 abstract public boolean contains(Object o);
2887 abstract public boolean remove(Object o);
2888
2889 private static final String oomeMsg = "Required array size too large";
2890
2891 public final Object[] toArray() {
2892 long sz = map.longSize();
2893 if (sz > (long)(MAX_ARRAY_SIZE))
2894 throw new OutOfMemoryError(oomeMsg);
2895 int n = (int)sz;
2896 Object[] r = new Object[n];
2897 int i = 0;
2898 Iterator<?> it = iter();
2899 while (it.hasNext()) {
2900 if (i == n) {
2901 if (n >= MAX_ARRAY_SIZE)
2902 throw new OutOfMemoryError(oomeMsg);
2903 if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
2904 n = MAX_ARRAY_SIZE;
2905 else
2906 n += (n >>> 1) + 1;
2907 r = Arrays.copyOf(r, n);
2908 }
2909 r[i++] = it.next();
2910 }
2911 return (i == n) ? r : Arrays.copyOf(r, i);
2912 }
2913
2914 @SuppressWarnings("unchecked")
2915 public final <T> T[] toArray(T[] a) {
2916 long sz = map.longSize();
2917 if (sz > (long)(MAX_ARRAY_SIZE))
2918 throw new OutOfMemoryError(oomeMsg);
2919 int m = (int)sz;
2920 T[] r = (a.length >= m) ? a :
2921 (T[])java.lang.reflect.Array
2922 .newInstance(a.getClass().getComponentType(), m);
2923 int n = r.length;
2924 int i = 0;
2925 Iterator<?> it = iter();
2926 while (it.hasNext()) {
2927 if (i == n) {
2928 if (n >= MAX_ARRAY_SIZE)
2929 throw new OutOfMemoryError(oomeMsg);
2930 if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
2931 n = MAX_ARRAY_SIZE;
2932 else
2933 n += (n >>> 1) + 1;
2934 r = Arrays.copyOf(r, n);
2935 }
2936 r[i++] = (T)it.next();
2937 }
2938 if (a == r && i < n) {
2939 r[i] = null; // null-terminate
2940 return r;
2941 }
2942 return (i == n) ? r : Arrays.copyOf(r, i);
2943 }
2944
2945 public final int hashCode() {
2946 int h = 0;
2947 for (Iterator<?> it = iter(); it.hasNext();)
2948 h += it.next().hashCode();
2949 return h;
2950 }
2951
2952 public final String toString() {
2953 StringBuilder sb = new StringBuilder();
2954 sb.append('[');
2955 Iterator<?> it = iter();
2956 if (it.hasNext()) {
2957 for (;;) {
2958 Object e = it.next();
2959 sb.append(e == this ? "(this Collection)" : e);
2960 if (!it.hasNext())
2961 break;
2962 sb.append(',').append(' ');
2963 }
2964 }
2965 return sb.append(']').toString();
2966 }
2967
2968 public final boolean containsAll(Collection<?> c) {
2969 if (c != this) {
2970 for (Iterator<?> it = c.iterator(); it.hasNext();) {
2971 Object e = it.next();
2972 if (e == null || !contains(e))
2973 return false;
2974 }
2975 }
2976 return true;
2977 }
2978
2979 public final boolean removeAll(Collection<?> c) {
2980 boolean modified = false;
2981 for (Iterator<?> it = iter(); it.hasNext();) {
2982 if (c.contains(it.next())) {
2983 it.remove();
2984 modified = true;
2985 }
2986 }
2987 return modified;
2988 }
2989
2990 public final boolean retainAll(Collection<?> c) {
2991 boolean modified = false;
2992 for (Iterator<?> it = iter(); it.hasNext();) {
2993 if (!c.contains(it.next())) {
2994 it.remove();
2995 modified = true;
2996 }
2997 }
2998 return modified;
2999 }
3000
3001 }
3002
3003 static final class KeySet<K,V> extends MapView<K,V> implements Set<K> {
3004 KeySet(ConcurrentHashMapV8<K, V> map) { super(map); }
3005 public final boolean contains(Object o) { return map.containsKey(o); }
3006 public final boolean remove(Object o) { return map.remove(o) != null; }
3007
3008 public final Iterator<K> iterator() {
3009 return new KeyIterator<K,V>(map);
3010 }
3011 final Iterator<?> iter() {
3012 return new KeyIterator<K,V>(map);
3013 }
3014 public final boolean add(K e) {
3015 throw new UnsupportedOperationException();
3016 }
3017 public final boolean addAll(Collection<? extends K> c) {
3018 throw new UnsupportedOperationException();
3019 }
3020 public boolean equals(Object o) {
3021 Set<?> c;
3022 return ((o instanceof Set) &&
3023 ((c = (Set<?>)o) == this ||
3024 (containsAll(c) && c.containsAll(this))));
3025 }
3026 }
3027
3028 static final class Values<K,V> extends MapView<K,V>
3029 implements Collection<V> {
3030 Values(ConcurrentHashMapV8<K, V> map) { super(map); }
3031 public final boolean contains(Object o) { return map.containsValue(o); }
3032
3033 public final boolean remove(Object o) {
3034 if (o != null) {
3035 Iterator<V> it = new ValueIterator<K,V>(map);
3036 while (it.hasNext()) {
3037 if (o.equals(it.next())) {
3038 it.remove();
3039 return true;
3040 }
3041 }
3042 }
3043 return false;
3044 }
3045 public final Iterator<V> iterator() {
3046 return new ValueIterator<K,V>(map);
3047 }
3048 final Iterator<?> iter() {
3049 return new ValueIterator<K,V>(map);
3050 }
3051 public final boolean add(V e) {
3052 throw new UnsupportedOperationException();
3053 }
3054 public final boolean addAll(Collection<? extends V> c) {
3055 throw new UnsupportedOperationException();
3056 }
3057 }
3058
3059 static final class EntrySet<K,V> extends MapView<K,V>
3060 implements Set<Map.Entry<K,V>> {
3061 EntrySet(ConcurrentHashMapV8<K, V> map) { super(map); }
3062
3063 public final boolean contains(Object o) {
3064 Object k, v, r; Map.Entry<?,?> e;
3065 return ((o instanceof Map.Entry) &&
3066 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3067 (r = map.get(k)) != null &&
3068 (v = e.getValue()) != null &&
3069 (v == r || v.equals(r)));
3070 }
3071
3072 public final boolean remove(Object o) {
3073 Object k, v; Map.Entry<?,?> e;
3074 return ((o instanceof Map.Entry) &&
3075 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3076 (v = e.getValue()) != null &&
3077 map.remove(k, v));
3078 }
3079
3080 public final Iterator<Map.Entry<K,V>> iterator() {
3081 return new EntryIterator<K,V>(map);
3082 }
3083 final Iterator<?> iter() {
3084 return new SnapshotEntryIterator<K,V>(map);
3085 }
3086 public final boolean add(Entry<K,V> e) {
3087 throw new UnsupportedOperationException();
3088 }
3089 public final boolean addAll(Collection<? extends Entry<K,V>> c) {
3090 throw new UnsupportedOperationException();
3091 }
3092 public boolean equals(Object o) {
3093 Set<?> c;
3094 return ((o instanceof Set) &&
3095 ((c = (Set<?>)o) == this ||
3096 (containsAll(c) && c.containsAll(this))));
3097 }
3098 }
3099
3100 /* ---------------- Serialization Support -------------- */
3101
3102 /**
3103 * Stripped-down version of helper class used in previous version,
3104 * declared for the sake of serialization compatibility
3105 */
3106 static class Segment<K,V> implements Serializable {
3107 private static final long serialVersionUID = 2249069246763182397L;
3108 final float loadFactor;
3109 Segment(float lf) { this.loadFactor = lf; }
3110 }
3111
3112 /**
3113 * Saves the state of the {@code ConcurrentHashMapV8} instance to a
3114 * stream (i.e., serializes it).
3115 * @param s the stream
3116 * @serialData
3117 * the key (Object) and value (Object)
3118 * for each key-value mapping, followed by a null pair.
3119 * The key-value mappings are emitted in no particular order.
3120 */
3121 @SuppressWarnings("unchecked")
3122 private void writeObject(java.io.ObjectOutputStream s)
3123 throws java.io.IOException {
3124 if (segments == null) { // for serialization compatibility
3125 segments = (Segment<K,V>[])
3126 new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3127 for (int i = 0; i < segments.length; ++i)
3128 segments[i] = new Segment<K,V>(LOAD_FACTOR);
3129 }
3130 s.defaultWriteObject();
3131 InternalIterator it = new InternalIterator(table);
3132 while (it.next != null) {
3133 s.writeObject(it.nextKey);
3134 s.writeObject(it.nextVal);
3135 it.advance();
3136 }
3137 s.writeObject(null);
3138 s.writeObject(null);
3139 segments = null; // throw away
3140 }
3141
3142 /**
3143 * Reconstitutes the instance from a stream (that is, deserializes it).
3144 * @param s the stream
3145 */
3146 @SuppressWarnings("unchecked")
3147 private void readObject(java.io.ObjectInputStream s)
3148 throws java.io.IOException, ClassNotFoundException {
3149 s.defaultReadObject();
3150 this.segments = null; // unneeded
3151 // initialize transient final field
3152 UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
3153
3154 // Create all nodes, then place in table once size is known
3155 long size = 0L;
3156 Node p = null;
3157 for (;;) {
3158 K k = (K) s.readObject();
3159 V v = (V) s.readObject();
3160 if (k != null && v != null) {
3161 int h = spread(k.hashCode());
3162 p = new Node(h, k, v, p);
3163 ++size;
3164 }
3165 else
3166 break;
3167 }
3168 if (p != null) {
3169 boolean init = false;
3170 int n;
3171 if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3172 n = MAXIMUM_CAPACITY;
3173 else {
3174 int sz = (int)size;
3175 n = tableSizeFor(sz + (sz >>> 1) + 1);
3176 }
3177 int sc = sizeCtl;
3178 boolean collide = false;
3179 if (n > sc &&
3180 UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3181 try {
3182 if (table == null) {
3183 init = true;
3184 Node[] tab = new Node[n];
3185 int mask = n - 1;
3186 while (p != null) {
3187 int j = p.hash & mask;
3188 Node next = p.next;
3189 Node q = p.next = tabAt(tab, j);
3190 setTabAt(tab, j, p);
3191 if (!collide && q != null && q.hash == p.hash)
3192 collide = true;
3193 p = next;
3194 }
3195 table = tab;
3196 counter.add(size);
3197 sc = n - (n >>> 2);
3198 }
3199 } finally {
3200 sizeCtl = sc;
3201 }
3202 if (collide) { // rescan and convert to TreeBins
3203 Node[] tab = table;
3204 for (int i = 0; i < tab.length; ++i) {
3205 int c = 0;
3206 for (Node e = tabAt(tab, i); e != null; e = e.next) {
3207 if (++c > TREE_THRESHOLD &&
3208 (e.key instanceof Comparable)) {
3209 replaceWithTreeBin(tab, i, e.key);
3210 break;
3211 }
3212 }
3213 }
3214 }
3215 }
3216 if (!init) { // Can only happen if unsafely published.
3217 while (p != null) {
3218 internalPut(p.key, p.val);
3219 p = p.next;
3220 }
3221 }
3222
3223 }
3224 }
3225
3226 // Unsafe mechanics
3227 private static final sun.misc.Unsafe UNSAFE;
3228 private static final long counterOffset;
3229 private static final long sizeCtlOffset;
3230 private static final long ABASE;
3231 private static final int ASHIFT;
3232
3233 static {
3234 int ss;
3235 try {
3236 UNSAFE = getUnsafe();
3237 Class<?> k = ConcurrentHashMapV8.class;
3238 counterOffset = UNSAFE.objectFieldOffset
3239 (k.getDeclaredField("counter"));
3240 sizeCtlOffset = UNSAFE.objectFieldOffset
3241 (k.getDeclaredField("sizeCtl"));
3242 Class<?> sc = Node[].class;
3243 ABASE = UNSAFE.arrayBaseOffset(sc);
3244 ss = UNSAFE.arrayIndexScale(sc);
3245 } catch (Exception e) {
3246 throw new Error(e);
3247 }
3248 if ((ss & (ss-1)) != 0)
3249 throw new Error("data type scale not a power of two");
3250 ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
3251 }
3252
3253 /**
3254 * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
3255 * Replace with a simple call to Unsafe.getUnsafe when integrating
3256 * into a jdk.
3257 *
3258 * @return a sun.misc.Unsafe
3259 */
3260 private static sun.misc.Unsafe getUnsafe() {
3261 try {
3262 return sun.misc.Unsafe.getUnsafe();
3263 } catch (SecurityException se) {
3264 try {
3265 return java.security.AccessController.doPrivileged
3266 (new java.security
3267 .PrivilegedExceptionAction<sun.misc.Unsafe>() {
3268 public sun.misc.Unsafe run() throws Exception {
3269 java.lang.reflect.Field f = sun.misc
3270 .Unsafe.class.getDeclaredField("theUnsafe");
3271 f.setAccessible(true);
3272 return (sun.misc.Unsafe) f.get(null);
3273 }});
3274 } catch (java.security.PrivilegedActionException e) {
3275 throw new RuntimeException("Could not initialize intrinsics",
3276 e.getCause());
3277 }
3278 }
3279 }
3280
3281 }