ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ConcurrentHashMapV8.java
(Generate patch)

Comparing jsr166/src/jsr166e/ConcurrentHashMapV8.java (file contents):
Revision 1.10 by dl, Tue Aug 30 16:03:48 2011 UTC vs.
Revision 1.51 by jsr166, Wed Jul 18 01:30:54 2012 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines