ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
(Generate patch)

Comparing jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java (file contents):
Revision 1.138 by dl, Tue Oct 30 14:23:07 2012 UTC vs.
Revision 1.252 by dl, Sun Dec 1 13:38:58 2013 UTC

# Line 5 | Line 5
5   */
6  
7   package java.util.concurrent;
8 import java.util.concurrent.atomic.LongAdder;
9 import java.util.concurrent.ForkJoinPool;
10 import java.util.concurrent.ForkJoinTask;
8  
9 < import java.util.Comparator;
9 > import java.io.ObjectStreamField;
10 > import java.io.Serializable;
11 > import java.lang.reflect.ParameterizedType;
12 > import java.lang.reflect.Type;
13 > import java.util.AbstractMap;
14   import java.util.Arrays;
14 import java.util.Map;
15 import java.util.Set;
15   import java.util.Collection;
16 < import java.util.AbstractMap;
17 < import java.util.AbstractSet;
19 < import java.util.AbstractCollection;
20 < import java.util.Hashtable;
16 > import java.util.Comparator;
17 > import java.util.Enumeration;
18   import java.util.HashMap;
19 + import java.util.Hashtable;
20   import java.util.Iterator;
21 < import java.util.Enumeration;
24 < import java.util.ConcurrentModificationException;
21 > import java.util.Map;
22   import java.util.NoSuchElementException;
23 + import java.util.Set;
24 + import java.util.Spliterator;
25   import java.util.concurrent.ConcurrentMap;
26 < import java.util.concurrent.ThreadLocalRandom;
28 < import java.util.concurrent.locks.LockSupport;
29 < import java.util.concurrent.locks.AbstractQueuedSynchronizer;
26 > import java.util.concurrent.ForkJoinPool;
27   import java.util.concurrent.atomic.AtomicReference;
28 <
29 < import java.io.Serializable;
28 > import java.util.concurrent.locks.LockSupport;
29 > import java.util.concurrent.locks.ReentrantLock;
30 > import java.util.function.BiConsumer;
31 > import java.util.function.BiFunction;
32 > import java.util.function.BinaryOperator;
33 > import java.util.function.Consumer;
34 > import java.util.function.DoubleBinaryOperator;
35 > import java.util.function.Function;
36 > import java.util.function.IntBinaryOperator;
37 > import java.util.function.LongBinaryOperator;
38 > import java.util.function.ToDoubleBiFunction;
39 > import java.util.function.ToDoubleFunction;
40 > import java.util.function.ToIntBiFunction;
41 > import java.util.function.ToIntFunction;
42 > import java.util.function.ToLongBiFunction;
43 > import java.util.function.ToLongFunction;
44 > import java.util.stream.Stream;
45  
46   /**
47   * A hash table supporting full concurrency of retrievals and
# Line 43 | Line 55 | import java.io.Serializable;
55   * interoperable with {@code Hashtable} in programs that rely on its
56   * thread safety but not on its synchronization details.
57   *
58 < * <p> Retrieval operations (including {@code get}) generally do not
58 > * <p>Retrieval operations (including {@code get}) generally do not
59   * block, so may overlap with update operations (including {@code put}
60   * and {@code remove}). Retrievals reflect the results of the most
61   * recently <em>completed</em> update operations holding upon their
# Line 52 | Line 64 | import java.io.Serializable;
64   * that key reporting the updated value.)  For aggregate operations
65   * such as {@code putAll} and {@code clear}, concurrent retrievals may
66   * reflect insertion or removal of only some entries.  Similarly,
67 < * Iterators and Enumerations return elements reflecting the state of
68 < * the hash table at some point at or since the creation of the
67 > * Iterators, Spliterators and Enumerations return elements reflecting the
68 > * state of the hash table at some point at or since the creation of the
69   * iterator/enumeration.  They do <em>not</em> throw {@link
70 < * ConcurrentModificationException}.  However, iterators are designed
71 < * to be used by only one thread at a time.  Bear in mind that the
72 < * results of aggregate status methods including {@code size}, {@code
73 < * isEmpty}, and {@code containsValue} are typically useful only when
74 < * a map is not undergoing concurrent updates in other threads.
70 > * java.util.ConcurrentModificationException ConcurrentModificationException}.
71 > * However, iterators are designed to be used by only one thread at a time.
72 > * Bear in mind that the results of aggregate status methods including
73 > * {@code size}, {@code isEmpty}, and {@code containsValue} are typically
74 > * useful only when a map is not undergoing concurrent updates in other threads.
75   * Otherwise the results of these methods reflect transient states
76   * that may be adequate for monitoring or estimation purposes, but not
77   * for program control.
78   *
79 < * <p> The table is dynamically expanded when there are too many
79 > * <p>The table is dynamically expanded when there are too many
80   * collisions (i.e., keys that have distinct hash codes but fall into
81   * the same slot modulo the table size), with the expected average
82   * effect of maintaining roughly two bins per mapping (corresponding
# Line 83 | Line 95 | import java.io.Serializable;
95   * expected {@code concurrencyLevel} as an additional hint for
96   * internal sizing.  Note that using many keys with exactly the same
97   * {@code hashCode()} is a sure way to slow down performance of any
98 < * hash table.
98 > * hash table. To ameliorate impact, when keys are {@link Comparable},
99 > * this class may use comparison order among keys to help break ties.
100   *
101 < * <p> A {@link Set} projection of a ConcurrentHashMap may be created
101 > * <p>A {@link Set} projection of a ConcurrentHashMap may be created
102   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
103   * (using {@link #keySet(Object)} when only keys are of interest, and the
104   * mapped values are (perhaps transiently) not used or all take the
105   * same mapping value.
106   *
107 < * <p> A ConcurrentHashMap can be used as scalable frequency map (a
108 < * form of histogram or multiset) by using {@link LongAdder} values
109 < * and initializing via {@link #computeIfAbsent}. For example, to add
110 < * a count to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you
111 < * can use {@code freqs.computeIfAbsent(k -> new
112 < * LongAdder()).increment();}
107 > * <p>A ConcurrentHashMap can be used as scalable frequency map (a
108 > * form of histogram or multiset) by using {@link
109 > * java.util.concurrent.atomic.LongAdder} values and initializing via
110 > * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count
111 > * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
112 > * {@code freqs.computeIfAbsent(k -> new LongAdder()).increment();}
113   *
114   * <p>This class and its views and iterators implement all of the
115   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
116   * interfaces.
117   *
118 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
118 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
119   * does <em>not</em> allow {@code null} to be used as a key or value.
120   *
121 < * <p>ConcurrentHashMaps support parallel operations using the {@link
122 < * ForkJoinPool#commonPool}. (Task that may be used in other contexts
123 < * are available in class {@link ForkJoinTasks}). These operations are
124 < * designed to be safely, and often sensibly, applied even with maps
125 < * that are being concurrently updated by other threads; for example,
126 < * when computing a snapshot summary of the values in a shared
127 < * registry.  There are three kinds of operation, each with four
128 < * forms, accepting functions with Keys, Values, Entries, and (Key,
129 < * Value) arguments and/or return values. Because the elements of a
130 < * ConcurrentHashMap are not ordered in any particular way, and may be
131 < * processed in different orders in different parallel executions, the
132 < * correctness of supplied functions should not depend on any
133 < * ordering, or on any other objects or values that may transiently
134 < * change while computation is in progress; and except for forEach
135 < * actions, should ideally be side-effect-free.
121 > * <p>ConcurrentHashMaps support a set of sequential and parallel bulk
122 > * operations that, unlike most {@link Stream} methods, are designed
123 > * to be safely, and often sensibly, applied even with maps that are
124 > * being concurrently updated by other threads; for example, when
125 > * computing a snapshot summary of the values in a shared registry.
126 > * There are three kinds of operation, each with four forms, accepting
127 > * functions with Keys, Values, Entries, and (Key, Value) arguments
128 > * and/or return values. Because the elements of a ConcurrentHashMap
129 > * are not ordered in any particular way, and may be processed in
130 > * different orders in different parallel executions, the correctness
131 > * of supplied functions should not depend on any ordering, or on any
132 > * other objects or values that may transiently change while
133 > * computation is in progress; and except for forEach actions, should
134 > * ideally be side-effect-free. Bulk operations on {@link java.util.Map.Entry}
135 > * objects do not support method {@code setValue}.
136   *
137   * <ul>
138   * <li> forEach: Perform a given action on each element.
# Line 146 | Line 159 | import java.io.Serializable;
159   * <li> Reductions to scalar doubles, longs, and ints, using a
160   * given basis value.</li>
161   *
149 * </li>
162   * </ul>
163 + * </li>
164   * </ul>
165   *
166 + * <p>These bulk operations accept a {@code parallelismThreshold}
167 + * argument. Methods proceed sequentially if the current map size is
168 + * estimated to be less than the given threshold. Using a value of
169 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
170 + * of {@code 1} results in maximal parallelism by partitioning into
171 + * enough subtasks to fully utilize the {@link
172 + * ForkJoinPool#commonPool()} that is used for all parallel
173 + * computations. Normally, you would initially choose one of these
174 + * extreme values, and then measure performance of using in-between
175 + * values that trade off overhead versus throughput.
176 + *
177   * <p>The concurrency properties of bulk operations follow
178   * from those of ConcurrentHashMap: Any non-null result returned
179   * from {@code get(key)} and related access methods bears a
# Line 185 | Line 209 | import java.io.Serializable;
209   * arguments can be supplied using {@code new
210   * AbstractMap.SimpleEntry(k,v)}.
211   *
212 < * <p> Bulk operations may complete abruptly, throwing an
212 > * <p>Bulk operations may complete abruptly, throwing an
213   * exception encountered in the application of a supplied
214   * function. Bear in mind when handling such exceptions that other
215   * concurrently executing functions could also have thrown
216   * exceptions, or would have done so if the first exception had
217   * not occurred.
218   *
219 < * <p>Parallel speedups for bulk operations compared to sequential
220 < * processing are common but not guaranteed.  Operations involving
221 < * brief functions on small maps may execute more slowly than
222 < * sequential loops if the underlying work to parallelize the
223 < * computation is more expensive than the computation
224 < * itself. Similarly, parallelization may not lead to much actual
225 < * parallelism if all processors are busy performing unrelated tasks.
219 > * <p>Speedups for parallel compared to sequential forms are common
220 > * but not guaranteed.  Parallel operations involving brief functions
221 > * on small maps may execute more slowly than sequential forms if the
222 > * underlying work to parallelize the computation is more expensive
223 > * than the computation itself.  Similarly, parallelization may not
224 > * lead to much actual parallelism if all processors are busy
225 > * performing unrelated tasks.
226   *
227 < * <p> All arguments to all task methods must be non-null.
204 < *
205 < * <p><em>jsr166e note: During transition, this class
206 < * uses nested functional interfaces with different names but the
207 < * same forms as those expected for JDK8.<em>
227 > * <p>All arguments to all task methods must be non-null.
228   *
229   * <p>This class is a member of the
230   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
# Line 215 | Line 235 | import java.io.Serializable;
235   * @param <K> the type of keys maintained by this map
236   * @param <V> the type of mapped values
237   */
238 < public class ConcurrentHashMap<K, V>
239 <    implements ConcurrentMap<K, V>, Serializable {
238 > public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
239 >    implements ConcurrentMap<K,V>, Serializable {
240      private static final long serialVersionUID = 7249069246763182397L;
241  
222    /**
223     * A partitionable iterator. A Spliterator can be traversed
224     * directly, but can also be partitioned (before traversal) by
225     * creating another Spliterator that covers a non-overlapping
226     * portion of the elements, and so may be amenable to parallel
227     * execution.
228     *
229     * <p> This interface exports a subset of expected JDK8
230     * functionality.
231     *
232     * <p>Sample usage: Here is one (of the several) ways to compute
233     * the sum of the values held in a map using the ForkJoin
234     * framework. As illustrated here, Spliterators are well suited to
235     * designs in which a task repeatedly splits off half its work
236     * into forked subtasks until small enough to process directly,
237     * and then joins these subtasks. Variants of this style can also
238     * be used in completion-based designs.
239     *
240     * <pre>
241     * {@code ConcurrentHashMap<String, Long> m = ...
242     * // split as if have 8 * parallelism, for load balance
243     * int n = m.size();
244     * int p = aForkJoinPool.getParallelism() * 8;
245     * int split = (n < p)? n : p;
246     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
247     * // ...
248     * static class SumValues extends RecursiveTask<Long> {
249     *   final Spliterator<Long> s;
250     *   final int split;             // split while > 1
251     *   final SumValues nextJoin;    // records forked subtasks to join
252     *   SumValues(Spliterator<Long> s, int depth, SumValues nextJoin) {
253     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
254     *   }
255     *   public Long compute() {
256     *     long sum = 0;
257     *     SumValues subtasks = null; // fork subtasks
258     *     for (int s = split >>> 1; s > 0; s >>>= 1)
259     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
260     *     while (s.hasNext())        // directly process remaining elements
261     *       sum += s.next();
262     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
263     *       sum += t.join();         // collect subtask results
264     *     return sum;
265     *   }
266     * }
267     * }</pre>
268     */
269    public static interface Spliterator<T> extends Iterator<T> {
270        /**
271         * Returns a Spliterator covering approximately half of the
272         * elements, guaranteed not to overlap with those subsequently
273         * returned by this Spliterator.  After invoking this method,
274         * the current Spliterator will <em>not</em> produce any of
275         * the elements of the returned Spliterator, but the two
276         * Spliterators together will produce all of the elements that
277         * would have been produced by this Spliterator had this
278         * method not been called. The exact number of elements
279         * produced by the returned Spliterator is not guaranteed, and
280         * may be zero (i.e., with {@code hasNext()} reporting {@code
281         * false}) if this Spliterator cannot be further split.
282         *
283         * @return a Spliterator covering approximately half of the
284         * elements
285         * @throws IllegalStateException if this Spliterator has
286         * already commenced traversing elements
287         */
288        Spliterator<T> split();
289    }
290
291    /**
292     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
293     * which additions may optionally be enabled by mapping to a
294     * common value.  This class cannot be directly instantiated. See
295     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
296     * {@link #newKeySet(int)}.
297     *
298     * <p>The view's {@code iterator} is a "weakly consistent" iterator
299     * that will never throw {@link ConcurrentModificationException},
300     * and guarantees to traverse elements as they existed upon
301     * construction of the iterator, and may (but is not guaranteed to)
302     * reflect any modifications subsequent to construction.
303     */
304    public static class KeySetView<K,V> extends CHMView<K,V> implements Set<K>, java.io.Serializable {
305        private static final long serialVersionUID = 7249069246763182397L;
306        private final V value;
307        KeySetView(ConcurrentHashMap<K, V> map, V value) {  // non-public
308            super(map);
309            this.value = value;
310        }
311
312        /**
313         * Returns the map backing this view.
314         *
315         * @return the map backing this view
316         */
317        public ConcurrentHashMap<K,V> getMap() { return map; }
318
319        /**
320         * Returns the default mapped value for additions,
321         * or {@code null} if additions are not supported.
322         *
323         * @return the default mapped value for additions, or {@code null}
324         * if not supported.
325         */
326        public V getMappedValue() { return value; }
327
328        // implement Set API
329
330        public boolean contains(Object o) { return map.containsKey(o); }
331        public boolean remove(Object o)   { return map.remove(o) != null; }
332        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
333        public boolean add(K e) {
334            V v;
335            if ((v = value) == null)
336                throw new UnsupportedOperationException();
337            if (e == null)
338                throw new NullPointerException();
339            return map.internalPutIfAbsent(e, v) == null;
340        }
341        public boolean addAll(Collection<? extends K> c) {
342            boolean added = false;
343            V v;
344            if ((v = value) == null)
345                throw new UnsupportedOperationException();
346            for (K e : c) {
347                if (e == null)
348                    throw new NullPointerException();
349                if (map.internalPutIfAbsent(e, v) == null)
350                    added = true;
351            }
352            return added;
353        }
354        public boolean equals(Object o) {
355            Set<?> c;
356            return ((o instanceof Set) &&
357                    ((c = (Set<?>)o) == this ||
358                     (containsAll(c) && c.containsAll(this))));
359        }
360    }
361
242      /*
243       * Overview:
244       *
# Line 369 | Line 249 | public class ConcurrentHashMap<K, V>
249       * the same or better than java.util.HashMap, and to support high
250       * initial insertion rates on an empty table by many threads.
251       *
252 <     * Each key-value mapping is held in a Node.  Because Node fields
253 <     * can contain special values, they are defined using plain Object
254 <     * types. Similarly in turn, all internal methods that use them
255 <     * work off Object types. And similarly, so do the internal
256 <     * methods of auxiliary iterator and view classes.  All public
257 <     * generic typed methods relay in/out of these internal methods,
258 <     * supplying null-checks and casts as needed. This also allows
259 <     * many of the public methods to be factored into a smaller number
260 <     * of internal methods (although sadly not so for the five
261 <     * variants of put-related operations). The validation-based
262 <     * approach explained below leads to a lot of code sprawl because
263 <     * retry-control precludes factoring into smaller methods.
252 >     * This map usually acts as a binned (bucketed) hash table.  Each
253 >     * key-value mapping is held in a Node.  Most nodes are instances
254 >     * of the basic Node class with hash, key, value, and next
255 >     * fields. However, various subclasses exist: TreeNodes are
256 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
257 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
258 >     * of bins during resizing. ReservationNodes are used as
259 >     * placeholders while establishing values in computeIfAbsent and
260 >     * related methods.  The types TreeBin, ForwardingNode, and
261 >     * ReservationNode do not hold normal user keys, values, or
262 >     * hashes, and are readily distinguishable during search etc
263 >     * because they have negative hash fields and null key and value
264 >     * fields. (These special nodes are either uncommon or transient,
265 >     * so the impact of carrying around some unused fields is
266 >     * insignificant.)
267       *
268       * The table is lazily initialized to a power-of-two size upon the
269       * first insertion.  Each bin in the table normally contains a
# Line 388 | Line 271 | public class ConcurrentHashMap<K, V>
271       * Table accesses require volatile/atomic reads, writes, and
272       * CASes.  Because there is no other way to arrange this without
273       * adding further indirections, we use intrinsics
274 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
275 <     * are always accurately traversable under volatile reads, so long
276 <     * as lookups check hash code and non-nullness of value before
277 <     * checking key equality.
278 <     *
279 <     * We use the top two bits of Node hash fields for control
397 <     * purposes -- they are available anyway because of addressing
398 <     * constraints.  As explained further below, these top bits are
399 <     * used as follows:
400 <     *  00 - Normal
401 <     *  01 - Locked
402 <     *  11 - Locked and may have a thread waiting for lock
403 <     *  10 - Node is a forwarding node
404 <     *
405 <     * The lower 30 bits of each Node's hash field contain a
406 <     * transformation of the key's hash code, except for forwarding
407 <     * nodes, for which the lower bits are zero (and so always have
408 <     * hash field == MOVED).
274 >     * (sun.misc.Unsafe) operations.
275 >     *
276 >     * We use the top (sign) bit of Node hash fields for control
277 >     * purposes -- it is available anyway because of addressing
278 >     * constraints.  Nodes with negative hash fields are specially
279 >     * handled or ignored in map methods.
280       *
281       * Insertion (via put or its variants) of the first node in an
282       * empty bin is performed by just CASing it to the bin.  This is
# Line 414 | Line 285 | public class ConcurrentHashMap<K, V>
285       * delete, and replace) require locks.  We do not want to waste
286       * the space required to associate a distinct lock object with
287       * each bin, so instead use the first node of a bin list itself as
288 <     * a lock. Blocking support for these locks relies on the builtin
289 <     * "synchronized" monitors.  However, we also need a tryLock
419 <     * construction, so we overlay these by using bits of the Node
420 <     * hash field for lock control (see above), and so normally use
421 <     * builtin monitors only for blocking and signalling using
422 <     * wait/notifyAll constructions. See Node.tryAwaitLock.
288 >     * a lock. Locking support for these locks relies on builtin
289 >     * "synchronized" monitors.
290       *
291       * Using the first node of a list as a lock does not by itself
292       * suffice though: When a node is locked, any update must first
293       * validate that it is still the first node after locking it, and
294       * retry if not. Because new nodes are always appended to lists,
295       * once a node is first in a bin, it remains first until deleted
296 <     * or the bin becomes invalidated (upon resizing).  However,
430 <     * operations that only conditionally update may inspect nodes
431 <     * until the point of update. This is a converse of sorts to the
432 <     * lazy locking technique described by Herlihy & Shavit.
296 >     * or the bin becomes invalidated (upon resizing).
297       *
298       * The main disadvantage of per-bin locks is that other update
299       * operations on other nodes in a bin list protected by the same
# Line 462 | Line 326 | public class ConcurrentHashMap<K, V>
326       * sometimes deviate significantly from uniform randomness.  This
327       * includes the case when N > (1<<30), so some keys MUST collide.
328       * Similarly for dumb or hostile usages in which multiple keys are
329 <     * designed to have identical hash codes. Also, although we guard
330 <     * against the worst effects of this (see method spread), sets of
331 <     * hashes may differ only in bits that do not impact their bin
332 <     * index for a given power-of-two mask.  So we use a secondary
333 <     * strategy that applies when the number of nodes in a bin exceeds
334 <     * a threshold, and at least one of the keys implements
471 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
472 <     * (a specialized form of red-black trees), bounding search time
473 <     * to O(log N).  Each search step in a TreeBin is around twice as
329 >     * designed to have identical hash codes or ones that differs only
330 >     * in masked-out high bits. So we use a secondary strategy that
331 >     * applies when the number of nodes in a bin exceeds a
332 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
333 >     * specialized form of red-black trees), bounding search time to
334 >     * O(log N).  Each search step in a TreeBin is at least twice as
335       * slow as in a regular list, but given that N cannot exceed
336       * (1<<64) (before running out of addresses) this bounds search
337       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 481 | Line 342 | public class ConcurrentHashMap<K, V>
342       * iterators in the same way.
343       *
344       * The table is resized when occupancy exceeds a percentage
345 <     * threshold (nominally, 0.75, but see below).  Only a single
346 <     * thread performs the resize (using field "sizeCtl", to arrange
347 <     * exclusion), but the table otherwise remains usable for reads
348 <     * and updates. Resizing proceeds by transferring bins, one by
349 <     * one, from the table to the next table.  Because we are using
350 <     * power-of-two expansion, the elements from each bin must either
351 <     * stay at same index, or move with a power of two offset. We
352 <     * eliminate unnecessary node creation by catching cases where old
353 <     * nodes can be reused because their next fields won't change.  On
354 <     * average, only about one-sixth of them need cloning when a table
355 <     * doubles. The nodes they replace will be garbage collectable as
356 <     * soon as they are no longer referenced by any reader thread that
357 <     * may be in the midst of concurrently traversing table.  Upon
358 <     * transfer, the old table bin contains only a special forwarding
359 <     * node (with hash field "MOVED") that contains the next table as
360 <     * its key. On encountering a forwarding node, access and update
361 <     * operations restart, using the new table.
362 <     *
363 <     * Each bin transfer requires its bin lock. However, unlike other
364 <     * cases, a transfer can skip a bin if it fails to acquire its
365 <     * lock, and revisit it later (unless it is a TreeBin). Method
366 <     * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
367 <     * have been skipped because of failure to acquire a lock, and
368 <     * blocks only if none are available (i.e., only very rarely).
369 <     * The transfer operation must also ensure that all accessible
370 <     * bins in both the old and new table are usable by any traversal.
371 <     * When there are no lock acquisition failures, this is arranged
372 <     * simply by proceeding from the last bin (table.length - 1) up
373 <     * towards the first.  Upon seeing a forwarding node, traversals
374 <     * (see class Iter) arrange to move to the new table
375 <     * without revisiting nodes.  However, when any node is skipped
376 <     * during a transfer, all earlier table bins may have become
377 <     * visible, so are initialized with a reverse-forwarding node back
378 <     * to the old table until the new ones are established. (This
379 <     * sometimes requires transiently locking a forwarding node, which
380 <     * is possible under the above encoding.) These more expensive
381 <     * mechanics trigger only when necessary.
345 >     * threshold (nominally, 0.75, but see below).  Any thread
346 >     * noticing an overfull bin may assist in resizing after the
347 >     * initiating thread allocates and sets up the replacement array.
348 >     * However, rather than stalling, these other threads may proceed
349 >     * with insertions etc.  The use of TreeBins shields us from the
350 >     * worst case effects of overfilling while resizes are in
351 >     * progress.  Resizing proceeds by transferring bins, one by one,
352 >     * from the table to the next table. However, threads claim small
353 >     * blocks of indices to transfer (via field transferIndex) before
354 >     * doing so, reducing contention.  A generation stamp in field
355 >     * sizeCtl ensures that resizings do not overlap. Because we are
356 >     * using power-of-two expansion, the elements from each bin must
357 >     * either stay at same index, or move with a power of two
358 >     * offset. We eliminate unnecessary node creation by catching
359 >     * cases where old nodes can be reused because their next fields
360 >     * won't change.  On average, only about one-sixth of them need
361 >     * cloning when a table doubles. The nodes they replace will be
362 >     * garbage collectable as soon as they are no longer referenced by
363 >     * any reader thread that may be in the midst of concurrently
364 >     * traversing table.  Upon transfer, the old table bin contains
365 >     * only a special forwarding node (with hash field "MOVED") that
366 >     * contains the next table as its key. On encountering a
367 >     * forwarding node, access and update operations restart, using
368 >     * the new table.
369 >     *
370 >     * Each bin transfer requires its bin lock, which can stall
371 >     * waiting for locks while resizing. However, because other
372 >     * threads can join in and help resize rather than contend for
373 >     * locks, average aggregate waits become shorter as resizing
374 >     * progresses.  The transfer operation must also ensure that all
375 >     * accessible bins in both the old and new table are usable by any
376 >     * traversal.  This is arranged in part by proceeding from the
377 >     * last bin (table.length - 1) up towards the first.  Upon seeing
378 >     * a forwarding node, traversals (see class Traverser) arrange to
379 >     * move to the new table without revisiting nodes.  To ensure that
380 >     * no intervening nodes are skipped even when moved out of order,
381 >     * a stack (see class TableStack) is created on first encounter of
382 >     * a forwarding node during a traversal, to maintain its place if
383 >     * later processing the current table. The need for these
384 >     * save/restore mechanics is relatively rare, but when one
385 >     * forwarding node is encountered, typically many more will be.
386 >     * So Traversers use a simple caching scheme to avoid creating so
387 >     * many new TableStack nodes. (Thanks to Peter Levart for
388 >     * suggesting use of a stack here.)
389       *
390       * The traversal scheme also applies to partial traversals of
391       * ranges of bins (via an alternate Traverser constructor)
# Line 532 | Line 400 | public class ConcurrentHashMap<K, V>
400       * These cases attempt to override the initial capacity settings,
401       * but harmlessly fail to take effect in cases of races.
402       *
403 <     * The element count is maintained using a LongAdder, which avoids
404 <     * contention on updates but can encounter cache thrashing if read
405 <     * too frequently during concurrent access. To avoid reading so
406 <     * often, resizing is attempted either when a bin lock is
407 <     * contended, or upon adding to a bin already holding two or more
408 <     * nodes (checked before adding in the xIfAbsent methods, after
409 <     * adding in others). Under uniform hash distributions, the
410 <     * probability of this occurring at threshold is around 13%,
411 <     * meaning that only about 1 in 8 puts check threshold (and after
412 <     * resizing, many fewer do so). But this approximation has high
413 <     * variance for small table sizes, so we check on any collision
414 <     * for sizes <= 64. The bulk putAll operation further reduces
415 <     * contention by only committing count updates upon these size
416 <     * checks.
403 >     * The element count is maintained using a specialization of
404 >     * LongAdder. We need to incorporate a specialization rather than
405 >     * just use a LongAdder in order to access implicit
406 >     * contention-sensing that leads to creation of multiple
407 >     * CounterCells.  The counter mechanics avoid contention on
408 >     * updates but can encounter cache thrashing if read too
409 >     * frequently during concurrent access. To avoid reading so often,
410 >     * resizing under contention is attempted only upon adding to a
411 >     * bin already holding two or more nodes. Under uniform hash
412 >     * distributions, the probability of this occurring at threshold
413 >     * is around 13%, meaning that only about 1 in 8 puts check
414 >     * threshold (and after resizing, many fewer do so).
415 >     *
416 >     * TreeBins use a special form of comparison for search and
417 >     * related operations (which is the main reason we cannot use
418 >     * existing collections such as TreeMaps). TreeBins contain
419 >     * Comparable elements, but may contain others, as well as
420 >     * elements that are Comparable but not necessarily Comparable for
421 >     * the same T, so we cannot invoke compareTo among them. To handle
422 >     * this, the tree is ordered primarily by hash value, then by
423 >     * Comparable.compareTo order if applicable.  On lookup at a node,
424 >     * if elements are not comparable or compare as 0 then both left
425 >     * and right children may need to be searched in the case of tied
426 >     * hash values. (This corresponds to the full list search that
427 >     * would be necessary if all elements were non-Comparable and had
428 >     * tied hashes.) On insertion, to keep a total ordering (or as
429 >     * close as is required here) across rebalancings, we compare
430 >     * classes and identityHashCodes as tie-breakers. The red-black
431 >     * balancing code is updated from pre-jdk-collections
432 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
433 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
434 >     * Algorithms" (CLR).
435 >     *
436 >     * TreeBins also require an additional locking mechanism.  While
437 >     * list traversal is always possible by readers even during
438 >     * updates, tree traversal is not, mainly because of tree-rotations
439 >     * that may change the root node and/or its linkages.  TreeBins
440 >     * include a simple read-write lock mechanism parasitic on the
441 >     * main bin-synchronization strategy: Structural adjustments
442 >     * associated with an insertion or removal are already bin-locked
443 >     * (and so cannot conflict with other writers) but must wait for
444 >     * ongoing readers to finish. Since there can be only one such
445 >     * waiter, we use a simple scheme using a single "waiter" field to
446 >     * block writers.  However, readers need never block.  If the root
447 >     * lock is held, they proceed along the slow traversal path (via
448 >     * next-pointers) until the lock becomes available or the list is
449 >     * exhausted, whichever comes first. These cases are not fast, but
450 >     * maximize aggregate expected throughput.
451       *
452       * Maintaining API and serialization compatibility with previous
453       * versions of this class introduces several oddities. Mainly: We
# Line 555 | Line 457 | public class ConcurrentHashMap<K, V>
457       * time that we can guarantee to honor it.) We also declare an
458       * unused "Segment" class that is instantiated in minimal form
459       * only when serializing.
460 +     *
461 +     * Also, solely for compatibility with previous versions of this
462 +     * class, it extends AbstractMap, even though all of its methods
463 +     * are overridden, so it is just useless baggage.
464 +     *
465 +     * This file is organized to make things a little easier to follow
466 +     * while reading than they might otherwise: First the main static
467 +     * declarations and utilities, then fields, then main public
468 +     * methods (with a few factorings of multiple public methods into
469 +     * internal ones), then sizing methods, trees, traversers, and
470 +     * bulk operations.
471       */
472  
473      /* ---------------- Constants -------------- */
# Line 596 | Line 509 | public class ConcurrentHashMap<K, V>
509      private static final float LOAD_FACTOR = 0.75f;
510  
511      /**
512 <     * The buffer size for skipped bins during transfers. The
513 <     * value is arbitrary but should be large enough to avoid
514 <     * most locking stalls during resizes.
512 >     * The bin count threshold for using a tree rather than list for a
513 >     * bin.  Bins are converted to trees when adding an element to a
514 >     * bin with at least this many nodes. The value must be greater
515 >     * than 2, and should be at least 8 to mesh with assumptions in
516 >     * tree removal about conversion back to plain bins upon
517 >     * shrinkage.
518       */
519 <    private static final int TRANSFER_BUFFER_SIZE = 32;
519 >    static final int TREEIFY_THRESHOLD = 8;
520  
521      /**
522 <     * The bin count threshold for using a tree rather than list for a
523 <     * bin.  The value reflects the approximate break-even point for
524 <     * using tree-based operations.
522 >     * The bin count threshold for untreeifying a (split) bin during a
523 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
524 >     * most 6 to mesh with shrinkage detection under removal.
525       */
526 <    private static final int TREE_THRESHOLD = 8;
526 >    static final int UNTREEIFY_THRESHOLD = 6;
527  
528 <    /*
529 <     * Encodings for special uses of Node hash fields. See above for
530 <     * explanation.
528 >    /**
529 >     * The smallest table capacity for which bins may be treeified.
530 >     * (Otherwise the table is resized if too many nodes in a bin.)
531 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
532 >     * conflicts between resizing and treeification thresholds.
533       */
534 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
617 <    static final int LOCKED    = 0x40000000; // set/tested only as a bit
618 <    static final int WAITING   = 0xc0000000; // both bits set/tested together
619 <    static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
620 <
621 <    /* ---------------- Fields -------------- */
534 >    static final int MIN_TREEIFY_CAPACITY = 64;
535  
536      /**
537 <     * The array of bins. Lazily initialized upon first insertion.
538 <     * Size is always a power of two. Accessed directly by iterators.
537 >     * Minimum number of rebinnings per transfer step. Ranges are
538 >     * subdivided to allow multiple resizer threads.  This value
539 >     * serves as a lower bound to avoid resizers encountering
540 >     * excessive memory contention.  The value should be at least
541 >     * DEFAULT_CAPACITY.
542       */
543 <    transient volatile Node[] table;
543 >    private static final int MIN_TRANSFER_STRIDE = 16;
544  
545      /**
546 <     * The counter maintaining number of elements.
546 >     * The number of bits used for generation stamp in sizeCtl.
547 >     * Must be at least 6 for 32bit arrays.
548       */
549 <    private transient final LongAdder counter;
549 >    private static int RESIZE_STAMP_BITS = 16;
550  
551      /**
552 <     * Table initialization and resizing control.  When negative, the
553 <     * table is being initialized or resized. Otherwise, when table is
637 <     * null, holds the initial table size to use upon creation, or 0
638 <     * for default. After initialization, holds the next element count
639 <     * value upon which to resize the table.
552 >     * The maximum number of threads that can help resize.
553 >     * Must fit in 32 - RESIZE_STAMP_BITS bits.
554       */
555 <    private transient volatile int sizeCtl;
555 >    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
556  
557 <    // views
558 <    private transient KeySetView<K,V> keySet;
559 <    private transient Values<K,V> values;
560 <    private transient EntrySet<K,V> entrySet;
647 <
648 <    /** For serialization compatibility. Null unless serialized; see below */
649 <    private Segment<K,V>[] segments;
650 <
651 <    /* ---------------- Table element access -------------- */
557 >    /**
558 >     * The bit shift for recording size stamp in sizeCtl.
559 >     */
560 >    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
561  
562      /*
563 <     * Volatile access methods are used for table elements as well as
655 <     * elements of in-progress next table while resizing.  Uses are
656 <     * null checked by callers, and implicitly bounds-checked, relying
657 <     * on the invariants that tab arrays have non-zero size, and all
658 <     * indices are masked with (tab.length - 1) which is never
659 <     * negative and always less than length. Note that, to be correct
660 <     * wrt arbitrary concurrency errors by users, bounds checks must
661 <     * operate on local variables, which accounts for some odd-looking
662 <     * inline assignments below.
563 >     * Encodings for Node hash fields. See above for explanation.
564       */
565 <
566 <    static final Node tabAt(Node[] tab, int i) { // used by Iter
567 <        return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
568 <    }
569 <
570 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
571 <        return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
572 <    }
573 <
574 <    private static final void setTabAt(Node[] tab, int i, Node v) {
575 <        UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
576 <    }
565 >    static final int MOVED     = -1; // hash for forwarding nodes
566 >    static final int TREEBIN   = -2; // hash for roots of trees
567 >    static final int RESERVED  = -3; // hash for transient reservations
568 >    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
569 >
570 >    /** Number of CPUS, to place bounds on some sizings */
571 >    static final int NCPU = Runtime.getRuntime().availableProcessors();
572 >
573 >    /** For serialization compatibility. */
574 >    private static final ObjectStreamField[] serialPersistentFields = {
575 >        new ObjectStreamField("segments", Segment[].class),
576 >        new ObjectStreamField("segmentMask", Integer.TYPE),
577 >        new ObjectStreamField("segmentShift", Integer.TYPE)
578 >    };
579  
580      /* ---------------- Nodes -------------- */
581  
582      /**
583 <     * Key-value entry. Note that this is never exported out as a
584 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
585 <     * field of MOVED are special, and do not contain user keys or
586 <     * values.  Otherwise, keys are never null, and null val fields
587 <     * indicate that a node is in the process of being deleted or
588 <     * created. For purposes of read-only access, a key may be read
589 <     * before a val, but can only be used after checking val to be
590 <     * non-null.
591 <     */
592 <    static class Node {
593 <        volatile int hash;
594 <        final Object key;
692 <        volatile Object val;
693 <        volatile Node next;
583 >     * Key-value entry.  This class is never exported out as a
584 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
585 >     * MapEntry below), but can be used for read-only traversals used
586 >     * in bulk tasks.  Subclasses of Node with a negative hash field
587 >     * are special, and contain null keys and values (but are never
588 >     * exported).  Otherwise, keys and vals are never null.
589 >     */
590 >    static class Node<K,V> implements Map.Entry<K,V> {
591 >        final int hash;
592 >        final K key;
593 >        volatile V val;
594 >        volatile Node<K,V> next;
595  
596 <        Node(int hash, Object key, Object val, Node next) {
596 >        Node(int hash, K key, V val, Node<K,V> next) {
597              this.hash = hash;
598              this.key = key;
599              this.val = val;
600              this.next = next;
601          }
602  
603 <        /** CompareAndSet the hash field */
604 <        final boolean casHash(int cmp, int val) {
605 <            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
606 <        }
607 <
608 <        /** The number of spins before blocking for a lock */
708 <        static final int MAX_SPINS =
709 <            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
710 <
711 <        /**
712 <         * Spins a while if LOCKED bit set and this node is the first
713 <         * of its bin, and then sets WAITING bits on hash field and
714 <         * blocks (once) if they are still set.  It is OK for this
715 <         * method to return even if lock is not available upon exit,
716 <         * which enables these simple single-wait mechanics.
717 <         *
718 <         * The corresponding signalling operation is performed within
719 <         * callers: Upon detecting that WAITING has been set when
720 <         * unlocking lock (via a failed CAS from non-waiting LOCKED
721 <         * state), unlockers acquire the sync lock and perform a
722 <         * notifyAll.
723 <         *
724 <         * The initial sanity check on tab and bounds is not currently
725 <         * necessary in the only usages of this method, but enables
726 <         * use in other future contexts.
727 <         */
728 <        final void tryAwaitLock(Node[] tab, int i) {
729 <            if (tab != null && i >= 0 && i < tab.length) { // sanity check
730 <                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
731 <                int spins = MAX_SPINS, h;
732 <                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
733 <                    if (spins >= 0) {
734 <                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
735 <                        if (r >= 0 && --spins == 0)
736 <                            Thread.yield();  // yield before block
737 <                    }
738 <                    else if (casHash(h, h | WAITING)) {
739 <                        synchronized (this) {
740 <                            if (tabAt(tab, i) == this &&
741 <                                (hash & WAITING) == WAITING) {
742 <                                try {
743 <                                    wait();
744 <                                } catch (InterruptedException ie) {
745 <                                    Thread.currentThread().interrupt();
746 <                                }
747 <                            }
748 <                            else
749 <                                notifyAll(); // possibly won race vs signaller
750 <                        }
751 <                        break;
752 <                    }
753 <                }
754 <            }
755 <        }
756 <
757 <        // Unsafe mechanics for casHash
758 <        private static final sun.misc.Unsafe UNSAFE;
759 <        private static final long hashOffset;
760 <
761 <        static {
762 <            try {
763 <                UNSAFE = sun.misc.Unsafe.getUnsafe();
764 <                Class<?> k = Node.class;
765 <                hashOffset = UNSAFE.objectFieldOffset
766 <                    (k.getDeclaredField("hash"));
767 <            } catch (Exception e) {
768 <                throw new Error(e);
769 <            }
770 <        }
771 <    }
772 <
773 <    /* ---------------- TreeBins -------------- */
774 <
775 <    /**
776 <     * Nodes for use in TreeBins
777 <     */
778 <    static final class TreeNode extends Node {
779 <        TreeNode parent;  // red-black tree links
780 <        TreeNode left;
781 <        TreeNode right;
782 <        TreeNode prev;    // needed to unlink next upon deletion
783 <        boolean red;
784 <
785 <        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
786 <            super(hash, key, val, next);
787 <            this.parent = parent;
788 <        }
789 <    }
790 <
791 <    /**
792 <     * A specialized form of red-black tree for use in bins
793 <     * whose size exceeds a threshold.
794 <     *
795 <     * TreeBins use a special form of comparison for search and
796 <     * related operations (which is the main reason we cannot use
797 <     * existing collections such as TreeMaps). TreeBins contain
798 <     * Comparable elements, but may contain others, as well as
799 <     * elements that are Comparable but not necessarily Comparable<T>
800 <     * for the same T, so we cannot invoke compareTo among them. To
801 <     * handle this, the tree is ordered primarily by hash value, then
802 <     * by getClass().getName() order, and then by Comparator order
803 <     * among elements of the same class.  On lookup at a node, if
804 <     * elements are not comparable or compare as 0, both left and
805 <     * right children may need to be searched in the case of tied hash
806 <     * values. (This corresponds to the full list search that would be
807 <     * necessary if all elements were non-Comparable and had tied
808 <     * hashes.)  The red-black balancing code is updated from
809 <     * pre-jdk-collections
810 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
811 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
812 <     * Algorithms" (CLR).
813 <     *
814 <     * TreeBins also maintain a separate locking discipline than
815 <     * regular bins. Because they are forwarded via special MOVED
816 <     * nodes at bin heads (which can never change once established),
817 <     * we cannot use those nodes as locks. Instead, TreeBin
818 <     * extends AbstractQueuedSynchronizer to support a simple form of
819 <     * read-write lock. For update operations and table validation,
820 <     * the exclusive form of lock behaves in the same way as bin-head
821 <     * locks. However, lookups use shared read-lock mechanics to allow
822 <     * multiple readers in the absence of writers.  Additionally,
823 <     * these lookups do not ever block: While the lock is not
824 <     * available, they proceed along the slow traversal path (via
825 <     * next-pointers) until the lock becomes available or the list is
826 <     * exhausted, whichever comes first. (These cases are not fast,
827 <     * but maximize aggregate expected throughput.)  The AQS mechanics
828 <     * for doing this are straightforward.  The lock state is held as
829 <     * AQS getState().  Read counts are negative; the write count (1)
830 <     * is positive.  There are no signalling preferences among readers
831 <     * and writers. Since we don't need to export full Lock API, we
832 <     * just override the minimal AQS methods and use them directly.
833 <     */
834 <    static final class TreeBin extends AbstractQueuedSynchronizer {
835 <        private static final long serialVersionUID = 2249069246763182397L;
836 <        transient TreeNode root;  // root of tree
837 <        transient TreeNode first; // head of next-pointer list
838 <
839 <        /* AQS overrides */
840 <        public final boolean isHeldExclusively() { return getState() > 0; }
841 <        public final boolean tryAcquire(int ignore) {
842 <            if (compareAndSetState(0, 1)) {
843 <                setExclusiveOwnerThread(Thread.currentThread());
844 <                return true;
845 <            }
846 <            return false;
847 <        }
848 <        public final boolean tryRelease(int ignore) {
849 <            setExclusiveOwnerThread(null);
850 <            setState(0);
851 <            return true;
852 <        }
853 <        public final int tryAcquireShared(int ignore) {
854 <            for (int c;;) {
855 <                if ((c = getState()) > 0)
856 <                    return -1;
857 <                if (compareAndSetState(c, c -1))
858 <                    return 1;
859 <            }
860 <        }
861 <        public final boolean tryReleaseShared(int ignore) {
862 <            int c;
863 <            do {} while (!compareAndSetState(c = getState(), c + 1));
864 <            return c == -1;
865 <        }
866 <
867 <        /** From CLR */
868 <        private void rotateLeft(TreeNode p) {
869 <            if (p != null) {
870 <                TreeNode r = p.right, pp, rl;
871 <                if ((rl = p.right = r.left) != null)
872 <                    rl.parent = p;
873 <                if ((pp = r.parent = p.parent) == null)
874 <                    root = r;
875 <                else if (pp.left == p)
876 <                    pp.left = r;
877 <                else
878 <                    pp.right = r;
879 <                r.left = p;
880 <                p.parent = r;
881 <            }
882 <        }
883 <
884 <        /** From CLR */
885 <        private void rotateRight(TreeNode p) {
886 <            if (p != null) {
887 <                TreeNode l = p.left, pp, lr;
888 <                if ((lr = p.left = l.right) != null)
889 <                    lr.parent = p;
890 <                if ((pp = l.parent = p.parent) == null)
891 <                    root = l;
892 <                else if (pp.right == p)
893 <                    pp.right = l;
894 <                else
895 <                    pp.left = l;
896 <                l.right = p;
897 <                p.parent = l;
898 <            }
899 <        }
900 <
901 <        /**
902 <         * Returns the TreeNode (or null if not found) for the given key
903 <         * starting at given root.
904 <         */
905 <        @SuppressWarnings("unchecked") final TreeNode getTreeNode
906 <            (int h, Object k, TreeNode p) {
907 <            Class<?> c = k.getClass();
908 <            while (p != null) {
909 <                int dir, ph;  Object pk; Class<?> pc;
910 <                if ((ph = p.hash) == h) {
911 <                    if ((pk = p.key) == k || k.equals(pk))
912 <                        return p;
913 <                    if (c != (pc = pk.getClass()) ||
914 <                        !(k instanceof Comparable) ||
915 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
916 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
917 <                        TreeNode r = null, s = null, pl, pr;
918 <                        if (dir >= 0) {
919 <                            if ((pl = p.left) != null && h <= pl.hash)
920 <                                s = pl;
921 <                        }
922 <                        else if ((pr = p.right) != null && h >= pr.hash)
923 <                            s = pr;
924 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
925 <                            return r;
926 <                    }
927 <                }
928 <                else
929 <                    dir = (h < ph) ? -1 : 1;
930 <                p = (dir > 0) ? p.right : p.left;
931 <            }
932 <            return null;
603 >        public final K getKey()       { return key; }
604 >        public final V getValue()     { return val; }
605 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
606 >        public final String toString(){ return key + "=" + val; }
607 >        public final V setValue(V value) {
608 >            throw new UnsupportedOperationException();
609          }
610  
611 <        /**
612 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
613 <         * read-lock to call getTreeNode, but during failure to get
614 <         * lock, searches along next links.
615 <         */
616 <        final Object getValue(int h, Object k) {
617 <            Node r = null;
942 <            int c = getState(); // Must read lock state first
943 <            for (Node e = first; e != null; e = e.next) {
944 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
945 <                    try {
946 <                        r = getTreeNode(h, k, root);
947 <                    } finally {
948 <                        releaseShared(0);
949 <                    }
950 <                    break;
951 <                }
952 <                else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
953 <                    r = e;
954 <                    break;
955 <                }
956 <                else
957 <                    c = getState();
958 <            }
959 <            return r == null ? null : r.val;
611 >        public final boolean equals(Object o) {
612 >            Object k, v, u; Map.Entry<?,?> e;
613 >            return ((o instanceof Map.Entry) &&
614 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
615 >                    (v = e.getValue()) != null &&
616 >                    (k == key || k.equals(key)) &&
617 >                    (v == (u = val) || v.equals(u)));
618          }
619  
620          /**
621 <         * Finds or adds a node.
964 <         * @return null if added
621 >         * Virtualized support for map.get(); overridden in subclasses.
622           */
623 <        @SuppressWarnings("unchecked") final TreeNode putTreeNode
624 <            (int h, Object k, Object v) {
625 <            Class<?> c = k.getClass();
626 <            TreeNode pp = root, p = null;
627 <            int dir = 0;
628 <            while (pp != null) { // find existing node or leaf to insert at
629 <                int ph;  Object pk; Class<?> pc;
630 <                p = pp;
631 <                if ((ph = p.hash) == h) {
975 <                    if ((pk = p.key) == k || k.equals(pk))
976 <                        return p;
977 <                    if (c != (pc = pk.getClass()) ||
978 <                        !(k instanceof Comparable) ||
979 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
980 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
981 <                        TreeNode r = null, s = null, pl, pr;
982 <                        if (dir >= 0) {
983 <                            if ((pl = p.left) != null && h <= pl.hash)
984 <                                s = pl;
985 <                        }
986 <                        else if ((pr = p.right) != null && h >= pr.hash)
987 <                            s = pr;
988 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
989 <                            return r;
990 <                    }
991 <                }
992 <                else
993 <                    dir = (h < ph) ? -1 : 1;
994 <                pp = (dir > 0) ? p.right : p.left;
995 <            }
996 <
997 <            TreeNode f = first;
998 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
999 <            if (p == null)
1000 <                root = x;
1001 <            else { // attach and rebalance; adapted from CLR
1002 <                TreeNode xp, xpp;
1003 <                if (f != null)
1004 <                    f.prev = x;
1005 <                if (dir <= 0)
1006 <                    p.left = x;
1007 <                else
1008 <                    p.right = x;
1009 <                x.red = true;
1010 <                while (x != null && (xp = x.parent) != null && xp.red &&
1011 <                       (xpp = xp.parent) != null) {
1012 <                    TreeNode xppl = xpp.left;
1013 <                    if (xp == xppl) {
1014 <                        TreeNode y = xpp.right;
1015 <                        if (y != null && y.red) {
1016 <                            y.red = false;
1017 <                            xp.red = false;
1018 <                            xpp.red = true;
1019 <                            x = xpp;
1020 <                        }
1021 <                        else {
1022 <                            if (x == xp.right) {
1023 <                                rotateLeft(x = xp);
1024 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
1025 <                            }
1026 <                            if (xp != null) {
1027 <                                xp.red = false;
1028 <                                if (xpp != null) {
1029 <                                    xpp.red = true;
1030 <                                    rotateRight(xpp);
1031 <                                }
1032 <                            }
1033 <                        }
1034 <                    }
1035 <                    else {
1036 <                        TreeNode y = xppl;
1037 <                        if (y != null && y.red) {
1038 <                            y.red = false;
1039 <                            xp.red = false;
1040 <                            xpp.red = true;
1041 <                            x = xpp;
1042 <                        }
1043 <                        else {
1044 <                            if (x == xp.left) {
1045 <                                rotateRight(x = xp);
1046 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
1047 <                            }
1048 <                            if (xp != null) {
1049 <                                xp.red = false;
1050 <                                if (xpp != null) {
1051 <                                    xpp.red = true;
1052 <                                    rotateLeft(xpp);
1053 <                                }
1054 <                            }
1055 <                        }
1056 <                    }
1057 <                }
1058 <                TreeNode r = root;
1059 <                if (r != null && r.red)
1060 <                    r.red = false;
623 >        Node<K,V> find(int h, Object k) {
624 >            Node<K,V> e = this;
625 >            if (k != null) {
626 >                do {
627 >                    K ek;
628 >                    if (e.hash == h &&
629 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
630 >                        return e;
631 >                } while ((e = e.next) != null);
632              }
633              return null;
634          }
1064
1065        /**
1066         * Removes the given node, that must be present before this
1067         * call.  This is messier than typical red-black deletion code
1068         * because we cannot swap the contents of an interior node
1069         * with a leaf successor that is pinned by "next" pointers
1070         * that are accessible independently of lock. So instead we
1071         * swap the tree linkages.
1072         */
1073        final void deleteTreeNode(TreeNode p) {
1074            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
1075            TreeNode pred = p.prev;
1076            if (pred == null)
1077                first = next;
1078            else
1079                pred.next = next;
1080            if (next != null)
1081                next.prev = pred;
1082            TreeNode replacement;
1083            TreeNode pl = p.left;
1084            TreeNode pr = p.right;
1085            if (pl != null && pr != null) {
1086                TreeNode s = pr, sl;
1087                while ((sl = s.left) != null) // find successor
1088                    s = sl;
1089                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
1090                TreeNode sr = s.right;
1091                TreeNode pp = p.parent;
1092                if (s == pr) { // p was s's direct parent
1093                    p.parent = s;
1094                    s.right = p;
1095                }
1096                else {
1097                    TreeNode sp = s.parent;
1098                    if ((p.parent = sp) != null) {
1099                        if (s == sp.left)
1100                            sp.left = p;
1101                        else
1102                            sp.right = p;
1103                    }
1104                    if ((s.right = pr) != null)
1105                        pr.parent = s;
1106                }
1107                p.left = null;
1108                if ((p.right = sr) != null)
1109                    sr.parent = p;
1110                if ((s.left = pl) != null)
1111                    pl.parent = s;
1112                if ((s.parent = pp) == null)
1113                    root = s;
1114                else if (p == pp.left)
1115                    pp.left = s;
1116                else
1117                    pp.right = s;
1118                replacement = sr;
1119            }
1120            else
1121                replacement = (pl != null) ? pl : pr;
1122            TreeNode pp = p.parent;
1123            if (replacement == null) {
1124                if (pp == null) {
1125                    root = null;
1126                    return;
1127                }
1128                replacement = p;
1129            }
1130            else {
1131                replacement.parent = pp;
1132                if (pp == null)
1133                    root = replacement;
1134                else if (p == pp.left)
1135                    pp.left = replacement;
1136                else
1137                    pp.right = replacement;
1138                p.left = p.right = p.parent = null;
1139            }
1140            if (!p.red) { // rebalance, from CLR
1141                TreeNode x = replacement;
1142                while (x != null) {
1143                    TreeNode xp, xpl;
1144                    if (x.red || (xp = x.parent) == null) {
1145                        x.red = false;
1146                        break;
1147                    }
1148                    if (x == (xpl = xp.left)) {
1149                        TreeNode sib = xp.right;
1150                        if (sib != null && sib.red) {
1151                            sib.red = false;
1152                            xp.red = true;
1153                            rotateLeft(xp);
1154                            sib = (xp = x.parent) == null ? null : xp.right;
1155                        }
1156                        if (sib == null)
1157                            x = xp;
1158                        else {
1159                            TreeNode sl = sib.left, sr = sib.right;
1160                            if ((sr == null || !sr.red) &&
1161                                (sl == null || !sl.red)) {
1162                                sib.red = true;
1163                                x = xp;
1164                            }
1165                            else {
1166                                if (sr == null || !sr.red) {
1167                                    if (sl != null)
1168                                        sl.red = false;
1169                                    sib.red = true;
1170                                    rotateRight(sib);
1171                                    sib = (xp = x.parent) == null ? null : xp.right;
1172                                }
1173                                if (sib != null) {
1174                                    sib.red = (xp == null) ? false : xp.red;
1175                                    if ((sr = sib.right) != null)
1176                                        sr.red = false;
1177                                }
1178                                if (xp != null) {
1179                                    xp.red = false;
1180                                    rotateLeft(xp);
1181                                }
1182                                x = root;
1183                            }
1184                        }
1185                    }
1186                    else { // symmetric
1187                        TreeNode sib = xpl;
1188                        if (sib != null && sib.red) {
1189                            sib.red = false;
1190                            xp.red = true;
1191                            rotateRight(xp);
1192                            sib = (xp = x.parent) == null ? null : xp.left;
1193                        }
1194                        if (sib == null)
1195                            x = xp;
1196                        else {
1197                            TreeNode sl = sib.left, sr = sib.right;
1198                            if ((sl == null || !sl.red) &&
1199                                (sr == null || !sr.red)) {
1200                                sib.red = true;
1201                                x = xp;
1202                            }
1203                            else {
1204                                if (sl == null || !sl.red) {
1205                                    if (sr != null)
1206                                        sr.red = false;
1207                                    sib.red = true;
1208                                    rotateLeft(sib);
1209                                    sib = (xp = x.parent) == null ? null : xp.left;
1210                                }
1211                                if (sib != null) {
1212                                    sib.red = (xp == null) ? false : xp.red;
1213                                    if ((sl = sib.left) != null)
1214                                        sl.red = false;
1215                                }
1216                                if (xp != null) {
1217                                    xp.red = false;
1218                                    rotateRight(xp);
1219                                }
1220                                x = root;
1221                            }
1222                        }
1223                    }
1224                }
1225            }
1226            if (p == replacement && (pp = p.parent) != null) {
1227                if (p == pp.left) // detach pointers
1228                    pp.left = null;
1229                else if (p == pp.right)
1230                    pp.right = null;
1231                p.parent = null;
1232            }
1233        }
635      }
636  
637 <    /* ---------------- Collision reduction methods -------------- */
637 >    /* ---------------- Static utilities -------------- */
638  
639      /**
640 <     * Spreads higher bits to lower, and also forces top 2 bits to 0.
641 <     * Because the table uses power-of-two masking, sets of hashes
642 <     * that vary only in bits above the current mask will always
643 <     * collide. (Among known examples are sets of Float keys holding
644 <     * consecutive whole numbers in small tables.)  To counter this,
645 <     * we apply a transform that spreads the impact of higher bits
640 >     * Spreads (XORs) higher bits of hash to lower and also forces top
641 >     * bit to 0. Because the table uses power-of-two masking, sets of
642 >     * hashes that vary only in bits above the current mask will
643 >     * always collide. (Among known examples are sets of Float keys
644 >     * holding consecutive whole numbers in small tables.)  So we
645 >     * apply a transform that spreads the impact of higher bits
646       * downward. There is a tradeoff between speed, utility, and
647       * quality of bit-spreading. Because many common sets of hashes
648 <     * are already reasonably distributed across bits (so don't benefit
649 <     * from spreading), and because we use trees to handle large sets
650 <     * of collisions in bins, we don't need excessively high quality.
648 >     * are already reasonably distributed (so don't benefit from
649 >     * spreading), and because we use trees to handle large sets of
650 >     * collisions in bins, we just XOR some shifted bits in the
651 >     * cheapest possible way to reduce systematic lossage, as well as
652 >     * to incorporate impact of the highest bits that would otherwise
653 >     * never be used in index calculations because of table bounds.
654       */
655 <    private static final int spread(int h) {
656 <        h ^= (h >>> 18) ^ (h >>> 12);
1253 <        return (h ^ (h >>> 10)) & HASH_BITS;
1254 <    }
1255 <
1256 <    /**
1257 <     * Replaces a list bin with a tree bin. Call only when locked.
1258 <     * Fails to replace if the given key is non-comparable or table
1259 <     * is, or needs, resizing.
1260 <     */
1261 <    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1262 <        if ((key instanceof Comparable) &&
1263 <            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
1264 <            TreeBin t = new TreeBin();
1265 <            for (Node e = tabAt(tab, index); e != null; e = e.next)
1266 <                t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
1267 <            setTabAt(tab, index, new Node(MOVED, t, null, null));
1268 <        }
1269 <    }
1270 <
1271 <    /* ---------------- Internal access and update methods -------------- */
1272 <
1273 <    /** Implementation for get and containsKey */
1274 <    private final Object internalGet(Object k) {
1275 <        int h = spread(k.hashCode());
1276 <        retry: for (Node[] tab = table; tab != null;) {
1277 <            Node e, p; Object ek, ev; int eh;      // locals to read fields once
1278 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1279 <                if ((eh = e.hash) == MOVED) {
1280 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1281 <                        return ((TreeBin)ek).getValue(h, k);
1282 <                    else {                        // restart with new table
1283 <                        tab = (Node[])ek;
1284 <                        continue retry;
1285 <                    }
1286 <                }
1287 <                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1288 <                         ((ek = e.key) == k || k.equals(ek)))
1289 <                    return ev;
1290 <            }
1291 <            break;
1292 <        }
1293 <        return null;
1294 <    }
1295 <
1296 <    /**
1297 <     * Implementation for the four public remove/replace methods:
1298 <     * Replaces node value with v, conditional upon match of cv if
1299 <     * non-null.  If resulting value is null, delete.
1300 <     */
1301 <    private final Object internalReplace(Object k, Object v, Object cv) {
1302 <        int h = spread(k.hashCode());
1303 <        Object oldVal = null;
1304 <        for (Node[] tab = table;;) {
1305 <            Node f; int i, fh; Object fk;
1306 <            if (tab == null ||
1307 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1308 <                break;
1309 <            else if ((fh = f.hash) == MOVED) {
1310 <                if ((fk = f.key) instanceof TreeBin) {
1311 <                    TreeBin t = (TreeBin)fk;
1312 <                    boolean validated = false;
1313 <                    boolean deleted = false;
1314 <                    t.acquire(0);
1315 <                    try {
1316 <                        if (tabAt(tab, i) == f) {
1317 <                            validated = true;
1318 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1319 <                            if (p != null) {
1320 <                                Object pv = p.val;
1321 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1322 <                                    oldVal = pv;
1323 <                                    if ((p.val = v) == null) {
1324 <                                        deleted = true;
1325 <                                        t.deleteTreeNode(p);
1326 <                                    }
1327 <                                }
1328 <                            }
1329 <                        }
1330 <                    } finally {
1331 <                        t.release(0);
1332 <                    }
1333 <                    if (validated) {
1334 <                        if (deleted)
1335 <                            counter.add(-1L);
1336 <                        break;
1337 <                    }
1338 <                }
1339 <                else
1340 <                    tab = (Node[])fk;
1341 <            }
1342 <            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
1343 <                break;                          // rules out possible existence
1344 <            else if ((fh & LOCKED) != 0) {
1345 <                checkForResize();               // try resizing if can't get lock
1346 <                f.tryAwaitLock(tab, i);
1347 <            }
1348 <            else if (f.casHash(fh, fh | LOCKED)) {
1349 <                boolean validated = false;
1350 <                boolean deleted = false;
1351 <                try {
1352 <                    if (tabAt(tab, i) == f) {
1353 <                        validated = true;
1354 <                        for (Node e = f, pred = null;;) {
1355 <                            Object ek, ev;
1356 <                            if ((e.hash & HASH_BITS) == h &&
1357 <                                ((ev = e.val) != null) &&
1358 <                                ((ek = e.key) == k || k.equals(ek))) {
1359 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1360 <                                    oldVal = ev;
1361 <                                    if ((e.val = v) == null) {
1362 <                                        deleted = true;
1363 <                                        Node en = e.next;
1364 <                                        if (pred != null)
1365 <                                            pred.next = en;
1366 <                                        else
1367 <                                            setTabAt(tab, i, en);
1368 <                                    }
1369 <                                }
1370 <                                break;
1371 <                            }
1372 <                            pred = e;
1373 <                            if ((e = e.next) == null)
1374 <                                break;
1375 <                        }
1376 <                    }
1377 <                } finally {
1378 <                    if (!f.casHash(fh | LOCKED, fh)) {
1379 <                        f.hash = fh;
1380 <                        synchronized (f) { f.notifyAll(); };
1381 <                    }
1382 <                }
1383 <                if (validated) {
1384 <                    if (deleted)
1385 <                        counter.add(-1L);
1386 <                    break;
1387 <                }
1388 <            }
1389 <        }
1390 <        return oldVal;
1391 <    }
1392 <
1393 <    /*
1394 <     * Internal versions of the six insertion methods, each a
1395 <     * little more complicated than the last. All have
1396 <     * the same basic structure as the first (internalPut):
1397 <     *  1. If table uninitialized, create
1398 <     *  2. If bin empty, try to CAS new node
1399 <     *  3. If bin stale, use new table
1400 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1401 <     *  5. Lock and validate; if valid, scan and add or update
1402 <     *
1403 <     * The others interweave other checks and/or alternative actions:
1404 <     *  * Plain put checks for and performs resize after insertion.
1405 <     *  * putIfAbsent prescans for mapping without lock (and fails to add
1406 <     *    if present), which also makes pre-emptive resize checks worthwhile.
1407 <     *  * computeIfAbsent extends form used in putIfAbsent with additional
1408 <     *    mechanics to deal with, calls, potential exceptions and null
1409 <     *    returns from function call.
1410 <     *  * compute uses the same function-call mechanics, but without
1411 <     *    the prescans
1412 <     *  * merge acts as putIfAbsent in the absent case, but invokes the
1413 <     *    update function if present
1414 <     *  * putAll attempts to pre-allocate enough table space
1415 <     *    and more lazily performs count updates and checks.
1416 <     *
1417 <     * Someday when details settle down a bit more, it might be worth
1418 <     * some factoring to reduce sprawl.
1419 <     */
1420 <
1421 <    /** Implementation for put */
1422 <    private final Object internalPut(Object k, Object v) {
1423 <        int h = spread(k.hashCode());
1424 <        int count = 0;
1425 <        for (Node[] tab = table;;) {
1426 <            int i; Node f; int fh; Object fk;
1427 <            if (tab == null)
1428 <                tab = initTable();
1429 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1430 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1431 <                    break;                   // no lock when adding to empty bin
1432 <            }
1433 <            else if ((fh = f.hash) == MOVED) {
1434 <                if ((fk = f.key) instanceof TreeBin) {
1435 <                    TreeBin t = (TreeBin)fk;
1436 <                    Object oldVal = null;
1437 <                    t.acquire(0);
1438 <                    try {
1439 <                        if (tabAt(tab, i) == f) {
1440 <                            count = 2;
1441 <                            TreeNode p = t.putTreeNode(h, k, v);
1442 <                            if (p != null) {
1443 <                                oldVal = p.val;
1444 <                                p.val = v;
1445 <                            }
1446 <                        }
1447 <                    } finally {
1448 <                        t.release(0);
1449 <                    }
1450 <                    if (count != 0) {
1451 <                        if (oldVal != null)
1452 <                            return oldVal;
1453 <                        break;
1454 <                    }
1455 <                }
1456 <                else
1457 <                    tab = (Node[])fk;
1458 <            }
1459 <            else if ((fh & LOCKED) != 0) {
1460 <                checkForResize();
1461 <                f.tryAwaitLock(tab, i);
1462 <            }
1463 <            else if (f.casHash(fh, fh | LOCKED)) {
1464 <                Object oldVal = null;
1465 <                try {                        // needed in case equals() throws
1466 <                    if (tabAt(tab, i) == f) {
1467 <                        count = 1;
1468 <                        for (Node e = f;; ++count) {
1469 <                            Object ek, ev;
1470 <                            if ((e.hash & HASH_BITS) == h &&
1471 <                                (ev = e.val) != null &&
1472 <                                ((ek = e.key) == k || k.equals(ek))) {
1473 <                                oldVal = ev;
1474 <                                e.val = v;
1475 <                                break;
1476 <                            }
1477 <                            Node last = e;
1478 <                            if ((e = e.next) == null) {
1479 <                                last.next = new Node(h, k, v, null);
1480 <                                if (count >= TREE_THRESHOLD)
1481 <                                    replaceWithTreeBin(tab, i, k);
1482 <                                break;
1483 <                            }
1484 <                        }
1485 <                    }
1486 <                } finally {                  // unlock and signal if needed
1487 <                    if (!f.casHash(fh | LOCKED, fh)) {
1488 <                        f.hash = fh;
1489 <                        synchronized (f) { f.notifyAll(); };
1490 <                    }
1491 <                }
1492 <                if (count != 0) {
1493 <                    if (oldVal != null)
1494 <                        return oldVal;
1495 <                    if (tab.length <= 64)
1496 <                        count = 2;
1497 <                    break;
1498 <                }
1499 <            }
1500 <        }
1501 <        counter.add(1L);
1502 <        if (count > 1)
1503 <            checkForResize();
1504 <        return null;
1505 <    }
1506 <
1507 <    /** Implementation for putIfAbsent */
1508 <    private final Object internalPutIfAbsent(Object k, Object v) {
1509 <        int h = spread(k.hashCode());
1510 <        int count = 0;
1511 <        for (Node[] tab = table;;) {
1512 <            int i; Node f; int fh; Object fk, fv;
1513 <            if (tab == null)
1514 <                tab = initTable();
1515 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1516 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1517 <                    break;
1518 <            }
1519 <            else if ((fh = f.hash) == MOVED) {
1520 <                if ((fk = f.key) instanceof TreeBin) {
1521 <                    TreeBin t = (TreeBin)fk;
1522 <                    Object oldVal = null;
1523 <                    t.acquire(0);
1524 <                    try {
1525 <                        if (tabAt(tab, i) == f) {
1526 <                            count = 2;
1527 <                            TreeNode p = t.putTreeNode(h, k, v);
1528 <                            if (p != null)
1529 <                                oldVal = p.val;
1530 <                        }
1531 <                    } finally {
1532 <                        t.release(0);
1533 <                    }
1534 <                    if (count != 0) {
1535 <                        if (oldVal != null)
1536 <                            return oldVal;
1537 <                        break;
1538 <                    }
1539 <                }
1540 <                else
1541 <                    tab = (Node[])fk;
1542 <            }
1543 <            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1544 <                     ((fk = f.key) == k || k.equals(fk)))
1545 <                return fv;
1546 <            else {
1547 <                Node g = f.next;
1548 <                if (g != null) { // at least 2 nodes -- search and maybe resize
1549 <                    for (Node e = g;;) {
1550 <                        Object ek, ev;
1551 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1552 <                            ((ek = e.key) == k || k.equals(ek)))
1553 <                            return ev;
1554 <                        if ((e = e.next) == null) {
1555 <                            checkForResize();
1556 <                            break;
1557 <                        }
1558 <                    }
1559 <                }
1560 <                if (((fh = f.hash) & LOCKED) != 0) {
1561 <                    checkForResize();
1562 <                    f.tryAwaitLock(tab, i);
1563 <                }
1564 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1565 <                    Object oldVal = null;
1566 <                    try {
1567 <                        if (tabAt(tab, i) == f) {
1568 <                            count = 1;
1569 <                            for (Node e = f;; ++count) {
1570 <                                Object ek, ev;
1571 <                                if ((e.hash & HASH_BITS) == h &&
1572 <                                    (ev = e.val) != null &&
1573 <                                    ((ek = e.key) == k || k.equals(ek))) {
1574 <                                    oldVal = ev;
1575 <                                    break;
1576 <                                }
1577 <                                Node last = e;
1578 <                                if ((e = e.next) == null) {
1579 <                                    last.next = new Node(h, k, v, null);
1580 <                                    if (count >= TREE_THRESHOLD)
1581 <                                        replaceWithTreeBin(tab, i, k);
1582 <                                    break;
1583 <                                }
1584 <                            }
1585 <                        }
1586 <                    } finally {
1587 <                        if (!f.casHash(fh | LOCKED, fh)) {
1588 <                            f.hash = fh;
1589 <                            synchronized (f) { f.notifyAll(); };
1590 <                        }
1591 <                    }
1592 <                    if (count != 0) {
1593 <                        if (oldVal != null)
1594 <                            return oldVal;
1595 <                        if (tab.length <= 64)
1596 <                            count = 2;
1597 <                        break;
1598 <                    }
1599 <                }
1600 <            }
1601 <        }
1602 <        counter.add(1L);
1603 <        if (count > 1)
1604 <            checkForResize();
1605 <        return null;
1606 <    }
1607 <
1608 <    /** Implementation for computeIfAbsent */
1609 <    private final Object internalComputeIfAbsent(K k,
1610 <                                                 Fun<? super K, ?> mf) {
1611 <        int h = spread(k.hashCode());
1612 <        Object val = null;
1613 <        int count = 0;
1614 <        for (Node[] tab = table;;) {
1615 <            Node f; int i, fh; Object fk, fv;
1616 <            if (tab == null)
1617 <                tab = initTable();
1618 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1619 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1620 <                if (casTabAt(tab, i, null, node)) {
1621 <                    count = 1;
1622 <                    try {
1623 <                        if ((val = mf.apply(k)) != null)
1624 <                            node.val = val;
1625 <                    } finally {
1626 <                        if (val == null)
1627 <                            setTabAt(tab, i, null);
1628 <                        if (!node.casHash(fh, h)) {
1629 <                            node.hash = h;
1630 <                            synchronized (node) { node.notifyAll(); };
1631 <                        }
1632 <                    }
1633 <                }
1634 <                if (count != 0)
1635 <                    break;
1636 <            }
1637 <            else if ((fh = f.hash) == MOVED) {
1638 <                if ((fk = f.key) instanceof TreeBin) {
1639 <                    TreeBin t = (TreeBin)fk;
1640 <                    boolean added = false;
1641 <                    t.acquire(0);
1642 <                    try {
1643 <                        if (tabAt(tab, i) == f) {
1644 <                            count = 1;
1645 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1646 <                            if (p != null)
1647 <                                val = p.val;
1648 <                            else if ((val = mf.apply(k)) != null) {
1649 <                                added = true;
1650 <                                count = 2;
1651 <                                t.putTreeNode(h, k, val);
1652 <                            }
1653 <                        }
1654 <                    } finally {
1655 <                        t.release(0);
1656 <                    }
1657 <                    if (count != 0) {
1658 <                        if (!added)
1659 <                            return val;
1660 <                        break;
1661 <                    }
1662 <                }
1663 <                else
1664 <                    tab = (Node[])fk;
1665 <            }
1666 <            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1667 <                     ((fk = f.key) == k || k.equals(fk)))
1668 <                return fv;
1669 <            else {
1670 <                Node g = f.next;
1671 <                if (g != null) {
1672 <                    for (Node e = g;;) {
1673 <                        Object ek, ev;
1674 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1675 <                            ((ek = e.key) == k || k.equals(ek)))
1676 <                            return ev;
1677 <                        if ((e = e.next) == null) {
1678 <                            checkForResize();
1679 <                            break;
1680 <                        }
1681 <                    }
1682 <                }
1683 <                if (((fh = f.hash) & LOCKED) != 0) {
1684 <                    checkForResize();
1685 <                    f.tryAwaitLock(tab, i);
1686 <                }
1687 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1688 <                    boolean added = false;
1689 <                    try {
1690 <                        if (tabAt(tab, i) == f) {
1691 <                            count = 1;
1692 <                            for (Node e = f;; ++count) {
1693 <                                Object ek, ev;
1694 <                                if ((e.hash & HASH_BITS) == h &&
1695 <                                    (ev = e.val) != null &&
1696 <                                    ((ek = e.key) == k || k.equals(ek))) {
1697 <                                    val = ev;
1698 <                                    break;
1699 <                                }
1700 <                                Node last = e;
1701 <                                if ((e = e.next) == null) {
1702 <                                    if ((val = mf.apply(k)) != null) {
1703 <                                        added = true;
1704 <                                        last.next = new Node(h, k, val, null);
1705 <                                        if (count >= TREE_THRESHOLD)
1706 <                                            replaceWithTreeBin(tab, i, k);
1707 <                                    }
1708 <                                    break;
1709 <                                }
1710 <                            }
1711 <                        }
1712 <                    } finally {
1713 <                        if (!f.casHash(fh | LOCKED, fh)) {
1714 <                            f.hash = fh;
1715 <                            synchronized (f) { f.notifyAll(); };
1716 <                        }
1717 <                    }
1718 <                    if (count != 0) {
1719 <                        if (!added)
1720 <                            return val;
1721 <                        if (tab.length <= 64)
1722 <                            count = 2;
1723 <                        break;
1724 <                    }
1725 <                }
1726 <            }
1727 <        }
1728 <        if (val != null) {
1729 <            counter.add(1L);
1730 <            if (count > 1)
1731 <                checkForResize();
1732 <        }
1733 <        return val;
1734 <    }
1735 <
1736 <    /** Implementation for compute */
1737 <    @SuppressWarnings("unchecked") private final Object internalCompute
1738 <        (K k, boolean onlyIfPresent, BiFun<? super K, ? super V, ? extends V> mf) {
1739 <        int h = spread(k.hashCode());
1740 <        Object val = null;
1741 <        int delta = 0;
1742 <        int count = 0;
1743 <        for (Node[] tab = table;;) {
1744 <            Node f; int i, fh; Object fk;
1745 <            if (tab == null)
1746 <                tab = initTable();
1747 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1748 <                if (onlyIfPresent)
1749 <                    break;
1750 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1751 <                if (casTabAt(tab, i, null, node)) {
1752 <                    try {
1753 <                        count = 1;
1754 <                        if ((val = mf.apply(k, null)) != null) {
1755 <                            node.val = val;
1756 <                            delta = 1;
1757 <                        }
1758 <                    } finally {
1759 <                        if (delta == 0)
1760 <                            setTabAt(tab, i, null);
1761 <                        if (!node.casHash(fh, h)) {
1762 <                            node.hash = h;
1763 <                            synchronized (node) { node.notifyAll(); };
1764 <                        }
1765 <                    }
1766 <                }
1767 <                if (count != 0)
1768 <                    break;
1769 <            }
1770 <            else if ((fh = f.hash) == MOVED) {
1771 <                if ((fk = f.key) instanceof TreeBin) {
1772 <                    TreeBin t = (TreeBin)fk;
1773 <                    t.acquire(0);
1774 <                    try {
1775 <                        if (tabAt(tab, i) == f) {
1776 <                            count = 1;
1777 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1778 <                            Object pv = (p == null) ? null : p.val;
1779 <                            if ((val = mf.apply(k, (V)pv)) != null) {
1780 <                                if (p != null)
1781 <                                    p.val = val;
1782 <                                else {
1783 <                                    count = 2;
1784 <                                    delta = 1;
1785 <                                    t.putTreeNode(h, k, val);
1786 <                                }
1787 <                            }
1788 <                            else if (p != null) {
1789 <                                delta = -1;
1790 <                                t.deleteTreeNode(p);
1791 <                            }
1792 <                        }
1793 <                    } finally {
1794 <                        t.release(0);
1795 <                    }
1796 <                    if (count != 0)
1797 <                        break;
1798 <                }
1799 <                else
1800 <                    tab = (Node[])fk;
1801 <            }
1802 <            else if ((fh & LOCKED) != 0) {
1803 <                checkForResize();
1804 <                f.tryAwaitLock(tab, i);
1805 <            }
1806 <            else if (f.casHash(fh, fh | LOCKED)) {
1807 <                try {
1808 <                    if (tabAt(tab, i) == f) {
1809 <                        count = 1;
1810 <                        for (Node e = f, pred = null;; ++count) {
1811 <                            Object ek, ev;
1812 <                            if ((e.hash & HASH_BITS) == h &&
1813 <                                (ev = e.val) != null &&
1814 <                                ((ek = e.key) == k || k.equals(ek))) {
1815 <                                val = mf.apply(k, (V)ev);
1816 <                                if (val != null)
1817 <                                    e.val = val;
1818 <                                else {
1819 <                                    delta = -1;
1820 <                                    Node en = e.next;
1821 <                                    if (pred != null)
1822 <                                        pred.next = en;
1823 <                                    else
1824 <                                        setTabAt(tab, i, en);
1825 <                                }
1826 <                                break;
1827 <                            }
1828 <                            pred = e;
1829 <                            if ((e = e.next) == null) {
1830 <                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1831 <                                    pred.next = new Node(h, k, val, null);
1832 <                                    delta = 1;
1833 <                                    if (count >= TREE_THRESHOLD)
1834 <                                        replaceWithTreeBin(tab, i, k);
1835 <                                }
1836 <                                break;
1837 <                            }
1838 <                        }
1839 <                    }
1840 <                } finally {
1841 <                    if (!f.casHash(fh | LOCKED, fh)) {
1842 <                        f.hash = fh;
1843 <                        synchronized (f) { f.notifyAll(); };
1844 <                    }
1845 <                }
1846 <                if (count != 0) {
1847 <                    if (tab.length <= 64)
1848 <                        count = 2;
1849 <                    break;
1850 <                }
1851 <            }
1852 <        }
1853 <        if (delta != 0) {
1854 <            counter.add((long)delta);
1855 <            if (count > 1)
1856 <                checkForResize();
1857 <        }
1858 <        return val;
1859 <    }
1860 <
1861 <    /** Implementation for merge */
1862 <    @SuppressWarnings("unchecked") private final Object internalMerge
1863 <        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1864 <        int h = spread(k.hashCode());
1865 <        Object val = null;
1866 <        int delta = 0;
1867 <        int count = 0;
1868 <        for (Node[] tab = table;;) {
1869 <            int i; Node f; int fh; Object fk, fv;
1870 <            if (tab == null)
1871 <                tab = initTable();
1872 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1873 <                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1874 <                    delta = 1;
1875 <                    val = v;
1876 <                    break;
1877 <                }
1878 <            }
1879 <            else if ((fh = f.hash) == MOVED) {
1880 <                if ((fk = f.key) instanceof TreeBin) {
1881 <                    TreeBin t = (TreeBin)fk;
1882 <                    t.acquire(0);
1883 <                    try {
1884 <                        if (tabAt(tab, i) == f) {
1885 <                            count = 1;
1886 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1887 <                            val = (p == null) ? v : mf.apply((V)p.val, v);
1888 <                            if (val != null) {
1889 <                                if (p != null)
1890 <                                    p.val = val;
1891 <                                else {
1892 <                                    count = 2;
1893 <                                    delta = 1;
1894 <                                    t.putTreeNode(h, k, val);
1895 <                                }
1896 <                            }
1897 <                            else if (p != null) {
1898 <                                delta = -1;
1899 <                                t.deleteTreeNode(p);
1900 <                            }
1901 <                        }
1902 <                    } finally {
1903 <                        t.release(0);
1904 <                    }
1905 <                    if (count != 0)
1906 <                        break;
1907 <                }
1908 <                else
1909 <                    tab = (Node[])fk;
1910 <            }
1911 <            else if ((fh & LOCKED) != 0) {
1912 <                checkForResize();
1913 <                f.tryAwaitLock(tab, i);
1914 <            }
1915 <            else if (f.casHash(fh, fh | LOCKED)) {
1916 <                try {
1917 <                    if (tabAt(tab, i) == f) {
1918 <                        count = 1;
1919 <                        for (Node e = f, pred = null;; ++count) {
1920 <                            Object ek, ev;
1921 <                            if ((e.hash & HASH_BITS) == h &&
1922 <                                (ev = e.val) != null &&
1923 <                                ((ek = e.key) == k || k.equals(ek))) {
1924 <                                val = mf.apply(v, (V)ev);
1925 <                                if (val != null)
1926 <                                    e.val = val;
1927 <                                else {
1928 <                                    delta = -1;
1929 <                                    Node en = e.next;
1930 <                                    if (pred != null)
1931 <                                        pred.next = en;
1932 <                                    else
1933 <                                        setTabAt(tab, i, en);
1934 <                                }
1935 <                                break;
1936 <                            }
1937 <                            pred = e;
1938 <                            if ((e = e.next) == null) {
1939 <                                val = v;
1940 <                                pred.next = new Node(h, k, val, null);
1941 <                                delta = 1;
1942 <                                if (count >= TREE_THRESHOLD)
1943 <                                    replaceWithTreeBin(tab, i, k);
1944 <                                break;
1945 <                            }
1946 <                        }
1947 <                    }
1948 <                } finally {
1949 <                    if (!f.casHash(fh | LOCKED, fh)) {
1950 <                        f.hash = fh;
1951 <                        synchronized (f) { f.notifyAll(); };
1952 <                    }
1953 <                }
1954 <                if (count != 0) {
1955 <                    if (tab.length <= 64)
1956 <                        count = 2;
1957 <                    break;
1958 <                }
1959 <            }
1960 <        }
1961 <        if (delta != 0) {
1962 <            counter.add((long)delta);
1963 <            if (count > 1)
1964 <                checkForResize();
1965 <        }
1966 <        return val;
655 >    static final int spread(int h) {
656 >        return (h ^ (h >>> 16)) & HASH_BITS;
657      }
658  
1969    /** Implementation for putAll */
1970    private final void internalPutAll(Map<?, ?> m) {
1971        tryPresize(m.size());
1972        long delta = 0L;     // number of uncommitted additions
1973        boolean npe = false; // to throw exception on exit for nulls
1974        try {                // to clean up counts on other exceptions
1975            for (Map.Entry<?, ?> entry : m.entrySet()) {
1976                Object k, v;
1977                if (entry == null || (k = entry.getKey()) == null ||
1978                    (v = entry.getValue()) == null) {
1979                    npe = true;
1980                    break;
1981                }
1982                int h = spread(k.hashCode());
1983                for (Node[] tab = table;;) {
1984                    int i; Node f; int fh; Object fk;
1985                    if (tab == null)
1986                        tab = initTable();
1987                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1988                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1989                            ++delta;
1990                            break;
1991                        }
1992                    }
1993                    else if ((fh = f.hash) == MOVED) {
1994                        if ((fk = f.key) instanceof TreeBin) {
1995                            TreeBin t = (TreeBin)fk;
1996                            boolean validated = false;
1997                            t.acquire(0);
1998                            try {
1999                                if (tabAt(tab, i) == f) {
2000                                    validated = true;
2001                                    TreeNode p = t.getTreeNode(h, k, t.root);
2002                                    if (p != null)
2003                                        p.val = v;
2004                                    else {
2005                                        t.putTreeNode(h, k, v);
2006                                        ++delta;
2007                                    }
2008                                }
2009                            } finally {
2010                                t.release(0);
2011                            }
2012                            if (validated)
2013                                break;
2014                        }
2015                        else
2016                            tab = (Node[])fk;
2017                    }
2018                    else if ((fh & LOCKED) != 0) {
2019                        counter.add(delta);
2020                        delta = 0L;
2021                        checkForResize();
2022                        f.tryAwaitLock(tab, i);
2023                    }
2024                    else if (f.casHash(fh, fh | LOCKED)) {
2025                        int count = 0;
2026                        try {
2027                            if (tabAt(tab, i) == f) {
2028                                count = 1;
2029                                for (Node e = f;; ++count) {
2030                                    Object ek, ev;
2031                                    if ((e.hash & HASH_BITS) == h &&
2032                                        (ev = e.val) != null &&
2033                                        ((ek = e.key) == k || k.equals(ek))) {
2034                                        e.val = v;
2035                                        break;
2036                                    }
2037                                    Node last = e;
2038                                    if ((e = e.next) == null) {
2039                                        ++delta;
2040                                        last.next = new Node(h, k, v, null);
2041                                        if (count >= TREE_THRESHOLD)
2042                                            replaceWithTreeBin(tab, i, k);
2043                                        break;
2044                                    }
2045                                }
2046                            }
2047                        } finally {
2048                            if (!f.casHash(fh | LOCKED, fh)) {
2049                                f.hash = fh;
2050                                synchronized (f) { f.notifyAll(); };
2051                            }
2052                        }
2053                        if (count != 0) {
2054                            if (count > 1) {
2055                                counter.add(delta);
2056                                delta = 0L;
2057                                checkForResize();
2058                            }
2059                            break;
2060                        }
2061                    }
2062                }
2063            }
2064        } finally {
2065            if (delta != 0)
2066                counter.add(delta);
2067        }
2068        if (npe)
2069            throw new NullPointerException();
2070    }
2071
2072    /* ---------------- Table Initialization and Resizing -------------- */
2073
659      /**
660       * Returns a power of two table size for the given desired capacity.
661       * See Hackers Delight, sec 3.2
# Line 2086 | Line 671 | public class ConcurrentHashMap<K, V>
671      }
672  
673      /**
674 <     * Initializes table, using the size recorded in sizeCtl.
674 >     * Returns x's Class if it is of the form "class C implements
675 >     * Comparable<C>", else null.
676       */
677 <    private final Node[] initTable() {
678 <        Node[] tab; int sc;
679 <        while ((tab = table) == null) {
680 <            if ((sc = sizeCtl) < 0)
681 <                Thread.yield(); // lost initialization race; just spin
682 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
683 <                try {
684 <                    if ((tab = table) == null) {
685 <                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
686 <                        tab = table = new Node[n];
687 <                        sc = n - (n >>> 2);
688 <                    }
689 <                } finally {
2104 <                    sizeCtl = sc;
2105 <                }
2106 <                break;
2107 <            }
2108 <        }
2109 <        return tab;
2110 <    }
2111 <
2112 <    /**
2113 <     * If table is too small and not already resizing, creates next
2114 <     * table and transfers bins.  Rechecks occupancy after a transfer
2115 <     * to see if another resize is already needed because resizings
2116 <     * are lagging additions.
2117 <     */
2118 <    private final void checkForResize() {
2119 <        Node[] tab; int n, sc;
2120 <        while ((tab = table) != null &&
2121 <               (n = tab.length) < MAXIMUM_CAPACITY &&
2122 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
2123 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
2124 <            try {
2125 <                if (tab == table) {
2126 <                    table = rebuild(tab);
2127 <                    sc = (n << 1) - (n >>> 1);
677 >    static Class<?> comparableClassFor(Object x) {
678 >        if (x instanceof Comparable) {
679 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
680 >            if ((c = x.getClass()) == String.class) // bypass checks
681 >                return c;
682 >            if ((ts = c.getGenericInterfaces()) != null) {
683 >                for (int i = 0; i < ts.length; ++i) {
684 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
685 >                        ((p = (ParameterizedType)t).getRawType() ==
686 >                         Comparable.class) &&
687 >                        (as = p.getActualTypeArguments()) != null &&
688 >                        as.length == 1 && as[0] == c) // type arg is c
689 >                        return c;
690                  }
2129            } finally {
2130                sizeCtl = sc;
691              }
692          }
693 +        return null;
694      }
695  
696      /**
697 <     * Tries to presize table to accommodate the given number of elements.
698 <     *
2138 <     * @param size number of elements (doesn't need to be perfectly accurate)
697 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
698 >     * class), else 0.
699       */
700 <    private final void tryPresize(int size) {
701 <        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
702 <            tableSizeFor(size + (size >>> 1) + 1);
703 <        int sc;
2144 <        while ((sc = sizeCtl) >= 0) {
2145 <            Node[] tab = table; int n;
2146 <            if (tab == null || (n = tab.length) == 0) {
2147 <                n = (sc > c) ? sc : c;
2148 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
2149 <                    try {
2150 <                        if (table == tab) {
2151 <                            table = new Node[n];
2152 <                            sc = n - (n >>> 2);
2153 <                        }
2154 <                    } finally {
2155 <                        sizeCtl = sc;
2156 <                    }
2157 <                }
2158 <            }
2159 <            else if (c <= sc || n >= MAXIMUM_CAPACITY)
2160 <                break;
2161 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
2162 <                try {
2163 <                    if (table == tab) {
2164 <                        table = rebuild(tab);
2165 <                        sc = (n << 1) - (n >>> 1);
2166 <                    }
2167 <                } finally {
2168 <                    sizeCtl = sc;
2169 <                }
2170 <            }
2171 <        }
700 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
701 >    static int compareComparables(Class<?> kc, Object k, Object x) {
702 >        return (x == null || x.getClass() != kc ? 0 :
703 >                ((Comparable)k).compareTo(x));
704      }
705  
706 +    /* ---------------- Table element access -------------- */
707 +
708      /*
709 <     * Moves and/or copies the nodes in each bin to new table. See
710 <     * above for explanation.
711 <     *
712 <     * @return the new table
713 <     */
714 <    private static final Node[] rebuild(Node[] tab) {
715 <        int n = tab.length;
716 <        Node[] nextTab = new Node[n << 1];
717 <        Node fwd = new Node(MOVED, nextTab, null, null);
718 <        int[] buffer = null;       // holds bins to revisit; null until needed
719 <        Node rev = null;           // reverse forwarder; null until needed
720 <        int nbuffered = 0;         // the number of bins in buffer list
721 <        int bufferIndex = 0;       // buffer index of current buffered bin
722 <        int bin = n - 1;           // current non-buffered bin or -1 if none
723 <
724 <        for (int i = bin;;) {      // start upwards sweep
725 <            int fh; Node f;
726 <            if ((f = tabAt(tab, i)) == null) {
727 <                if (bin >= 0) {    // Unbuffered; no lock needed (or available)
728 <                    if (!casTabAt(tab, i, f, fwd))
729 <                        continue;
730 <                }
731 <                else {             // transiently use a locked forwarding node
2198 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2199 <                    if (!casTabAt(tab, i, f, g))
2200 <                        continue;
2201 <                    setTabAt(nextTab, i, null);
2202 <                    setTabAt(nextTab, i + n, null);
2203 <                    setTabAt(tab, i, fwd);
2204 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2205 <                        g.hash = MOVED;
2206 <                        synchronized (g) { g.notifyAll(); }
2207 <                    }
2208 <                }
2209 <            }
2210 <            else if ((fh = f.hash) == MOVED) {
2211 <                Object fk = f.key;
2212 <                if (fk instanceof TreeBin) {
2213 <                    TreeBin t = (TreeBin)fk;
2214 <                    boolean validated = false;
2215 <                    t.acquire(0);
2216 <                    try {
2217 <                        if (tabAt(tab, i) == f) {
2218 <                            validated = true;
2219 <                            splitTreeBin(nextTab, i, t);
2220 <                            setTabAt(tab, i, fwd);
2221 <                        }
2222 <                    } finally {
2223 <                        t.release(0);
2224 <                    }
2225 <                    if (!validated)
2226 <                        continue;
2227 <                }
2228 <            }
2229 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2230 <                boolean validated = false;
2231 <                try {              // split to lo and hi lists; copying as needed
2232 <                    if (tabAt(tab, i) == f) {
2233 <                        validated = true;
2234 <                        splitBin(nextTab, i, f);
2235 <                        setTabAt(tab, i, fwd);
2236 <                    }
2237 <                } finally {
2238 <                    if (!f.casHash(fh | LOCKED, fh)) {
2239 <                        f.hash = fh;
2240 <                        synchronized (f) { f.notifyAll(); };
2241 <                    }
2242 <                }
2243 <                if (!validated)
2244 <                    continue;
2245 <            }
2246 <            else {
2247 <                if (buffer == null) // initialize buffer for revisits
2248 <                    buffer = new int[TRANSFER_BUFFER_SIZE];
2249 <                if (bin < 0 && bufferIndex > 0) {
2250 <                    int j = buffer[--bufferIndex];
2251 <                    buffer[bufferIndex] = i;
2252 <                    i = j;         // swap with another bin
2253 <                    continue;
2254 <                }
2255 <                if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
2256 <                    f.tryAwaitLock(tab, i);
2257 <                    continue;      // no other options -- block
2258 <                }
2259 <                if (rev == null)   // initialize reverse-forwarder
2260 <                    rev = new Node(MOVED, tab, null, null);
2261 <                if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
2262 <                    continue;      // recheck before adding to list
2263 <                buffer[nbuffered++] = i;
2264 <                setTabAt(nextTab, i, rev);     // install place-holders
2265 <                setTabAt(nextTab, i + n, rev);
2266 <            }
2267 <
2268 <            if (bin > 0)
2269 <                i = --bin;
2270 <            else if (buffer != null && nbuffered > 0) {
2271 <                bin = -1;
2272 <                i = buffer[bufferIndex = --nbuffered];
2273 <            }
2274 <            else
2275 <                return nextTab;
2276 <        }
709 >     * Volatile access methods are used for table elements as well as
710 >     * elements of in-progress next table while resizing.  All uses of
711 >     * the tab arguments must be null checked by callers.  All callers
712 >     * also paranoically precheck that tab's length is not zero (or an
713 >     * equivalent check), thus ensuring that any index argument taking
714 >     * the form of a hash value anded with (length - 1) is a valid
715 >     * index.  Note that, to be correct wrt arbitrary concurrency
716 >     * errors by users, these checks must operate on local variables,
717 >     * which accounts for some odd-looking inline assignments below.
718 >     * Note that calls to setTabAt always occur within locked regions,
719 >     * and so in principle require only release ordering, not
720 >     * full volatile semantics, but are currently coded as volatile
721 >     * writes to be conservative.
722 >     */
723 >
724 >    @SuppressWarnings("unchecked")
725 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
726 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
727 >    }
728 >
729 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
730 >                                        Node<K,V> c, Node<K,V> v) {
731 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
732      }
733  
734 <    /**
735 <     * Splits a normal bin with list headed by e into lo and hi parts;
2281 <     * installs in given table.
2282 <     */
2283 <    private static void splitBin(Node[] nextTab, int i, Node e) {
2284 <        int bit = nextTab.length >>> 1; // bit to split on
2285 <        int runBit = e.hash & bit;
2286 <        Node lastRun = e, lo = null, hi = null;
2287 <        for (Node p = e.next; p != null; p = p.next) {
2288 <            int b = p.hash & bit;
2289 <            if (b != runBit) {
2290 <                runBit = b;
2291 <                lastRun = p;
2292 <            }
2293 <        }
2294 <        if (runBit == 0)
2295 <            lo = lastRun;
2296 <        else
2297 <            hi = lastRun;
2298 <        for (Node p = e; p != lastRun; p = p.next) {
2299 <            int ph = p.hash & HASH_BITS;
2300 <            Object pk = p.key, pv = p.val;
2301 <            if ((ph & bit) == 0)
2302 <                lo = new Node(ph, pk, pv, lo);
2303 <            else
2304 <                hi = new Node(ph, pk, pv, hi);
2305 <        }
2306 <        setTabAt(nextTab, i, lo);
2307 <        setTabAt(nextTab, i + bit, hi);
734 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
735 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
736      }
737  
738 +    /* ---------------- Fields -------------- */
739 +
740      /**
741 <     * Splits a tree bin into lo and hi parts; installs in given table.
741 >     * The array of bins. Lazily initialized upon first insertion.
742 >     * Size is always a power of two. Accessed directly by iterators.
743       */
744 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2314 <        int bit = nextTab.length >>> 1;
2315 <        TreeBin lt = new TreeBin();
2316 <        TreeBin ht = new TreeBin();
2317 <        int lc = 0, hc = 0;
2318 <        for (Node e = t.first; e != null; e = e.next) {
2319 <            int h = e.hash & HASH_BITS;
2320 <            Object k = e.key, v = e.val;
2321 <            if ((h & bit) == 0) {
2322 <                ++lc;
2323 <                lt.putTreeNode(h, k, v);
2324 <            }
2325 <            else {
2326 <                ++hc;
2327 <                ht.putTreeNode(h, k, v);
2328 <            }
2329 <        }
2330 <        Node ln, hn; // throw away trees if too small
2331 <        if (lc <= (TREE_THRESHOLD >>> 1)) {
2332 <            ln = null;
2333 <            for (Node p = lt.first; p != null; p = p.next)
2334 <                ln = new Node(p.hash, p.key, p.val, ln);
2335 <        }
2336 <        else
2337 <            ln = new Node(MOVED, lt, null, null);
2338 <        setTabAt(nextTab, i, ln);
2339 <        if (hc <= (TREE_THRESHOLD >>> 1)) {
2340 <            hn = null;
2341 <            for (Node p = ht.first; p != null; p = p.next)
2342 <                hn = new Node(p.hash, p.key, p.val, hn);
2343 <        }
2344 <        else
2345 <            hn = new Node(MOVED, ht, null, null);
2346 <        setTabAt(nextTab, i + bit, hn);
2347 <    }
744 >    transient volatile Node<K,V>[] table;
745  
746      /**
747 <     * Implementation for clear. Steps through each bin, removing all
2351 <     * nodes.
747 >     * The next table to use; non-null only while resizing.
748       */
749 <    private final void internalClear() {
2354 <        long delta = 0L; // negative number of deletions
2355 <        int i = 0;
2356 <        Node[] tab = table;
2357 <        while (tab != null && i < tab.length) {
2358 <            int fh; Object fk;
2359 <            Node f = tabAt(tab, i);
2360 <            if (f == null)
2361 <                ++i;
2362 <            else if ((fh = f.hash) == MOVED) {
2363 <                if ((fk = f.key) instanceof TreeBin) {
2364 <                    TreeBin t = (TreeBin)fk;
2365 <                    t.acquire(0);
2366 <                    try {
2367 <                        if (tabAt(tab, i) == f) {
2368 <                            for (Node p = t.first; p != null; p = p.next) {
2369 <                                if (p.val != null) { // (currently always true)
2370 <                                    p.val = null;
2371 <                                    --delta;
2372 <                                }
2373 <                            }
2374 <                            t.first = null;
2375 <                            t.root = null;
2376 <                            ++i;
2377 <                        }
2378 <                    } finally {
2379 <                        t.release(0);
2380 <                    }
2381 <                }
2382 <                else
2383 <                    tab = (Node[])fk;
2384 <            }
2385 <            else if ((fh & LOCKED) != 0) {
2386 <                counter.add(delta); // opportunistically update count
2387 <                delta = 0L;
2388 <                f.tryAwaitLock(tab, i);
2389 <            }
2390 <            else if (f.casHash(fh, fh | LOCKED)) {
2391 <                try {
2392 <                    if (tabAt(tab, i) == f) {
2393 <                        for (Node e = f; e != null; e = e.next) {
2394 <                            if (e.val != null) {  // (currently always true)
2395 <                                e.val = null;
2396 <                                --delta;
2397 <                            }
2398 <                        }
2399 <                        setTabAt(tab, i, null);
2400 <                        ++i;
2401 <                    }
2402 <                } finally {
2403 <                    if (!f.casHash(fh | LOCKED, fh)) {
2404 <                        f.hash = fh;
2405 <                        synchronized (f) { f.notifyAll(); };
2406 <                    }
2407 <                }
2408 <            }
2409 <        }
2410 <        if (delta != 0)
2411 <            counter.add(delta);
2412 <    }
2413 <
2414 <    /* ----------------Table Traversal -------------- */
749 >    private transient volatile Node<K,V>[] nextTable;
750  
751      /**
752 <     * Encapsulates traversal for methods such as containsValue; also
753 <     * serves as a base class for other iterators and bulk tasks.
754 <     *
755 <     * At each step, the iterator snapshots the key ("nextKey") and
756 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2422 <     * snapshot, has a non-null user value). Because val fields can
2423 <     * change (including to null, indicating deletion), field nextVal
2424 <     * might not be accurate at point of use, but still maintains the
2425 <     * weak consistency property of holding a value that was once
2426 <     * valid. To support iterator.remove, the nextKey field is not
2427 <     * updated (nulled out) when the iterator cannot advance.
2428 <     *
2429 <     * Internal traversals directly access these fields, as in:
2430 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2431 <     *
2432 <     * Exported iterators must track whether the iterator has advanced
2433 <     * (in hasNext vs next) (by setting/checking/nulling field
2434 <     * nextVal), and then extract key, value, or key-value pairs as
2435 <     * return values of next().
2436 <     *
2437 <     * The iterator visits once each still-valid node that was
2438 <     * reachable upon iterator construction. It might miss some that
2439 <     * were added to a bin after the bin was visited, which is OK wrt
2440 <     * consistency guarantees. Maintaining this property in the face
2441 <     * of possible ongoing resizes requires a fair amount of
2442 <     * bookkeeping state that is difficult to optimize away amidst
2443 <     * volatile accesses.  Even so, traversal maintains reasonable
2444 <     * throughput.
2445 <     *
2446 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2447 <     * However, if the table has been resized, then all future steps
2448 <     * must traverse both the bin at the current index as well as at
2449 <     * (index + baseSize); and so on for further resizings. To
2450 <     * paranoically cope with potential sharing by users of iterators
2451 <     * across threads, iteration terminates if a bounds checks fails
2452 <     * for a table read.
2453 <     *
2454 <     * This class extends ForkJoinTask to streamline parallel
2455 <     * iteration in bulk operations (see BulkTask). This adds only an
2456 <     * int of space overhead, which is close enough to negligible in
2457 <     * cases where it is not needed to not worry about it.  Because
2458 <     * ForkJoinTask is Serializable, but iterators need not be, we
2459 <     * need to add warning suppressions.
2460 <     */
2461 <    @SuppressWarnings("serial") static class Traverser<K,V,R> extends ForkJoinTask<R> {
2462 <        final ConcurrentHashMap<K, V> map;
2463 <        Node next;           // the next entry to use
2464 <        Object nextKey;      // cached key field of next
2465 <        Object nextVal;      // cached val field of next
2466 <        Node[] tab;          // current table; updated if resized
2467 <        int index;           // index of bin to use next
2468 <        int baseIndex;       // current index of initial table
2469 <        int baseLimit;       // index bound for initial table
2470 <        int baseSize;        // initial table size
752 >     * Base counter value, used mainly when there is no contention,
753 >     * but also as a fallback during table initialization
754 >     * races. Updated via CAS.
755 >     */
756 >    private transient volatile long baseCount;
757  
758 <        /** Creates iterator for all entries in the table. */
759 <        Traverser(ConcurrentHashMap<K, V> map) {
760 <            this.map = map;
761 <        }
758 >    /**
759 >     * Table initialization and resizing control.  When negative, the
760 >     * table is being initialized or resized: -1 for initialization,
761 >     * else -(1 + the number of active resizing threads).  Otherwise,
762 >     * when table is null, holds the initial table size to use upon
763 >     * creation, or 0 for default. After initialization, holds the
764 >     * next element count value upon which to resize the table.
765 >     */
766 >    private transient volatile int sizeCtl;
767  
768 <        /** Creates iterator for split() methods */
769 <        Traverser(Traverser<K,V,?> it) {
770 <            ConcurrentHashMap<K, V> m; Node[] t;
771 <            if ((m = this.map = it.map) == null)
2481 <                t = null;
2482 <            else if ((t = it.tab) == null && // force parent tab initialization
2483 <                     (t = it.tab = m.table) != null)
2484 <                it.baseLimit = it.baseSize = t.length;
2485 <            this.tab = t;
2486 <            this.baseSize = it.baseSize;
2487 <            it.baseLimit = this.index = this.baseIndex =
2488 <                ((this.baseLimit = it.baseLimit) + it.baseIndex + 1) >>> 1;
2489 <        }
768 >    /**
769 >     * The next table index (plus one) to split while resizing.
770 >     */
771 >    private transient volatile int transferIndex;
772  
773 <        /**
774 <         * Advances next; returns nextVal or null if terminated.
775 <         * See above for explanation.
776 <         */
2495 <        final Object advance() {
2496 <            Node e = next;
2497 <            Object ev = null;
2498 <            outer: do {
2499 <                if (e != null)                  // advance past used/skipped node
2500 <                    e = e.next;
2501 <                while (e == null) {             // get to next non-null bin
2502 <                    ConcurrentHashMap<K, V> m;
2503 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2504 <                    if ((t = tab) != null)
2505 <                        n = t.length;
2506 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2507 <                        n = baseLimit = baseSize = t.length;
2508 <                    else
2509 <                        break outer;
2510 <                    if ((b = baseIndex) >= baseLimit ||
2511 <                        (i = index) < 0 || i >= n)
2512 <                        break outer;
2513 <                    if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2514 <                        if ((ek = e.key) instanceof TreeBin)
2515 <                            e = ((TreeBin)ek).first;
2516 <                        else {
2517 <                            tab = (Node[])ek;
2518 <                            continue;           // restarts due to null val
2519 <                        }
2520 <                    }                           // visit upper slots if present
2521 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2522 <                }
2523 <                nextKey = e.key;
2524 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2525 <            next = e;
2526 <            return nextVal = ev;
2527 <        }
773 >    /**
774 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
775 >     */
776 >    private transient volatile int cellsBusy;
777  
778 <        public final void remove() {
779 <            Object k = nextKey;
780 <            if (k == null && (advance() == null || (k = nextKey) == null))
781 <                throw new IllegalStateException();
2533 <            map.internalReplace(k, null, null);
2534 <        }
778 >    /**
779 >     * Table of counter cells. When non-null, size is a power of 2.
780 >     */
781 >    private transient volatile CounterCell[] counterCells;
782  
783 <        public final boolean hasNext() {
784 <            return nextVal != null || advance() != null;
785 <        }
783 >    // views
784 >    private transient KeySetView<K,V> keySet;
785 >    private transient ValuesView<K,V> values;
786 >    private transient EntrySetView<K,V> entrySet;
787  
2540        public final boolean hasMoreElements() { return hasNext(); }
2541        public final void setRawResult(Object x) { }
2542        public R getRawResult() { return null; }
2543        public boolean exec() { return true; }
2544    }
788  
789      /* ---------------- Public operations -------------- */
790  
# Line 2549 | Line 792 | public class ConcurrentHashMap<K, V>
792       * Creates a new, empty map with the default initial table size (16).
793       */
794      public ConcurrentHashMap() {
2552        this.counter = new LongAdder();
795      }
796  
797      /**
# Line 2568 | Line 810 | public class ConcurrentHashMap<K, V>
810          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
811                     MAXIMUM_CAPACITY :
812                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2571        this.counter = new LongAdder();
813          this.sizeCtl = cap;
814      }
815  
# Line 2578 | Line 819 | public class ConcurrentHashMap<K, V>
819       * @param m the map
820       */
821      public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2581        this.counter = new LongAdder();
822          this.sizeCtl = DEFAULT_CAPACITY;
823 <        internalPutAll(m);
823 >        putAll(m);
824      }
825  
826      /**
# Line 2621 | Line 861 | public class ConcurrentHashMap<K, V>
861       * nonpositive
862       */
863      public ConcurrentHashMap(int initialCapacity,
864 <                               float loadFactor, int concurrencyLevel) {
864 >                             float loadFactor, int concurrencyLevel) {
865          if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
866              throw new IllegalArgumentException();
867          if (initialCapacity < concurrencyLevel)   // Use at least as many bins
# Line 2629 | Line 869 | public class ConcurrentHashMap<K, V>
869          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
870          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
871              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2632        this.counter = new LongAdder();
872          this.sizeCtl = cap;
873      }
874  
875 <    /**
2637 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2638 <     * from the given type to {@code Boolean.TRUE}.
2639 <     *
2640 <     * @return the new set
2641 <     */
2642 <    public static <K> KeySetView<K,Boolean> newKeySet() {
2643 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(),
2644 <                                      Boolean.TRUE);
2645 <    }
2646 <
2647 <    /**
2648 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2649 <     * from the given type to {@code Boolean.TRUE}.
2650 <     *
2651 <     * @param initialCapacity The implementation performs internal
2652 <     * sizing to accommodate this many elements.
2653 <     * @throws IllegalArgumentException if the initial capacity of
2654 <     * elements is negative
2655 <     * @return the new set
2656 <     */
2657 <    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2658 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(initialCapacity),
2659 <                                      Boolean.TRUE);
2660 <    }
2661 <
2662 <    /**
2663 <     * {@inheritDoc}
2664 <     */
2665 <    public boolean isEmpty() {
2666 <        return counter.sum() <= 0L; // ignore transient negative values
2667 <    }
875 >    // Original (since JDK1.2) Map methods
876  
877      /**
878       * {@inheritDoc}
879       */
880      public int size() {
881 <        long n = counter.sum();
881 >        long n = sumCount();
882          return ((n < 0L) ? 0 :
883                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
884                  (int)n);
885      }
886  
887      /**
888 <     * Returns the number of mappings. This method should be used
2681 <     * instead of {@link #size} because a ConcurrentHashMap may
2682 <     * contain more mappings than can be represented as an int. The
2683 <     * value returned is a snapshot; the actual count may differ if
2684 <     * there are ongoing concurrent insertions or removals.
2685 <     *
2686 <     * @return the number of mappings
888 >     * {@inheritDoc}
889       */
890 <    public long mappingCount() {
891 <        long n = counter.sum();
2690 <        return (n < 0L) ? 0L : n; // ignore transient negative values
890 >    public boolean isEmpty() {
891 >        return sumCount() <= 0L; // ignore transient negative values
892      }
893  
894      /**
# Line 2701 | Line 902 | public class ConcurrentHashMap<K, V>
902       *
903       * @throws NullPointerException if the specified key is null
904       */
905 <    @SuppressWarnings("unchecked") public V get(Object key) {
906 <        if (key == null)
907 <            throw new NullPointerException();
908 <        return (V)internalGet(key);
909 <    }
910 <
911 <    /**
912 <     * Returns the value to which the specified key is mapped,
913 <     * or the given defaultValue if this map contains no mapping for the key.
914 <     *
915 <     * @param key the key
916 <     * @param defaultValue the value to return if this map contains
917 <     * no mapping for the given key
918 <     * @return the mapping for the key, if present; else the defaultValue
919 <     * @throws NullPointerException if the specified key is null
920 <     */
921 <    @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) {
922 <        if (key == null)
2722 <            throw new NullPointerException();
2723 <        V v = (V) internalGet(key);
2724 <        return v == null ? defaultValue : v;
905 >    public V get(Object key) {
906 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
907 >        int h = spread(key.hashCode());
908 >        if ((tab = table) != null && (n = tab.length) > 0 &&
909 >            (e = tabAt(tab, (n - 1) & h)) != null) {
910 >            if ((eh = e.hash) == h) {
911 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
912 >                    return e.val;
913 >            }
914 >            else if (eh < 0)
915 >                return (p = e.find(h, key)) != null ? p.val : null;
916 >            while ((e = e.next) != null) {
917 >                if (e.hash == h &&
918 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
919 >                    return e.val;
920 >            }
921 >        }
922 >        return null;
923      }
924  
925      /**
926       * Tests if the specified object is a key in this table.
927       *
928 <     * @param  key   possible key
928 >     * @param  key possible key
929       * @return {@code true} if and only if the specified object
930       *         is a key in this table, as determined by the
931       *         {@code equals} method; {@code false} otherwise
932       * @throws NullPointerException if the specified key is null
933       */
934      public boolean containsKey(Object key) {
935 <        if (key == null)
2738 <            throw new NullPointerException();
2739 <        return internalGet(key) != null;
935 >        return get(key) != null;
936      }
937  
938      /**
# Line 2752 | Line 948 | public class ConcurrentHashMap<K, V>
948      public boolean containsValue(Object value) {
949          if (value == null)
950              throw new NullPointerException();
951 <        Object v;
952 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
953 <        while ((v = it.advance()) != null) {
954 <            if (v == value || value.equals(v))
955 <                return true;
951 >        Node<K,V>[] t;
952 >        if ((t = table) != null) {
953 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
954 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
955 >                V v;
956 >                if ((v = p.val) == value || (v != null && value.equals(v)))
957 >                    return true;
958 >            }
959          }
960          return false;
961      }
962  
963      /**
2765     * Legacy method testing if some key maps into the specified value
2766     * in this table.  This method is identical in functionality to
2767     * {@link #containsValue}, and exists solely to ensure
2768     * full compatibility with class {@link java.util.Hashtable},
2769     * which supported this method prior to introduction of the
2770     * Java Collections framework.
2771     *
2772     * @param  value a value to search for
2773     * @return {@code true} if and only if some key maps to the
2774     *         {@code value} argument in this table as
2775     *         determined by the {@code equals} method;
2776     *         {@code false} otherwise
2777     * @throws NullPointerException if the specified value is null
2778     */
2779    public boolean contains(Object value) {
2780        return containsValue(value);
2781    }
2782
2783    /**
964       * Maps the specified key to the specified value in this table.
965       * Neither the key nor the value can be null.
966       *
967 <     * <p> The value can be retrieved by calling the {@code get} method
967 >     * <p>The value can be retrieved by calling the {@code get} method
968       * with a key that is equal to the original key.
969       *
970       * @param key key with which the specified value is to be associated
# Line 2793 | Line 973 | public class ConcurrentHashMap<K, V>
973       *         {@code null} if there was no mapping for {@code key}
974       * @throws NullPointerException if the specified key or value is null
975       */
976 <    @SuppressWarnings("unchecked") public V put(K key, V value) {
977 <        if (key == null || value == null)
976 >    public V put(K key, V value) {
977 >        return putVal(key, value, false);
978 >    }
979 >
980 >    /** Implementation for put and putIfAbsent */
981 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
982 >        if (key == null || value == null) throw new NullPointerException();
983 >        int hash = spread(key.hashCode());
984 >        int binCount = 0;
985 >        for (Node<K,V>[] tab = table;;) {
986 >            Node<K,V> f; int n, i, fh;
987 >            if (tab == null || (n = tab.length) == 0)
988 >                tab = initTable();
989 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
990 >                if (casTabAt(tab, i, null,
991 >                             new Node<K,V>(hash, key, value, null)))
992 >                    break;                   // no lock when adding to empty bin
993 >            }
994 >            else if ((fh = f.hash) == MOVED)
995 >                tab = helpTransfer(tab, f);
996 >            else {
997 >                V oldVal = null;
998 >                synchronized (f) {
999 >                    if (tabAt(tab, i) == f) {
1000 >                        if (fh >= 0) {
1001 >                            binCount = 1;
1002 >                            for (Node<K,V> e = f;; ++binCount) {
1003 >                                K ek;
1004 >                                if (e.hash == hash &&
1005 >                                    ((ek = e.key) == key ||
1006 >                                     (ek != null && key.equals(ek)))) {
1007 >                                    oldVal = e.val;
1008 >                                    if (!onlyIfAbsent)
1009 >                                        e.val = value;
1010 >                                    break;
1011 >                                }
1012 >                                Node<K,V> pred = e;
1013 >                                if ((e = e.next) == null) {
1014 >                                    pred.next = new Node<K,V>(hash, key,
1015 >                                                              value, null);
1016 >                                    break;
1017 >                                }
1018 >                            }
1019 >                        }
1020 >                        else if (f instanceof TreeBin) {
1021 >                            Node<K,V> p;
1022 >                            binCount = 2;
1023 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1024 >                                                           value)) != null) {
1025 >                                oldVal = p.val;
1026 >                                if (!onlyIfAbsent)
1027 >                                    p.val = value;
1028 >                            }
1029 >                        }
1030 >                    }
1031 >                }
1032 >                if (binCount != 0) {
1033 >                    if (binCount >= TREEIFY_THRESHOLD)
1034 >                        treeifyBin(tab, i);
1035 >                    if (oldVal != null)
1036 >                        return oldVal;
1037 >                    break;
1038 >                }
1039 >            }
1040 >        }
1041 >        addCount(1L, binCount);
1042 >        return null;
1043 >    }
1044 >
1045 >    /**
1046 >     * Copies all of the mappings from the specified map to this one.
1047 >     * These mappings replace any mappings that this map had for any of the
1048 >     * keys currently in the specified map.
1049 >     *
1050 >     * @param m mappings to be stored in this map
1051 >     */
1052 >    public void putAll(Map<? extends K, ? extends V> m) {
1053 >        tryPresize(m.size());
1054 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1055 >            putVal(e.getKey(), e.getValue(), false);
1056 >    }
1057 >
1058 >    /**
1059 >     * Removes the key (and its corresponding value) from this map.
1060 >     * This method does nothing if the key is not in the map.
1061 >     *
1062 >     * @param  key the key that needs to be removed
1063 >     * @return the previous value associated with {@code key}, or
1064 >     *         {@code null} if there was no mapping for {@code key}
1065 >     * @throws NullPointerException if the specified key is null
1066 >     */
1067 >    public V remove(Object key) {
1068 >        return replaceNode(key, null, null);
1069 >    }
1070 >
1071 >    /**
1072 >     * Implementation for the four public remove/replace methods:
1073 >     * Replaces node value with v, conditional upon match of cv if
1074 >     * non-null.  If resulting value is null, delete.
1075 >     */
1076 >    final V replaceNode(Object key, V value, Object cv) {
1077 >        int hash = spread(key.hashCode());
1078 >        for (Node<K,V>[] tab = table;;) {
1079 >            Node<K,V> f; int n, i, fh;
1080 >            if (tab == null || (n = tab.length) == 0 ||
1081 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1082 >                break;
1083 >            else if ((fh = f.hash) == MOVED)
1084 >                tab = helpTransfer(tab, f);
1085 >            else {
1086 >                V oldVal = null;
1087 >                boolean validated = false;
1088 >                synchronized (f) {
1089 >                    if (tabAt(tab, i) == f) {
1090 >                        if (fh >= 0) {
1091 >                            validated = true;
1092 >                            for (Node<K,V> e = f, pred = null;;) {
1093 >                                K ek;
1094 >                                if (e.hash == hash &&
1095 >                                    ((ek = e.key) == key ||
1096 >                                     (ek != null && key.equals(ek)))) {
1097 >                                    V ev = e.val;
1098 >                                    if (cv == null || cv == ev ||
1099 >                                        (ev != null && cv.equals(ev))) {
1100 >                                        oldVal = ev;
1101 >                                        if (value != null)
1102 >                                            e.val = value;
1103 >                                        else if (pred != null)
1104 >                                            pred.next = e.next;
1105 >                                        else
1106 >                                            setTabAt(tab, i, e.next);
1107 >                                    }
1108 >                                    break;
1109 >                                }
1110 >                                pred = e;
1111 >                                if ((e = e.next) == null)
1112 >                                    break;
1113 >                            }
1114 >                        }
1115 >                        else if (f instanceof TreeBin) {
1116 >                            validated = true;
1117 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1118 >                            TreeNode<K,V> r, p;
1119 >                            if ((r = t.root) != null &&
1120 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1121 >                                V pv = p.val;
1122 >                                if (cv == null || cv == pv ||
1123 >                                    (pv != null && cv.equals(pv))) {
1124 >                                    oldVal = pv;
1125 >                                    if (value != null)
1126 >                                        p.val = value;
1127 >                                    else if (t.removeTreeNode(p))
1128 >                                        setTabAt(tab, i, untreeify(t.first));
1129 >                                }
1130 >                            }
1131 >                        }
1132 >                    }
1133 >                }
1134 >                if (validated) {
1135 >                    if (oldVal != null) {
1136 >                        if (value == null)
1137 >                            addCount(-1L, -1);
1138 >                        return oldVal;
1139 >                    }
1140 >                    break;
1141 >                }
1142 >            }
1143 >        }
1144 >        return null;
1145 >    }
1146 >
1147 >    /**
1148 >     * Removes all of the mappings from this map.
1149 >     */
1150 >    public void clear() {
1151 >        long delta = 0L; // negative number of deletions
1152 >        int i = 0;
1153 >        Node<K,V>[] tab = table;
1154 >        while (tab != null && i < tab.length) {
1155 >            int fh;
1156 >            Node<K,V> f = tabAt(tab, i);
1157 >            if (f == null)
1158 >                ++i;
1159 >            else if ((fh = f.hash) == MOVED) {
1160 >                tab = helpTransfer(tab, f);
1161 >                i = 0; // restart
1162 >            }
1163 >            else {
1164 >                synchronized (f) {
1165 >                    if (tabAt(tab, i) == f) {
1166 >                        Node<K,V> p = (fh >= 0 ? f :
1167 >                                       (f instanceof TreeBin) ?
1168 >                                       ((TreeBin<K,V>)f).first : null);
1169 >                        while (p != null) {
1170 >                            --delta;
1171 >                            p = p.next;
1172 >                        }
1173 >                        setTabAt(tab, i++, null);
1174 >                    }
1175 >                }
1176 >            }
1177 >        }
1178 >        if (delta != 0L)
1179 >            addCount(delta, -1);
1180 >    }
1181 >
1182 >    /**
1183 >     * Returns a {@link Set} view of the keys contained in this map.
1184 >     * The set is backed by the map, so changes to the map are
1185 >     * reflected in the set, and vice-versa. The set supports element
1186 >     * removal, which removes the corresponding mapping from this map,
1187 >     * via the {@code Iterator.remove}, {@code Set.remove},
1188 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1189 >     * operations.  It does not support the {@code add} or
1190 >     * {@code addAll} operations.
1191 >     *
1192 >     * <p>The view's iterators and spliterators are
1193 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1194 >     *
1195 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1196 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1197 >     *
1198 >     * @return the set view
1199 >     */
1200 >    public KeySetView<K,V> keySet() {
1201 >        KeySetView<K,V> ks;
1202 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1203 >    }
1204 >
1205 >    /**
1206 >     * Returns a {@link Collection} view of the values contained in this map.
1207 >     * The collection is backed by the map, so changes to the map are
1208 >     * reflected in the collection, and vice-versa.  The collection
1209 >     * supports element removal, which removes the corresponding
1210 >     * mapping from this map, via the {@code Iterator.remove},
1211 >     * {@code Collection.remove}, {@code removeAll},
1212 >     * {@code retainAll}, and {@code clear} operations.  It does not
1213 >     * support the {@code add} or {@code addAll} operations.
1214 >     *
1215 >     * <p>The view's iterators and spliterators are
1216 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1217 >     *
1218 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}
1219 >     * and {@link Spliterator#NONNULL}.
1220 >     *
1221 >     * @return the collection view
1222 >     */
1223 >    public Collection<V> values() {
1224 >        ValuesView<K,V> vs;
1225 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1226 >    }
1227 >
1228 >    /**
1229 >     * Returns a {@link Set} view of the mappings contained in this map.
1230 >     * The set is backed by the map, so changes to the map are
1231 >     * reflected in the set, and vice-versa.  The set supports element
1232 >     * removal, which removes the corresponding mapping from the map,
1233 >     * via the {@code Iterator.remove}, {@code Set.remove},
1234 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1235 >     * operations.
1236 >     *
1237 >     * <p>The view's iterators and spliterators are
1238 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1239 >     *
1240 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1241 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1242 >     *
1243 >     * @return the set view
1244 >     */
1245 >    public Set<Map.Entry<K,V>> entrySet() {
1246 >        EntrySetView<K,V> es;
1247 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1248 >    }
1249 >
1250 >    /**
1251 >     * Returns the hash code value for this {@link Map}, i.e.,
1252 >     * the sum of, for each key-value pair in the map,
1253 >     * {@code key.hashCode() ^ value.hashCode()}.
1254 >     *
1255 >     * @return the hash code value for this map
1256 >     */
1257 >    public int hashCode() {
1258 >        int h = 0;
1259 >        Node<K,V>[] t;
1260 >        if ((t = table) != null) {
1261 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1262 >            for (Node<K,V> p; (p = it.advance()) != null; )
1263 >                h += p.key.hashCode() ^ p.val.hashCode();
1264 >        }
1265 >        return h;
1266 >    }
1267 >
1268 >    /**
1269 >     * Returns a string representation of this map.  The string
1270 >     * representation consists of a list of key-value mappings (in no
1271 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1272 >     * mappings are separated by the characters {@code ", "} (comma
1273 >     * and space).  Each key-value mapping is rendered as the key
1274 >     * followed by an equals sign ("{@code =}") followed by the
1275 >     * associated value.
1276 >     *
1277 >     * @return a string representation of this map
1278 >     */
1279 >    public String toString() {
1280 >        Node<K,V>[] t;
1281 >        int f = (t = table) == null ? 0 : t.length;
1282 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1283 >        StringBuilder sb = new StringBuilder();
1284 >        sb.append('{');
1285 >        Node<K,V> p;
1286 >        if ((p = it.advance()) != null) {
1287 >            for (;;) {
1288 >                K k = p.key;
1289 >                V v = p.val;
1290 >                sb.append(k == this ? "(this Map)" : k);
1291 >                sb.append('=');
1292 >                sb.append(v == this ? "(this Map)" : v);
1293 >                if ((p = it.advance()) == null)
1294 >                    break;
1295 >                sb.append(',').append(' ');
1296 >            }
1297 >        }
1298 >        return sb.append('}').toString();
1299 >    }
1300 >
1301 >    /**
1302 >     * Compares the specified object with this map for equality.
1303 >     * Returns {@code true} if the given object is a map with the same
1304 >     * mappings as this map.  This operation may return misleading
1305 >     * results if either map is concurrently modified during execution
1306 >     * of this method.
1307 >     *
1308 >     * @param o object to be compared for equality with this map
1309 >     * @return {@code true} if the specified object is equal to this map
1310 >     */
1311 >    public boolean equals(Object o) {
1312 >        if (o != this) {
1313 >            if (!(o instanceof Map))
1314 >                return false;
1315 >            Map<?,?> m = (Map<?,?>) o;
1316 >            Node<K,V>[] t;
1317 >            int f = (t = table) == null ? 0 : t.length;
1318 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1319 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1320 >                V val = p.val;
1321 >                Object v = m.get(p.key);
1322 >                if (v == null || (v != val && !v.equals(val)))
1323 >                    return false;
1324 >            }
1325 >            for (Map.Entry<?,?> e : m.entrySet()) {
1326 >                Object mk, mv, v;
1327 >                if ((mk = e.getKey()) == null ||
1328 >                    (mv = e.getValue()) == null ||
1329 >                    (v = get(mk)) == null ||
1330 >                    (mv != v && !mv.equals(v)))
1331 >                    return false;
1332 >            }
1333 >        }
1334 >        return true;
1335 >    }
1336 >
1337 >    /**
1338 >     * Stripped-down version of helper class used in previous version,
1339 >     * declared for the sake of serialization compatibility
1340 >     */
1341 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1342 >        private static final long serialVersionUID = 2249069246763182397L;
1343 >        final float loadFactor;
1344 >        Segment(float lf) { this.loadFactor = lf; }
1345 >    }
1346 >
1347 >    /**
1348 >     * Saves the state of the {@code ConcurrentHashMap} instance to a
1349 >     * stream (i.e., serializes it).
1350 >     * @param s the stream
1351 >     * @throws java.io.IOException if an I/O error occurs
1352 >     * @serialData
1353 >     * the key (Object) and value (Object)
1354 >     * for each key-value mapping, followed by a null pair.
1355 >     * The key-value mappings are emitted in no particular order.
1356 >     */
1357 >    private void writeObject(java.io.ObjectOutputStream s)
1358 >        throws java.io.IOException {
1359 >        // For serialization compatibility
1360 >        // Emulate segment calculation from previous version of this class
1361 >        int sshift = 0;
1362 >        int ssize = 1;
1363 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1364 >            ++sshift;
1365 >            ssize <<= 1;
1366 >        }
1367 >        int segmentShift = 32 - sshift;
1368 >        int segmentMask = ssize - 1;
1369 >        @SuppressWarnings("unchecked")
1370 >        Segment<K,V>[] segments = (Segment<K,V>[])
1371 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1372 >        for (int i = 0; i < segments.length; ++i)
1373 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1374 >        s.putFields().put("segments", segments);
1375 >        s.putFields().put("segmentShift", segmentShift);
1376 >        s.putFields().put("segmentMask", segmentMask);
1377 >        s.writeFields();
1378 >
1379 >        Node<K,V>[] t;
1380 >        if ((t = table) != null) {
1381 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1382 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1383 >                s.writeObject(p.key);
1384 >                s.writeObject(p.val);
1385 >            }
1386 >        }
1387 >        s.writeObject(null);
1388 >        s.writeObject(null);
1389 >        segments = null; // throw away
1390 >    }
1391 >
1392 >    /**
1393 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1394 >     * @param s the stream
1395 >     * @throws ClassNotFoundException if the class of a serialized object
1396 >     *         could not be found
1397 >     * @throws java.io.IOException if an I/O error occurs
1398 >     */
1399 >    private void readObject(java.io.ObjectInputStream s)
1400 >        throws java.io.IOException, ClassNotFoundException {
1401 >        /*
1402 >         * To improve performance in typical cases, we create nodes
1403 >         * while reading, then place in table once size is known.
1404 >         * However, we must also validate uniqueness and deal with
1405 >         * overpopulated bins while doing so, which requires
1406 >         * specialized versions of putVal mechanics.
1407 >         */
1408 >        sizeCtl = -1; // force exclusion for table construction
1409 >        s.defaultReadObject();
1410 >        long size = 0L;
1411 >        Node<K,V> p = null;
1412 >        for (;;) {
1413 >            @SuppressWarnings("unchecked")
1414 >            K k = (K) s.readObject();
1415 >            @SuppressWarnings("unchecked")
1416 >            V v = (V) s.readObject();
1417 >            if (k != null && v != null) {
1418 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1419 >                ++size;
1420 >            }
1421 >            else
1422 >                break;
1423 >        }
1424 >        if (size == 0L)
1425 >            sizeCtl = 0;
1426 >        else {
1427 >            int n;
1428 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1429 >                n = MAXIMUM_CAPACITY;
1430 >            else {
1431 >                int sz = (int)size;
1432 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1433 >            }
1434 >            @SuppressWarnings("unchecked")
1435 >            Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1436 >            int mask = n - 1;
1437 >            long added = 0L;
1438 >            while (p != null) {
1439 >                boolean insertAtFront;
1440 >                Node<K,V> next = p.next, first;
1441 >                int h = p.hash, j = h & mask;
1442 >                if ((first = tabAt(tab, j)) == null)
1443 >                    insertAtFront = true;
1444 >                else {
1445 >                    K k = p.key;
1446 >                    if (first.hash < 0) {
1447 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1448 >                        if (t.putTreeVal(h, k, p.val) == null)
1449 >                            ++added;
1450 >                        insertAtFront = false;
1451 >                    }
1452 >                    else {
1453 >                        int binCount = 0;
1454 >                        insertAtFront = true;
1455 >                        Node<K,V> q; K qk;
1456 >                        for (q = first; q != null; q = q.next) {
1457 >                            if (q.hash == h &&
1458 >                                ((qk = q.key) == k ||
1459 >                                 (qk != null && k.equals(qk)))) {
1460 >                                insertAtFront = false;
1461 >                                break;
1462 >                            }
1463 >                            ++binCount;
1464 >                        }
1465 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1466 >                            insertAtFront = false;
1467 >                            ++added;
1468 >                            p.next = first;
1469 >                            TreeNode<K,V> hd = null, tl = null;
1470 >                            for (q = p; q != null; q = q.next) {
1471 >                                TreeNode<K,V> t = new TreeNode<K,V>
1472 >                                    (q.hash, q.key, q.val, null, null);
1473 >                                if ((t.prev = tl) == null)
1474 >                                    hd = t;
1475 >                                else
1476 >                                    tl.next = t;
1477 >                                tl = t;
1478 >                            }
1479 >                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1480 >                        }
1481 >                    }
1482 >                }
1483 >                if (insertAtFront) {
1484 >                    ++added;
1485 >                    p.next = first;
1486 >                    setTabAt(tab, j, p);
1487 >                }
1488 >                p = next;
1489 >            }
1490 >            table = tab;
1491 >            sizeCtl = n - (n >>> 2);
1492 >            baseCount = added;
1493 >        }
1494 >    }
1495 >
1496 >    // ConcurrentMap methods
1497 >
1498 >    /**
1499 >     * {@inheritDoc}
1500 >     *
1501 >     * @return the previous value associated with the specified key,
1502 >     *         or {@code null} if there was no mapping for the key
1503 >     * @throws NullPointerException if the specified key or value is null
1504 >     */
1505 >    public V putIfAbsent(K key, V value) {
1506 >        return putVal(key, value, true);
1507 >    }
1508 >
1509 >    /**
1510 >     * {@inheritDoc}
1511 >     *
1512 >     * @throws NullPointerException if the specified key is null
1513 >     */
1514 >    public boolean remove(Object key, Object value) {
1515 >        if (key == null)
1516 >            throw new NullPointerException();
1517 >        return value != null && replaceNode(key, null, value) != null;
1518 >    }
1519 >
1520 >    /**
1521 >     * {@inheritDoc}
1522 >     *
1523 >     * @throws NullPointerException if any of the arguments are null
1524 >     */
1525 >    public boolean replace(K key, V oldValue, V newValue) {
1526 >        if (key == null || oldValue == null || newValue == null)
1527              throw new NullPointerException();
1528 <        return (V)internalPut(key, value);
1528 >        return replaceNode(key, newValue, oldValue) != null;
1529      }
1530  
1531      /**
# Line 2806 | Line 1535 | public class ConcurrentHashMap<K, V>
1535       *         or {@code null} if there was no mapping for the key
1536       * @throws NullPointerException if the specified key or value is null
1537       */
1538 <    @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) {
1538 >    public V replace(K key, V value) {
1539          if (key == null || value == null)
1540              throw new NullPointerException();
1541 <        return (V)internalPutIfAbsent(key, value);
1541 >        return replaceNode(key, value, null);
1542      }
1543  
1544 +    // Overrides of JDK8+ Map extension method defaults
1545 +
1546      /**
1547 <     * Copies all of the mappings from the specified map to this one.
1548 <     * These mappings replace any mappings that this map had for any of the
1549 <     * keys currently in the specified map.
1547 >     * Returns the value to which the specified key is mapped, or the
1548 >     * given default value if this map contains no mapping for the
1549 >     * key.
1550       *
1551 <     * @param m mappings to be stored in this map
1551 >     * @param key the key whose associated value is to be returned
1552 >     * @param defaultValue the value to return if this map contains
1553 >     * no mapping for the given key
1554 >     * @return the mapping for the key, if present; else the default value
1555 >     * @throws NullPointerException if the specified key is null
1556       */
1557 <    public void putAll(Map<? extends K, ? extends V> m) {
1558 <        internalPutAll(m);
1557 >    public V getOrDefault(Object key, V defaultValue) {
1558 >        V v;
1559 >        return (v = get(key)) == null ? defaultValue : v;
1560 >    }
1561 >
1562 >    public void forEach(BiConsumer<? super K, ? super V> action) {
1563 >        if (action == null) throw new NullPointerException();
1564 >        Node<K,V>[] t;
1565 >        if ((t = table) != null) {
1566 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1567 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1568 >                action.accept(p.key, p.val);
1569 >            }
1570 >        }
1571 >    }
1572 >
1573 >    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1574 >        if (function == null) throw new NullPointerException();
1575 >        Node<K,V>[] t;
1576 >        if ((t = table) != null) {
1577 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1578 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1579 >                V oldValue = p.val;
1580 >                for (K key = p.key;;) {
1581 >                    V newValue = function.apply(key, oldValue);
1582 >                    if (newValue == null)
1583 >                        throw new NullPointerException();
1584 >                    if (replaceNode(key, newValue, oldValue) != null ||
1585 >                        (oldValue = get(key)) == null)
1586 >                        break;
1587 >                }
1588 >            }
1589 >        }
1590      }
1591  
1592      /**
1593       * If the specified key is not already associated with a value,
1594 <     * computes its value using the given mappingFunction and enters
1595 <     * it into the map unless null.  This is equivalent to
1596 <     * <pre> {@code
1597 <     * if (map.containsKey(key))
1598 <     *   return map.get(key);
1599 <     * value = mappingFunction.apply(key);
1600 <     * if (value != null)
2835 <     *   map.put(key, value);
2836 <     * return value;}</pre>
2837 <     *
2838 <     * except that the action is performed atomically.  If the
2839 <     * function returns {@code null} no mapping is recorded. If the
2840 <     * function itself throws an (unchecked) exception, the exception
2841 <     * is rethrown to its caller, and no mapping is recorded.  Some
2842 <     * attempted update operations on this map by other threads may be
2843 <     * blocked while computation is in progress, so the computation
2844 <     * should be short and simple, and must not attempt to update any
2845 <     * other mappings of this Map. The most appropriate usage is to
2846 <     * construct a new object serving as an initial mapped value, or
2847 <     * memoized result, as in:
2848 <     *
2849 <     *  <pre> {@code
2850 <     * map.computeIfAbsent(key, new Fun<K, V>() {
2851 <     *   public V map(K k) { return new Value(f(k)); }});}</pre>
1594 >     * attempts to compute its value using the given mapping function
1595 >     * and enters it into this map unless {@code null}.  The entire
1596 >     * method invocation is performed atomically, so the function is
1597 >     * applied at most once per key.  Some attempted update operations
1598 >     * on this map by other threads may be blocked while computation
1599 >     * is in progress, so the computation should be short and simple,
1600 >     * and must not attempt to update any other mappings of this map.
1601       *
1602       * @param key key with which the specified value is to be associated
1603       * @param mappingFunction the function to compute a value
# Line 2862 | Line 1611 | public class ConcurrentHashMap<K, V>
1611       * @throws RuntimeException or Error if the mappingFunction does so,
1612       *         in which case the mapping is left unestablished
1613       */
1614 <    @SuppressWarnings("unchecked") public V computeIfAbsent
2866 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
1614 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1615          if (key == null || mappingFunction == null)
1616              throw new NullPointerException();
1617 <        return (V)internalComputeIfAbsent(key, mappingFunction);
1617 >        int h = spread(key.hashCode());
1618 >        V val = null;
1619 >        int binCount = 0;
1620 >        for (Node<K,V>[] tab = table;;) {
1621 >            Node<K,V> f; int n, i, fh;
1622 >            if (tab == null || (n = tab.length) == 0)
1623 >                tab = initTable();
1624 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1625 >                Node<K,V> r = new ReservationNode<K,V>();
1626 >                synchronized (r) {
1627 >                    if (casTabAt(tab, i, null, r)) {
1628 >                        binCount = 1;
1629 >                        Node<K,V> node = null;
1630 >                        try {
1631 >                            if ((val = mappingFunction.apply(key)) != null)
1632 >                                node = new Node<K,V>(h, key, val, null);
1633 >                        } finally {
1634 >                            setTabAt(tab, i, node);
1635 >                        }
1636 >                    }
1637 >                }
1638 >                if (binCount != 0)
1639 >                    break;
1640 >            }
1641 >            else if ((fh = f.hash) == MOVED)
1642 >                tab = helpTransfer(tab, f);
1643 >            else {
1644 >                boolean added = false;
1645 >                synchronized (f) {
1646 >                    if (tabAt(tab, i) == f) {
1647 >                        if (fh >= 0) {
1648 >                            binCount = 1;
1649 >                            for (Node<K,V> e = f;; ++binCount) {
1650 >                                K ek; V ev;
1651 >                                if (e.hash == h &&
1652 >                                    ((ek = e.key) == key ||
1653 >                                     (ek != null && key.equals(ek)))) {
1654 >                                    val = e.val;
1655 >                                    break;
1656 >                                }
1657 >                                Node<K,V> pred = e;
1658 >                                if ((e = e.next) == null) {
1659 >                                    if ((val = mappingFunction.apply(key)) != null) {
1660 >                                        added = true;
1661 >                                        pred.next = new Node<K,V>(h, key, val, null);
1662 >                                    }
1663 >                                    break;
1664 >                                }
1665 >                            }
1666 >                        }
1667 >                        else if (f instanceof TreeBin) {
1668 >                            binCount = 2;
1669 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1670 >                            TreeNode<K,V> r, p;
1671 >                            if ((r = t.root) != null &&
1672 >                                (p = r.findTreeNode(h, key, null)) != null)
1673 >                                val = p.val;
1674 >                            else if ((val = mappingFunction.apply(key)) != null) {
1675 >                                added = true;
1676 >                                t.putTreeVal(h, key, val);
1677 >                            }
1678 >                        }
1679 >                    }
1680 >                }
1681 >                if (binCount != 0) {
1682 >                    if (binCount >= TREEIFY_THRESHOLD)
1683 >                        treeifyBin(tab, i);
1684 >                    if (!added)
1685 >                        return val;
1686 >                    break;
1687 >                }
1688 >            }
1689 >        }
1690 >        if (val != null)
1691 >            addCount(1L, binCount);
1692 >        return val;
1693      }
1694  
1695      /**
1696 <     * If the given key is present, computes a new mapping value given a key and
1697 <     * its current mapped value. This is equivalent to
1698 <     *  <pre> {@code
1699 <     *   if (map.containsKey(key)) {
1700 <     *     value = remappingFunction.apply(key, map.get(key));
1701 <     *     if (value != null)
1702 <     *       map.put(key, value);
2880 <     *     else
2881 <     *       map.remove(key);
2882 <     *   }
2883 <     * }</pre>
2884 <     *
2885 <     * except that the action is performed atomically.  If the
2886 <     * function returns {@code null}, the mapping is removed.  If the
2887 <     * function itself throws an (unchecked) exception, the exception
2888 <     * is rethrown to its caller, and the current mapping is left
2889 <     * unchanged.  Some attempted update operations on this map by
2890 <     * other threads may be blocked while computation is in progress,
2891 <     * so the computation should be short and simple, and must not
2892 <     * attempt to update any other mappings of this Map. For example,
2893 <     * to either create or append new messages to a value mapping:
1696 >     * If the value for the specified key is present, attempts to
1697 >     * compute a new mapping given the key and its current mapped
1698 >     * value.  The entire method invocation is performed atomically.
1699 >     * Some attempted update operations on this map by other threads
1700 >     * may be blocked while computation is in progress, so the
1701 >     * computation should be short and simple, and must not attempt to
1702 >     * update any other mappings of this map.
1703       *
1704 <     * @param key key with which the specified value is to be associated
1704 >     * @param key key with which a value may be associated
1705       * @param remappingFunction the function to compute a value
1706       * @return the new value associated with the specified key, or null if none
1707       * @throws NullPointerException if the specified key or remappingFunction
# Line 2903 | Line 1712 | public class ConcurrentHashMap<K, V>
1712       * @throws RuntimeException or Error if the remappingFunction does so,
1713       *         in which case the mapping is unchanged
1714       */
1715 <    @SuppressWarnings("unchecked") public V computeIfPresent
2907 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1715 >    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1716          if (key == null || remappingFunction == null)
1717              throw new NullPointerException();
1718 <        return (V)internalCompute(key, true, remappingFunction);
1718 >        int h = spread(key.hashCode());
1719 >        V val = null;
1720 >        int delta = 0;
1721 >        int binCount = 0;
1722 >        for (Node<K,V>[] tab = table;;) {
1723 >            Node<K,V> f; int n, i, fh;
1724 >            if (tab == null || (n = tab.length) == 0)
1725 >                tab = initTable();
1726 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1727 >                break;
1728 >            else if ((fh = f.hash) == MOVED)
1729 >                tab = helpTransfer(tab, f);
1730 >            else {
1731 >                synchronized (f) {
1732 >                    if (tabAt(tab, i) == f) {
1733 >                        if (fh >= 0) {
1734 >                            binCount = 1;
1735 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1736 >                                K ek;
1737 >                                if (e.hash == h &&
1738 >                                    ((ek = e.key) == key ||
1739 >                                     (ek != null && key.equals(ek)))) {
1740 >                                    val = remappingFunction.apply(key, e.val);
1741 >                                    if (val != null)
1742 >                                        e.val = val;
1743 >                                    else {
1744 >                                        delta = -1;
1745 >                                        Node<K,V> en = e.next;
1746 >                                        if (pred != null)
1747 >                                            pred.next = en;
1748 >                                        else
1749 >                                            setTabAt(tab, i, en);
1750 >                                    }
1751 >                                    break;
1752 >                                }
1753 >                                pred = e;
1754 >                                if ((e = e.next) == null)
1755 >                                    break;
1756 >                            }
1757 >                        }
1758 >                        else if (f instanceof TreeBin) {
1759 >                            binCount = 2;
1760 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1761 >                            TreeNode<K,V> r, p;
1762 >                            if ((r = t.root) != null &&
1763 >                                (p = r.findTreeNode(h, key, null)) != null) {
1764 >                                val = remappingFunction.apply(key, p.val);
1765 >                                if (val != null)
1766 >                                    p.val = val;
1767 >                                else {
1768 >                                    delta = -1;
1769 >                                    if (t.removeTreeNode(p))
1770 >                                        setTabAt(tab, i, untreeify(t.first));
1771 >                                }
1772 >                            }
1773 >                        }
1774 >                    }
1775 >                }
1776 >                if (binCount != 0)
1777 >                    break;
1778 >            }
1779 >        }
1780 >        if (delta != 0)
1781 >            addCount((long)delta, binCount);
1782 >        return val;
1783      }
1784  
1785      /**
1786 <     * Computes a new mapping value given a key and
1787 <     * its current mapped value (or {@code null} if there is no current
1788 <     * mapping). This is equivalent to
1789 <     *  <pre> {@code
1790 <     *   value = remappingFunction.apply(key, map.get(key));
1791 <     *   if (value != null)
1792 <     *     map.put(key, value);
2921 <     *   else
2922 <     *     map.remove(key);
2923 <     * }</pre>
2924 <     *
2925 <     * except that the action is performed atomically.  If the
2926 <     * function returns {@code null}, the mapping is removed.  If the
2927 <     * function itself throws an (unchecked) exception, the exception
2928 <     * is rethrown to its caller, and the current mapping is left
2929 <     * unchanged.  Some attempted update operations on this map by
2930 <     * other threads may be blocked while computation is in progress,
2931 <     * so the computation should be short and simple, and must not
2932 <     * attempt to update any other mappings of this Map. For example,
2933 <     * to either create or append new messages to a value mapping:
2934 <     *
2935 <     * <pre> {@code
2936 <     * Map<Key, String> map = ...;
2937 <     * final String msg = ...;
2938 <     * map.compute(key, new BiFun<Key, String, String>() {
2939 <     *   public String apply(Key k, String v) {
2940 <     *    return (v == null) ? msg : v + msg;});}}</pre>
1786 >     * Attempts to compute a mapping for the specified key and its
1787 >     * current mapped value (or {@code null} if there is no current
1788 >     * mapping). The entire method invocation is performed atomically.
1789 >     * Some attempted update operations on this map by other threads
1790 >     * may be blocked while computation is in progress, so the
1791 >     * computation should be short and simple, and must not attempt to
1792 >     * update any other mappings of this Map.
1793       *
1794       * @param key key with which the specified value is to be associated
1795       * @param remappingFunction the function to compute a value
# Line 2950 | Line 1802 | public class ConcurrentHashMap<K, V>
1802       * @throws RuntimeException or Error if the remappingFunction does so,
1803       *         in which case the mapping is unchanged
1804       */
1805 <    @SuppressWarnings("unchecked") public V compute
1806 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1805 >    public V compute(K key,
1806 >                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1807          if (key == null || remappingFunction == null)
1808              throw new NullPointerException();
1809 <        return (V)internalCompute(key, false, remappingFunction);
1809 >        int h = spread(key.hashCode());
1810 >        V val = null;
1811 >        int delta = 0;
1812 >        int binCount = 0;
1813 >        for (Node<K,V>[] tab = table;;) {
1814 >            Node<K,V> f; int n, i, fh;
1815 >            if (tab == null || (n = tab.length) == 0)
1816 >                tab = initTable();
1817 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1818 >                Node<K,V> r = new ReservationNode<K,V>();
1819 >                synchronized (r) {
1820 >                    if (casTabAt(tab, i, null, r)) {
1821 >                        binCount = 1;
1822 >                        Node<K,V> node = null;
1823 >                        try {
1824 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1825 >                                delta = 1;
1826 >                                node = new Node<K,V>(h, key, val, null);
1827 >                            }
1828 >                        } finally {
1829 >                            setTabAt(tab, i, node);
1830 >                        }
1831 >                    }
1832 >                }
1833 >                if (binCount != 0)
1834 >                    break;
1835 >            }
1836 >            else if ((fh = f.hash) == MOVED)
1837 >                tab = helpTransfer(tab, f);
1838 >            else {
1839 >                synchronized (f) {
1840 >                    if (tabAt(tab, i) == f) {
1841 >                        if (fh >= 0) {
1842 >                            binCount = 1;
1843 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1844 >                                K ek;
1845 >                                if (e.hash == h &&
1846 >                                    ((ek = e.key) == key ||
1847 >                                     (ek != null && key.equals(ek)))) {
1848 >                                    val = remappingFunction.apply(key, e.val);
1849 >                                    if (val != null)
1850 >                                        e.val = val;
1851 >                                    else {
1852 >                                        delta = -1;
1853 >                                        Node<K,V> en = e.next;
1854 >                                        if (pred != null)
1855 >                                            pred.next = en;
1856 >                                        else
1857 >                                            setTabAt(tab, i, en);
1858 >                                    }
1859 >                                    break;
1860 >                                }
1861 >                                pred = e;
1862 >                                if ((e = e.next) == null) {
1863 >                                    val = remappingFunction.apply(key, null);
1864 >                                    if (val != null) {
1865 >                                        delta = 1;
1866 >                                        pred.next =
1867 >                                            new Node<K,V>(h, key, val, null);
1868 >                                    }
1869 >                                    break;
1870 >                                }
1871 >                            }
1872 >                        }
1873 >                        else if (f instanceof TreeBin) {
1874 >                            binCount = 1;
1875 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1876 >                            TreeNode<K,V> r, p;
1877 >                            if ((r = t.root) != null)
1878 >                                p = r.findTreeNode(h, key, null);
1879 >                            else
1880 >                                p = null;
1881 >                            V pv = (p == null) ? null : p.val;
1882 >                            val = remappingFunction.apply(key, pv);
1883 >                            if (val != null) {
1884 >                                if (p != null)
1885 >                                    p.val = val;
1886 >                                else {
1887 >                                    delta = 1;
1888 >                                    t.putTreeVal(h, key, val);
1889 >                                }
1890 >                            }
1891 >                            else if (p != null) {
1892 >                                delta = -1;
1893 >                                if (t.removeTreeNode(p))
1894 >                                    setTabAt(tab, i, untreeify(t.first));
1895 >                            }
1896 >                        }
1897 >                    }
1898 >                }
1899 >                if (binCount != 0) {
1900 >                    if (binCount >= TREEIFY_THRESHOLD)
1901 >                        treeifyBin(tab, i);
1902 >                    break;
1903 >                }
1904 >            }
1905 >        }
1906 >        if (delta != 0)
1907 >            addCount((long)delta, binCount);
1908 >        return val;
1909      }
1910  
1911      /**
1912 <     * If the specified key is not already associated
1913 <     * with a value, associate it with the given value.
1914 <     * Otherwise, replace the value with the results of
1915 <     * the given remapping function. This is equivalent to:
1916 <     *  <pre> {@code
1917 <     *   if (!map.containsKey(key))
1918 <     *     map.put(value);
1919 <     *   else {
1920 <     *     newValue = remappingFunction.apply(map.get(key), value);
1921 <     *     if (value != null)
1922 <     *       map.put(key, value);
1923 <     *     else
1924 <     *       map.remove(key);
1925 <     *   }
1926 <     * }</pre>
1927 <     * except that the action is performed atomically.  If the
1928 <     * function returns {@code null}, the mapping is removed.  If the
1929 <     * function itself throws an (unchecked) exception, the exception
2979 <     * is rethrown to its caller, and the current mapping is left
2980 <     * unchanged.  Some attempted update operations on this map by
2981 <     * other threads may be blocked while computation is in progress,
2982 <     * so the computation should be short and simple, and must not
2983 <     * attempt to update any other mappings of this Map.
1912 >     * If the specified key is not already associated with a
1913 >     * (non-null) value, associates it with the given value.
1914 >     * Otherwise, replaces the value with the results of the given
1915 >     * remapping function, or removes if {@code null}. The entire
1916 >     * method invocation is performed atomically.  Some attempted
1917 >     * update operations on this map by other threads may be blocked
1918 >     * while computation is in progress, so the computation should be
1919 >     * short and simple, and must not attempt to update any other
1920 >     * mappings of this Map.
1921 >     *
1922 >     * @param key key with which the specified value is to be associated
1923 >     * @param value the value to use if absent
1924 >     * @param remappingFunction the function to recompute a value if present
1925 >     * @return the new value associated with the specified key, or null if none
1926 >     * @throws NullPointerException if the specified key or the
1927 >     *         remappingFunction is null
1928 >     * @throws RuntimeException or Error if the remappingFunction does so,
1929 >     *         in which case the mapping is unchanged
1930       */
1931 <    @SuppressWarnings("unchecked") public V merge
2986 <        (K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1931 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1932          if (key == null || value == null || remappingFunction == null)
1933              throw new NullPointerException();
1934 <        return (V)internalMerge(key, value, remappingFunction);
1934 >        int h = spread(key.hashCode());
1935 >        V val = null;
1936 >        int delta = 0;
1937 >        int binCount = 0;
1938 >        for (Node<K,V>[] tab = table;;) {
1939 >            Node<K,V> f; int n, i, fh;
1940 >            if (tab == null || (n = tab.length) == 0)
1941 >                tab = initTable();
1942 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1943 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1944 >                    delta = 1;
1945 >                    val = value;
1946 >                    break;
1947 >                }
1948 >            }
1949 >            else if ((fh = f.hash) == MOVED)
1950 >                tab = helpTransfer(tab, f);
1951 >            else {
1952 >                synchronized (f) {
1953 >                    if (tabAt(tab, i) == f) {
1954 >                        if (fh >= 0) {
1955 >                            binCount = 1;
1956 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1957 >                                K ek;
1958 >                                if (e.hash == h &&
1959 >                                    ((ek = e.key) == key ||
1960 >                                     (ek != null && key.equals(ek)))) {
1961 >                                    val = remappingFunction.apply(e.val, value);
1962 >                                    if (val != null)
1963 >                                        e.val = val;
1964 >                                    else {
1965 >                                        delta = -1;
1966 >                                        Node<K,V> en = e.next;
1967 >                                        if (pred != null)
1968 >                                            pred.next = en;
1969 >                                        else
1970 >                                            setTabAt(tab, i, en);
1971 >                                    }
1972 >                                    break;
1973 >                                }
1974 >                                pred = e;
1975 >                                if ((e = e.next) == null) {
1976 >                                    delta = 1;
1977 >                                    val = value;
1978 >                                    pred.next =
1979 >                                        new Node<K,V>(h, key, val, null);
1980 >                                    break;
1981 >                                }
1982 >                            }
1983 >                        }
1984 >                        else if (f instanceof TreeBin) {
1985 >                            binCount = 2;
1986 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1987 >                            TreeNode<K,V> r = t.root;
1988 >                            TreeNode<K,V> p = (r == null) ? null :
1989 >                                r.findTreeNode(h, key, null);
1990 >                            val = (p == null) ? value :
1991 >                                remappingFunction.apply(p.val, value);
1992 >                            if (val != null) {
1993 >                                if (p != null)
1994 >                                    p.val = val;
1995 >                                else {
1996 >                                    delta = 1;
1997 >                                    t.putTreeVal(h, key, val);
1998 >                                }
1999 >                            }
2000 >                            else if (p != null) {
2001 >                                delta = -1;
2002 >                                if (t.removeTreeNode(p))
2003 >                                    setTabAt(tab, i, untreeify(t.first));
2004 >                            }
2005 >                        }
2006 >                    }
2007 >                }
2008 >                if (binCount != 0) {
2009 >                    if (binCount >= TREEIFY_THRESHOLD)
2010 >                        treeifyBin(tab, i);
2011 >                    break;
2012 >                }
2013 >            }
2014 >        }
2015 >        if (delta != 0)
2016 >            addCount((long)delta, binCount);
2017 >        return val;
2018      }
2019  
2020 +    // Hashtable legacy methods
2021 +
2022      /**
2023 <     * Removes the key (and its corresponding value) from this map.
2024 <     * This method does nothing if the key is not in the map.
2023 >     * Legacy method testing if some key maps into the specified value
2024 >     * in this table.
2025       *
2026 <     * @param  key the key that needs to be removed
2027 <     * @return the previous value associated with {@code key}, or
2028 <     *         {@code null} if there was no mapping for {@code key}
2029 <     * @throws NullPointerException if the specified key is null
2026 >     * @deprecated This method is identical in functionality to
2027 >     * {@link #containsValue(Object)}, and exists solely to ensure
2028 >     * full compatibility with class {@link java.util.Hashtable},
2029 >     * which supported this method prior to introduction of the
2030 >     * Java Collections framework.
2031 >     *
2032 >     * @param  value a value to search for
2033 >     * @return {@code true} if and only if some key maps to the
2034 >     *         {@code value} argument in this table as
2035 >     *         determined by the {@code equals} method;
2036 >     *         {@code false} otherwise
2037 >     * @throws NullPointerException if the specified value is null
2038       */
2039 <    @SuppressWarnings("unchecked") public V remove(Object key) {
2040 <        if (key == null)
2041 <            throw new NullPointerException();
3004 <        return (V)internalReplace(key, null, null);
2039 >    @Deprecated
2040 >    public boolean contains(Object value) {
2041 >        return containsValue(value);
2042      }
2043  
2044      /**
2045 <     * {@inheritDoc}
2045 >     * Returns an enumeration of the keys in this table.
2046       *
2047 <     * @throws NullPointerException if the specified key is null
2047 >     * @return an enumeration of the keys in this table
2048 >     * @see #keySet()
2049       */
2050 <    public boolean remove(Object key, Object value) {
2051 <        if (key == null)
2052 <            throw new NullPointerException();
2053 <        if (value == null)
3016 <            return false;
3017 <        return internalReplace(key, null, value) != null;
2050 >    public Enumeration<K> keys() {
2051 >        Node<K,V>[] t;
2052 >        int f = (t = table) == null ? 0 : t.length;
2053 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2054      }
2055  
2056      /**
2057 <     * {@inheritDoc}
2057 >     * Returns an enumeration of the values in this table.
2058       *
2059 <     * @throws NullPointerException if any of the arguments are null
2059 >     * @return an enumeration of the values in this table
2060 >     * @see #values()
2061       */
2062 <    public boolean replace(K key, V oldValue, V newValue) {
2063 <        if (key == null || oldValue == null || newValue == null)
2064 <            throw new NullPointerException();
2065 <        return internalReplace(key, newValue, oldValue) != null;
2062 >    public Enumeration<V> elements() {
2063 >        Node<K,V>[] t;
2064 >        int f = (t = table) == null ? 0 : t.length;
2065 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2066      }
2067  
2068 +    // ConcurrentHashMap-only methods
2069 +
2070      /**
2071 <     * {@inheritDoc}
2071 >     * Returns the number of mappings. This method should be used
2072 >     * instead of {@link #size} because a ConcurrentHashMap may
2073 >     * contain more mappings than can be represented as an int. The
2074 >     * value returned is an estimate; the actual count may differ if
2075 >     * there are concurrent insertions or removals.
2076       *
2077 <     * @return the previous value associated with the specified key,
2078 <     *         or {@code null} if there was no mapping for the key
3036 <     * @throws NullPointerException if the specified key or value is null
2077 >     * @return the number of mappings
2078 >     * @since 1.8
2079       */
2080 <    @SuppressWarnings("unchecked") public V replace(K key, V value) {
2081 <        if (key == null || value == null)
2082 <            throw new NullPointerException();
3041 <        return (V)internalReplace(key, value, null);
2080 >    public long mappingCount() {
2081 >        long n = sumCount();
2082 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2083      }
2084  
2085      /**
2086 <     * Removes all of the mappings from this map.
2086 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2087 >     * from the given type to {@code Boolean.TRUE}.
2088 >     *
2089 >     * @param <K> the element type of the returned set
2090 >     * @return the new set
2091 >     * @since 1.8
2092       */
2093 <    public void clear() {
2094 <        internalClear();
2093 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2094 >        return new KeySetView<K,Boolean>
2095 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2096      }
2097  
2098      /**
2099 <     * Returns a {@link Set} view of the keys contained in this map.
2100 <     * The set is backed by the map, so changes to the map are
3054 <     * reflected in the set, and vice-versa.
2099 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2100 >     * from the given type to {@code Boolean.TRUE}.
2101       *
2102 <     * @return the set view
2102 >     * @param initialCapacity The implementation performs internal
2103 >     * sizing to accommodate this many elements.
2104 >     * @param <K> the element type of the returned set
2105 >     * @return the new set
2106 >     * @throws IllegalArgumentException if the initial capacity of
2107 >     * elements is negative
2108 >     * @since 1.8
2109       */
2110 <    public KeySetView<K,V> keySet() {
2111 <        KeySetView<K,V> ks = keySet;
2112 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2110 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2111 >        return new KeySetView<K,Boolean>
2112 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2113      }
2114  
2115      /**
2116       * Returns a {@link Set} view of the keys in this map, using the
2117       * given common mapped value for any additions (i.e., {@link
2118 <     * Collection#add} and {@link Collection#addAll}). This is of
2119 <     * course only appropriate if it is acceptable to use the same
2120 <     * value for all additions from this view.
2118 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2119 >     * This is of course only appropriate if it is acceptable to use
2120 >     * the same value for all additions from this view.
2121       *
2122 <     * @param mappedValue the mapped value to use for any
3071 <     * additions.
2122 >     * @param mappedValue the mapped value to use for any additions
2123       * @return the set view
2124       * @throws NullPointerException if the mappedValue is null
2125       */
# Line 3078 | Line 2129 | public class ConcurrentHashMap<K, V>
2129          return new KeySetView<K,V>(this, mappedValue);
2130      }
2131  
2132 +    /* ---------------- Special Nodes -------------- */
2133 +
2134      /**
2135 <     * Returns a {@link Collection} view of the values contained in this map.
3083 <     * The collection is backed by the map, so changes to the map are
3084 <     * reflected in the collection, and vice-versa.  The collection
3085 <     * supports element removal, which removes the corresponding
3086 <     * mapping from this map, via the {@code Iterator.remove},
3087 <     * {@code Collection.remove}, {@code removeAll},
3088 <     * {@code retainAll}, and {@code clear} operations.  It does not
3089 <     * support the {@code add} or {@code addAll} operations.
3090 <     *
3091 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
3092 <     * that will never throw {@link ConcurrentModificationException},
3093 <     * and guarantees to traverse elements as they existed upon
3094 <     * construction of the iterator, and may (but is not guaranteed to)
3095 <     * reflect any modifications subsequent to construction.
2135 >     * A node inserted at head of bins during transfer operations.
2136       */
2137 <    public Collection<V> values() {
2138 <        Values<K,V> vs = values;
2139 <        return (vs != null) ? vs : (values = new Values<K,V>(this));
2137 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2138 >        final Node<K,V>[] nextTable;
2139 >        ForwardingNode(Node<K,V>[] tab) {
2140 >            super(MOVED, null, null, null);
2141 >            this.nextTable = tab;
2142 >        }
2143 >
2144 >        Node<K,V> find(int h, Object k) {
2145 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2146 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2147 >                Node<K,V> e; int n;
2148 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2149 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2150 >                    return null;
2151 >                for (;;) {
2152 >                    int eh; K ek;
2153 >                    if ((eh = e.hash) == h &&
2154 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2155 >                        return e;
2156 >                    if (eh < 0) {
2157 >                        if (e instanceof ForwardingNode) {
2158 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2159 >                            continue outer;
2160 >                        }
2161 >                        else
2162 >                            return e.find(h, k);
2163 >                    }
2164 >                    if ((e = e.next) == null)
2165 >                        return null;
2166 >                }
2167 >            }
2168 >        }
2169      }
2170  
2171      /**
2172 <     * Returns a {@link Set} view of the mappings contained in this map.
3104 <     * The set is backed by the map, so changes to the map are
3105 <     * reflected in the set, and vice-versa.  The set supports element
3106 <     * removal, which removes the corresponding mapping from the map,
3107 <     * via the {@code Iterator.remove}, {@code Set.remove},
3108 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
3109 <     * operations.  It does not support the {@code add} or
3110 <     * {@code addAll} operations.
3111 <     *
3112 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
3113 <     * that will never throw {@link ConcurrentModificationException},
3114 <     * and guarantees to traverse elements as they existed upon
3115 <     * construction of the iterator, and may (but is not guaranteed to)
3116 <     * reflect any modifications subsequent to construction.
2172 >     * A place-holder node used in computeIfAbsent and compute
2173       */
2174 <    public Set<Map.Entry<K,V>> entrySet() {
2175 <        EntrySet<K,V> es = entrySet;
2176 <        return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
2174 >    static final class ReservationNode<K,V> extends Node<K,V> {
2175 >        ReservationNode() {
2176 >            super(RESERVED, null, null, null);
2177 >        }
2178 >
2179 >        Node<K,V> find(int h, Object k) {
2180 >            return null;
2181 >        }
2182      }
2183  
2184 +    /* ---------------- Table Initialization and Resizing -------------- */
2185 +
2186      /**
2187 <     * Returns an enumeration of the keys in this table.
2188 <     *
3126 <     * @return an enumeration of the keys in this table
3127 <     * @see #keySet()
2187 >     * Returns the stamp bits for resizing a table of size n.
2188 >     * Must be negative when shifted left by RESIZE_STAMP_SHIFT.
2189       */
2190 <    public Enumeration<K> keys() {
2191 <        return new KeyIterator<K,V>(this);
2190 >    static final int resizeStamp(int n) {
2191 >        return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
2192      }
2193  
2194      /**
2195 <     * Returns an enumeration of the values in this table.
3135 <     *
3136 <     * @return an enumeration of the values in this table
3137 <     * @see #values()
2195 >     * Initializes table, using the size recorded in sizeCtl.
2196       */
2197 <    public Enumeration<V> elements() {
2198 <        return new ValueIterator<K,V>(this);
2197 >    private final Node<K,V>[] initTable() {
2198 >        Node<K,V>[] tab; int sc;
2199 >        while ((tab = table) == null || tab.length == 0) {
2200 >            if ((sc = sizeCtl) < 0)
2201 >                Thread.yield(); // lost initialization race; just spin
2202 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2203 >                try {
2204 >                    if ((tab = table) == null || tab.length == 0) {
2205 >                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2206 >                        @SuppressWarnings("unchecked")
2207 >                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2208 >                        table = tab = nt;
2209 >                        sc = n - (n >>> 2);
2210 >                    }
2211 >                } finally {
2212 >                    sizeCtl = sc;
2213 >                }
2214 >                break;
2215 >            }
2216 >        }
2217 >        return tab;
2218      }
2219  
2220      /**
2221 <     * Returns a partitionable iterator of the keys in this map.
2222 <     *
2223 <     * @return a partitionable iterator of the keys in this map
2224 <     */
2225 <    public Spliterator<K> keySpliterator() {
2226 <        return new KeyIterator<K,V>(this);
2221 >     * Adds to count, and if table is too small and not already
2222 >     * resizing, initiates transfer. If already resizing, helps
2223 >     * perform transfer if work is available.  Rechecks occupancy
2224 >     * after a transfer to see if another resize is already needed
2225 >     * because resizings are lagging additions.
2226 >     *
2227 >     * @param x the count to add
2228 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
2229 >     */
2230 >    private final void addCount(long x, int check) {
2231 >        CounterCell[] as; long b, s;
2232 >        if ((as = counterCells) != null ||
2233 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2234 >            CounterCell a; long v; int m;
2235 >            boolean uncontended = true;
2236 >            if (as == null || (m = as.length - 1) < 0 ||
2237 >                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
2238 >                !(uncontended =
2239 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2240 >                fullAddCount(x, uncontended);
2241 >                return;
2242 >            }
2243 >            if (check <= 1)
2244 >                return;
2245 >            s = sumCount();
2246 >        }
2247 >        if (check >= 0) {
2248 >            Node<K,V>[] tab, nt; int n, sc;
2249 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2250 >                   (n = tab.length) < MAXIMUM_CAPACITY) {
2251 >                int rs = resizeStamp(n);
2252 >                if (sc < 0) {
2253 >                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2254 >                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
2255 >                        transferIndex <= 0)
2256 >                        break;
2257 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
2258 >                        transfer(tab, nt);
2259 >                }
2260 >                else if (U.compareAndSwapInt(this, SIZECTL, sc,
2261 >                                             (rs << RESIZE_STAMP_SHIFT) + 2))
2262 >                    transfer(tab, null);
2263 >                s = sumCount();
2264 >            }
2265 >        }
2266      }
2267  
2268      /**
2269 <     * Returns a partitionable iterator of the values in this map.
3154 <     *
3155 <     * @return a partitionable iterator of the values in this map
2269 >     * Helps transfer if a resize is in progress.
2270       */
2271 <    public Spliterator<V> valueSpliterator() {
2272 <        return new ValueIterator<K,V>(this);
2271 >    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2272 >        Node<K,V>[] nextTab; int sc;
2273 >        if (tab != null && (f instanceof ForwardingNode) &&
2274 >            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2275 >            int rs = resizeStamp(tab.length);
2276 >            while (nextTab == nextTable && table == tab &&
2277 >                   (sc = sizeCtl) < 0) {
2278 >                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2279 >                    sc == rs + MAX_RESIZERS || transferIndex <= 0)
2280 >                    break;
2281 >                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
2282 >                    transfer(tab, nextTab);
2283 >                    break;
2284 >                }
2285 >            }
2286 >            return nextTab;
2287 >        }
2288 >        return table;
2289      }
2290  
2291      /**
2292 <     * Returns a partitionable iterator of the entries in this map.
2292 >     * Tries to presize table to accommodate the given number of elements.
2293       *
2294 <     * @return a partitionable iterator of the entries in this map
2294 >     * @param size number of elements (doesn't need to be perfectly accurate)
2295       */
2296 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
2297 <        return new EntryIterator<K,V>(this);
2296 >    private final void tryPresize(int size) {
2297 >        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2298 >            tableSizeFor(size + (size >>> 1) + 1);
2299 >        int sc;
2300 >        while ((sc = sizeCtl) >= 0) {
2301 >            Node<K,V>[] tab = table; int n;
2302 >            if (tab == null || (n = tab.length) == 0) {
2303 >                n = (sc > c) ? sc : c;
2304 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2305 >                    try {
2306 >                        if (table == tab) {
2307 >                            @SuppressWarnings("unchecked")
2308 >                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2309 >                            table = nt;
2310 >                            sc = n - (n >>> 2);
2311 >                        }
2312 >                    } finally {
2313 >                        sizeCtl = sc;
2314 >                    }
2315 >                }
2316 >            }
2317 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
2318 >                break;
2319 >            else if (tab == table) {
2320 >                int rs = resizeStamp(n);
2321 >                if (sc < 0) {
2322 >                    Node<K,V>[] nt;
2323 >                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2324 >                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
2325 >                        transferIndex <= 0)
2326 >                        break;
2327 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
2328 >                        transfer(tab, nt);
2329 >                }
2330 >                else if (U.compareAndSwapInt(this, SIZECTL, sc,
2331 >                                             (rs << RESIZE_STAMP_SHIFT) + 2))
2332 >                    transfer(tab, null);
2333 >            }
2334 >        }
2335      }
2336  
2337      /**
2338 <     * Returns the hash code value for this {@link Map}, i.e.,
2339 <     * the sum of, for each key-value pair in the map,
3173 <     * {@code key.hashCode() ^ value.hashCode()}.
3174 <     *
3175 <     * @return the hash code value for this map
2338 >     * Moves and/or copies the nodes in each bin to new table. See
2339 >     * above for explanation.
2340       */
2341 <    public int hashCode() {
2342 <        int h = 0;
2343 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2344 <        Object v;
2345 <        while ((v = it.advance()) != null) {
2346 <            h += it.nextKey.hashCode() ^ v.hashCode();
2341 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2342 >        int n = tab.length, stride;
2343 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2344 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
2345 >        if (nextTab == null) {            // initiating
2346 >            try {
2347 >                @SuppressWarnings("unchecked")
2348 >                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
2349 >                nextTab = nt;
2350 >            } catch (Throwable ex) {      // try to cope with OOME
2351 >                sizeCtl = Integer.MAX_VALUE;
2352 >                return;
2353 >            }
2354 >            nextTable = nextTab;
2355 >            transferIndex = n;
2356 >        }
2357 >        int nextn = nextTab.length;
2358 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2359 >        boolean advance = true;
2360 >        boolean finishing = false; // to ensure sweep before committing nextTab
2361 >        for (int i = 0, bound = 0;;) {
2362 >            Node<K,V> f; int fh;
2363 >            while (advance) {
2364 >                int nextIndex, nextBound;
2365 >                if (--i >= bound || finishing)
2366 >                    advance = false;
2367 >                else if ((nextIndex = transferIndex) <= 0) {
2368 >                    i = -1;
2369 >                    advance = false;
2370 >                }
2371 >                else if (U.compareAndSwapInt
2372 >                         (this, TRANSFERINDEX, nextIndex,
2373 >                          nextBound = (nextIndex > stride ?
2374 >                                       nextIndex - stride : 0))) {
2375 >                    bound = nextBound;
2376 >                    i = nextIndex - 1;
2377 >                    advance = false;
2378 >                }
2379 >            }
2380 >            if (i < 0 || i >= n || i + n >= nextn) {
2381 >                int sc;
2382 >                if (finishing) {
2383 >                    nextTable = null;
2384 >                    table = nextTab;
2385 >                    sizeCtl = (n << 1) - (n >>> 1);
2386 >                    return;
2387 >                }
2388 >                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
2389 >                    if ((sc - 2) != resizeStamp(n))
2390 >                        return;
2391 >                    finishing = advance = true;
2392 >                    i = n; // recheck before commit
2393 >                }
2394 >            }
2395 >            else if ((f = tabAt(tab, i)) == null)
2396 >                advance = casTabAt(tab, i, null, fwd);
2397 >            else if ((fh = f.hash) == MOVED)
2398 >                advance = true; // already processed
2399 >            else {
2400 >                synchronized (f) {
2401 >                    if (tabAt(tab, i) == f) {
2402 >                        Node<K,V> ln, hn;
2403 >                        if (fh >= 0) {
2404 >                            int runBit = fh & n;
2405 >                            Node<K,V> lastRun = f;
2406 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2407 >                                int b = p.hash & n;
2408 >                                if (b != runBit) {
2409 >                                    runBit = b;
2410 >                                    lastRun = p;
2411 >                                }
2412 >                            }
2413 >                            if (runBit == 0) {
2414 >                                ln = lastRun;
2415 >                                hn = null;
2416 >                            }
2417 >                            else {
2418 >                                hn = lastRun;
2419 >                                ln = null;
2420 >                            }
2421 >                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2422 >                                int ph = p.hash; K pk = p.key; V pv = p.val;
2423 >                                if ((ph & n) == 0)
2424 >                                    ln = new Node<K,V>(ph, pk, pv, ln);
2425 >                                else
2426 >                                    hn = new Node<K,V>(ph, pk, pv, hn);
2427 >                            }
2428 >                            setTabAt(nextTab, i, ln);
2429 >                            setTabAt(nextTab, i + n, hn);
2430 >                            setTabAt(tab, i, fwd);
2431 >                            advance = true;
2432 >                        }
2433 >                        else if (f instanceof TreeBin) {
2434 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2435 >                            TreeNode<K,V> lo = null, loTail = null;
2436 >                            TreeNode<K,V> hi = null, hiTail = null;
2437 >                            int lc = 0, hc = 0;
2438 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2439 >                                int h = e.hash;
2440 >                                TreeNode<K,V> p = new TreeNode<K,V>
2441 >                                    (h, e.key, e.val, null, null);
2442 >                                if ((h & n) == 0) {
2443 >                                    if ((p.prev = loTail) == null)
2444 >                                        lo = p;
2445 >                                    else
2446 >                                        loTail.next = p;
2447 >                                    loTail = p;
2448 >                                    ++lc;
2449 >                                }
2450 >                                else {
2451 >                                    if ((p.prev = hiTail) == null)
2452 >                                        hi = p;
2453 >                                    else
2454 >                                        hiTail.next = p;
2455 >                                    hiTail = p;
2456 >                                    ++hc;
2457 >                                }
2458 >                            }
2459 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2460 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2461 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2462 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2463 >                            setTabAt(nextTab, i, ln);
2464 >                            setTabAt(nextTab, i + n, hn);
2465 >                            setTabAt(tab, i, fwd);
2466 >                            advance = true;
2467 >                        }
2468 >                    }
2469 >                }
2470 >            }
2471          }
3184        return h;
2472      }
2473  
2474 +    /* ---------------- Counter support -------------- */
2475 +
2476      /**
2477 <     * Returns a string representation of this map.  The string
2478 <     * representation consists of a list of key-value mappings (in no
3190 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3191 <     * mappings are separated by the characters {@code ", "} (comma
3192 <     * and space).  Each key-value mapping is rendered as the key
3193 <     * followed by an equals sign ("{@code =}") followed by the
3194 <     * associated value.
3195 <     *
3196 <     * @return a string representation of this map
2477 >     * A padded cell for distributing counts.  Adapted from LongAdder
2478 >     * and Striped64.  See their internal docs for explanation.
2479       */
2480 <    public String toString() {
2481 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2482 <        StringBuilder sb = new StringBuilder();
2483 <        sb.append('{');
2484 <        Object v;
2485 <        if ((v = it.advance()) != null) {
2486 <            for (;;) {
2487 <                Object k = it.nextKey;
2488 <                sb.append(k == this ? "(this Map)" : k);
2489 <                sb.append('=');
2490 <                sb.append(v == this ? "(this Map)" : v);
2491 <                if ((v = it.advance()) == null)
2480 >    @sun.misc.Contended static final class CounterCell {
2481 >        volatile long value;
2482 >        CounterCell(long x) { value = x; }
2483 >    }
2484 >
2485 >    final long sumCount() {
2486 >        CounterCell[] as = counterCells; CounterCell a;
2487 >        long sum = baseCount;
2488 >        if (as != null) {
2489 >            for (int i = 0; i < as.length; ++i) {
2490 >                if ((a = as[i]) != null)
2491 >                    sum += a.value;
2492 >            }
2493 >        }
2494 >        return sum;
2495 >    }
2496 >
2497 >    // See LongAdder version for explanation
2498 >    private final void fullAddCount(long x, boolean wasUncontended) {
2499 >        int h;
2500 >        if ((h = ThreadLocalRandom.getProbe()) == 0) {
2501 >            ThreadLocalRandom.localInit();      // force initialization
2502 >            h = ThreadLocalRandom.getProbe();
2503 >            wasUncontended = true;
2504 >        }
2505 >        boolean collide = false;                // True if last slot nonempty
2506 >        for (;;) {
2507 >            CounterCell[] as; CounterCell a; int n; long v;
2508 >            if ((as = counterCells) != null && (n = as.length) > 0) {
2509 >                if ((a = as[(n - 1) & h]) == null) {
2510 >                    if (cellsBusy == 0) {            // Try to attach new Cell
2511 >                        CounterCell r = new CounterCell(x); // Optimistic create
2512 >                        if (cellsBusy == 0 &&
2513 >                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2514 >                            boolean created = false;
2515 >                            try {               // Recheck under lock
2516 >                                CounterCell[] rs; int m, j;
2517 >                                if ((rs = counterCells) != null &&
2518 >                                    (m = rs.length) > 0 &&
2519 >                                    rs[j = (m - 1) & h] == null) {
2520 >                                    rs[j] = r;
2521 >                                    created = true;
2522 >                                }
2523 >                            } finally {
2524 >                                cellsBusy = 0;
2525 >                            }
2526 >                            if (created)
2527 >                                break;
2528 >                            continue;           // Slot is now non-empty
2529 >                        }
2530 >                    }
2531 >                    collide = false;
2532 >                }
2533 >                else if (!wasUncontended)       // CAS already known to fail
2534 >                    wasUncontended = true;      // Continue after rehash
2535 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2536 >                    break;
2537 >                else if (counterCells != as || n >= NCPU)
2538 >                    collide = false;            // At max size or stale
2539 >                else if (!collide)
2540 >                    collide = true;
2541 >                else if (cellsBusy == 0 &&
2542 >                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2543 >                    try {
2544 >                        if (counterCells == as) {// Expand table unless stale
2545 >                            CounterCell[] rs = new CounterCell[n << 1];
2546 >                            for (int i = 0; i < n; ++i)
2547 >                                rs[i] = as[i];
2548 >                            counterCells = rs;
2549 >                        }
2550 >                    } finally {
2551 >                        cellsBusy = 0;
2552 >                    }
2553 >                    collide = false;
2554 >                    continue;                   // Retry with expanded table
2555 >                }
2556 >                h = ThreadLocalRandom.advanceProbe(h);
2557 >            }
2558 >            else if (cellsBusy == 0 && counterCells == as &&
2559 >                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2560 >                boolean init = false;
2561 >                try {                           // Initialize table
2562 >                    if (counterCells == as) {
2563 >                        CounterCell[] rs = new CounterCell[2];
2564 >                        rs[h & 1] = new CounterCell(x);
2565 >                        counterCells = rs;
2566 >                        init = true;
2567 >                    }
2568 >                } finally {
2569 >                    cellsBusy = 0;
2570 >                }
2571 >                if (init)
2572                      break;
3211                sb.append(',').append(' ');
2573              }
2574 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2575 +                break;                          // Fall back on using base
2576          }
3214        return sb.append('}').toString();
2577      }
2578  
2579 +    /* ---------------- Conversion from/to TreeBins -------------- */
2580 +
2581      /**
2582 <     * Compares the specified object with this map for equality.
2583 <     * Returns {@code true} if the given object is a map with the same
2584 <     * mappings as this map.  This operation may return misleading
2585 <     * results if either map is concurrently modified during execution
2586 <     * of this method.
2587 <     *
2588 <     * @param o object to be compared for equality with this map
2589 <     * @return {@code true} if the specified object is equal to this map
2582 >     * Replaces all linked nodes in bin at given index unless table is
2583 >     * too small, in which case resizes instead.
2584 >     */
2585 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2586 >        Node<K,V> b; int n, sc;
2587 >        if (tab != null) {
2588 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
2589 >                tryPresize(n << 1);
2590 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2591 >                synchronized (b) {
2592 >                    if (tabAt(tab, index) == b) {
2593 >                        TreeNode<K,V> hd = null, tl = null;
2594 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2595 >                            TreeNode<K,V> p =
2596 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2597 >                                                  null, null);
2598 >                            if ((p.prev = tl) == null)
2599 >                                hd = p;
2600 >                            else
2601 >                                tl.next = p;
2602 >                            tl = p;
2603 >                        }
2604 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2605 >                    }
2606 >                }
2607 >            }
2608 >        }
2609 >    }
2610 >
2611 >    /**
2612 >     * Returns a list on non-TreeNodes replacing those in given list.
2613       */
2614 <    public boolean equals(Object o) {
2615 <        if (o != this) {
2616 <            if (!(o instanceof Map))
2617 <                return false;
2618 <            Map<?,?> m = (Map<?,?>) o;
2619 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2620 <            Object val;
2621 <            while ((val = it.advance()) != null) {
2622 <                Object v = m.get(it.nextKey);
2623 <                if (v == null || (v != val && !v.equals(val)))
2624 <                    return false;
2614 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2615 >        Node<K,V> hd = null, tl = null;
2616 >        for (Node<K,V> q = b; q != null; q = q.next) {
2617 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2618 >            if (tl == null)
2619 >                hd = p;
2620 >            else
2621 >                tl.next = p;
2622 >            tl = p;
2623 >        }
2624 >        return hd;
2625 >    }
2626 >
2627 >    /* ---------------- TreeNodes -------------- */
2628 >
2629 >    /**
2630 >     * Nodes for use in TreeBins
2631 >     */
2632 >    static final class TreeNode<K,V> extends Node<K,V> {
2633 >        TreeNode<K,V> parent;  // red-black tree links
2634 >        TreeNode<K,V> left;
2635 >        TreeNode<K,V> right;
2636 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2637 >        boolean red;
2638 >
2639 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2640 >                 TreeNode<K,V> parent) {
2641 >            super(hash, key, val, next);
2642 >            this.parent = parent;
2643 >        }
2644 >
2645 >        Node<K,V> find(int h, Object k) {
2646 >            return findTreeNode(h, k, null);
2647 >        }
2648 >
2649 >        /**
2650 >         * Returns the TreeNode (or null if not found) for the given key
2651 >         * starting at given root.
2652 >         */
2653 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2654 >            if (k != null) {
2655 >                TreeNode<K,V> p = this;
2656 >                do  {
2657 >                    int ph, dir; K pk; TreeNode<K,V> q;
2658 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2659 >                    if ((ph = p.hash) > h)
2660 >                        p = pl;
2661 >                    else if (ph < h)
2662 >                        p = pr;
2663 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2664 >                        return p;
2665 >                    else if (pl == null)
2666 >                        p = pr;
2667 >                    else if (pr == null)
2668 >                        p = pl;
2669 >                    else if ((kc != null ||
2670 >                              (kc = comparableClassFor(k)) != null) &&
2671 >                             (dir = compareComparables(kc, k, pk)) != 0)
2672 >                        p = (dir < 0) ? pl : pr;
2673 >                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
2674 >                        return q;
2675 >                    else
2676 >                        p = pl;
2677 >                } while (p != null);
2678              }
2679 <            for (Map.Entry<?,?> e : m.entrySet()) {
2680 <                Object mk, mv, v;
2681 <                if ((mk = e.getKey()) == null ||
2682 <                    (mv = e.getValue()) == null ||
2683 <                    (v = internalGet(mk)) == null ||
2684 <                    (mv != v && !mv.equals(v)))
2685 <                    return false;
2679 >            return null;
2680 >        }
2681 >    }
2682 >
2683 >    /* ---------------- TreeBins -------------- */
2684 >
2685 >    /**
2686 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2687 >     * keys or values, but instead point to list of TreeNodes and
2688 >     * their root. They also maintain a parasitic read-write lock
2689 >     * forcing writers (who hold bin lock) to wait for readers (who do
2690 >     * not) to complete before tree restructuring operations.
2691 >     */
2692 >    static final class TreeBin<K,V> extends Node<K,V> {
2693 >        TreeNode<K,V> root;
2694 >        volatile TreeNode<K,V> first;
2695 >        volatile Thread waiter;
2696 >        volatile int lockState;
2697 >        // values for lockState
2698 >        static final int WRITER = 1; // set while holding write lock
2699 >        static final int WAITER = 2; // set when waiting for write lock
2700 >        static final int READER = 4; // increment value for setting read lock
2701 >
2702 >        /**
2703 >         * Tie-breaking utility for ordering insertions when equal
2704 >         * hashCodes and non-comparable. We don't require a total
2705 >         * order, just a consistent insertion rule to maintain
2706 >         * equivalence across rebalancings. Tie-breaking further than
2707 >         * necessary simplifies testing a bit.
2708 >         */
2709 >        static int tieBreakOrder(Object a, Object b) {
2710 >            int d;
2711 >            if (a == null || b == null ||
2712 >                (d = a.getClass().getName().
2713 >                 compareTo(b.getClass().getName())) == 0)
2714 >                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2715 >                     -1 : 1);
2716 >            return d;
2717 >        }
2718 >
2719 >        /**
2720 >         * Creates bin with initial set of nodes headed by b.
2721 >         */
2722 >        TreeBin(TreeNode<K,V> b) {
2723 >            super(TREEBIN, null, null, null);
2724 >            this.first = b;
2725 >            TreeNode<K,V> r = null;
2726 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2727 >                next = (TreeNode<K,V>)x.next;
2728 >                x.left = x.right = null;
2729 >                if (r == null) {
2730 >                    x.parent = null;
2731 >                    x.red = false;
2732 >                    r = x;
2733 >                }
2734 >                else {
2735 >                    K k = x.key;
2736 >                    int h = x.hash;
2737 >                    Class<?> kc = null;
2738 >                    for (TreeNode<K,V> p = r;;) {
2739 >                        int dir, ph;
2740 >                        K pk = p.key;
2741 >                        if ((ph = p.hash) > h)
2742 >                            dir = -1;
2743 >                        else if (ph < h)
2744 >                            dir = 1;
2745 >                        else if ((kc == null &&
2746 >                                  (kc = comparableClassFor(k)) == null) ||
2747 >                                 (dir = compareComparables(kc, k, pk)) == 0)
2748 >                            dir = tieBreakOrder(k, pk);
2749 >                            TreeNode<K,V> xp = p;
2750 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2751 >                            x.parent = xp;
2752 >                            if (dir <= 0)
2753 >                                xp.left = x;
2754 >                            else
2755 >                                xp.right = x;
2756 >                            r = balanceInsertion(r, x);
2757 >                            break;
2758 >                        }
2759 >                    }
2760 >                }
2761 >            }
2762 >            this.root = r;
2763 >            assert checkInvariants(root);
2764 >        }
2765 >
2766 >        /**
2767 >         * Acquires write lock for tree restructuring.
2768 >         */
2769 >        private final void lockRoot() {
2770 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2771 >                contendedLock(); // offload to separate method
2772 >        }
2773 >
2774 >        /**
2775 >         * Releases write lock for tree restructuring.
2776 >         */
2777 >        private final void unlockRoot() {
2778 >            lockState = 0;
2779 >        }
2780 >
2781 >        /**
2782 >         * Possibly blocks awaiting root lock.
2783 >         */
2784 >        private final void contendedLock() {
2785 >            boolean waiting = false;
2786 >            for (int s;;) {
2787 >                if (((s = lockState) & ~WAITER) == 0) {
2788 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2789 >                        if (waiting)
2790 >                            waiter = null;
2791 >                        return;
2792 >                    }
2793 >                }
2794 >                else if ((s & WAITER) == 0) {
2795 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2796 >                        waiting = true;
2797 >                        waiter = Thread.currentThread();
2798 >                    }
2799 >                }
2800 >                else if (waiting)
2801 >                    LockSupport.park(this);
2802 >            }
2803 >        }
2804 >
2805 >        /**
2806 >         * Returns matching node or null if none. Tries to search
2807 >         * using tree comparisons from root, but continues linear
2808 >         * search when lock not available.
2809 >         */
2810 >        final Node<K,V> find(int h, Object k) {
2811 >            if (k != null) {
2812 >                for (Node<K,V> e = first; e != null; e = e.next) {
2813 >                    int s; K ek;
2814 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2815 >                        if (e.hash == h &&
2816 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2817 >                            return e;
2818 >                    }
2819 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2820 >                                                 s + READER)) {
2821 >                        TreeNode<K,V> r, p;
2822 >                        try {
2823 >                            p = ((r = root) == null ? null :
2824 >                                 r.findTreeNode(h, k, null));
2825 >                        } finally {
2826 >                            Thread w;
2827 >                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2828 >                                (READER|WAITER) && (w = waiter) != null)
2829 >                                LockSupport.unpark(w);
2830 >                        }
2831 >                        return p;
2832 >                    }
2833 >                }
2834 >            }
2835 >            return null;
2836 >        }
2837 >
2838 >        /**
2839 >         * Finds or adds a node.
2840 >         * @return null if added
2841 >         */
2842 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2843 >            Class<?> kc = null;
2844 >            boolean searched = false;
2845 >            for (TreeNode<K,V> p = root;;) {
2846 >                int dir, ph; K pk;
2847 >                if (p == null) {
2848 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2849 >                    break;
2850 >                }
2851 >                else if ((ph = p.hash) > h)
2852 >                    dir = -1;
2853 >                else if (ph < h)
2854 >                    dir = 1;
2855 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2856 >                    return p;
2857 >                else if ((kc == null &&
2858 >                          (kc = comparableClassFor(k)) == null) ||
2859 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2860 >                    if (!searched) {
2861 >                        TreeNode<K,V> q, ch;
2862 >                        searched = true;
2863 >                        if (((ch = p.left) != null &&
2864 >                             (q = ch.findTreeNode(h, k, kc)) != null) ||
2865 >                            ((ch = p.right) != null &&
2866 >                             (q = ch.findTreeNode(h, k, kc)) != null))
2867 >                            return q;
2868 >                    }
2869 >                    dir = tieBreakOrder(k, pk);
2870 >                }
2871 >
2872 >                TreeNode<K,V> xp = p;
2873 >                if ((p = (dir <= 0) ? p.left : p.right) == null) {
2874 >                    TreeNode<K,V> x, f = first;
2875 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2876 >                    if (f != null)
2877 >                        f.prev = x;
2878 >                    if (dir <= 0)
2879 >                        xp.left = x;
2880 >                    else
2881 >                        xp.right = x;
2882 >                    if (!xp.red)
2883 >                        x.red = true;
2884 >                    else {
2885 >                        lockRoot();
2886 >                        try {
2887 >                            root = balanceInsertion(root, x);
2888 >                        } finally {
2889 >                            unlockRoot();
2890 >                        }
2891 >                    }
2892 >                    break;
2893 >                }
2894 >            }
2895 >            assert checkInvariants(root);
2896 >            return null;
2897 >        }
2898 >
2899 >        /**
2900 >         * Removes the given node, that must be present before this
2901 >         * call.  This is messier than typical red-black deletion code
2902 >         * because we cannot swap the contents of an interior node
2903 >         * with a leaf successor that is pinned by "next" pointers
2904 >         * that are accessible independently of lock. So instead we
2905 >         * swap the tree linkages.
2906 >         *
2907 >         * @return true if now too small, so should be untreeified
2908 >         */
2909 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2910 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2911 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2912 >            TreeNode<K,V> r, rl;
2913 >            if (pred == null)
2914 >                first = next;
2915 >            else
2916 >                pred.next = next;
2917 >            if (next != null)
2918 >                next.prev = pred;
2919 >            if (first == null) {
2920 >                root = null;
2921 >                return true;
2922 >            }
2923 >            if ((r = root) == null || r.right == null || // too small
2924 >                (rl = r.left) == null || rl.left == null)
2925 >                return true;
2926 >            lockRoot();
2927 >            try {
2928 >                TreeNode<K,V> replacement;
2929 >                TreeNode<K,V> pl = p.left;
2930 >                TreeNode<K,V> pr = p.right;
2931 >                if (pl != null && pr != null) {
2932 >                    TreeNode<K,V> s = pr, sl;
2933 >                    while ((sl = s.left) != null) // find successor
2934 >                        s = sl;
2935 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2936 >                    TreeNode<K,V> sr = s.right;
2937 >                    TreeNode<K,V> pp = p.parent;
2938 >                    if (s == pr) { // p was s's direct parent
2939 >                        p.parent = s;
2940 >                        s.right = p;
2941 >                    }
2942 >                    else {
2943 >                        TreeNode<K,V> sp = s.parent;
2944 >                        if ((p.parent = sp) != null) {
2945 >                            if (s == sp.left)
2946 >                                sp.left = p;
2947 >                            else
2948 >                                sp.right = p;
2949 >                        }
2950 >                        if ((s.right = pr) != null)
2951 >                            pr.parent = s;
2952 >                    }
2953 >                    p.left = null;
2954 >                    if ((p.right = sr) != null)
2955 >                        sr.parent = p;
2956 >                    if ((s.left = pl) != null)
2957 >                        pl.parent = s;
2958 >                    if ((s.parent = pp) == null)
2959 >                        r = s;
2960 >                    else if (p == pp.left)
2961 >                        pp.left = s;
2962 >                    else
2963 >                        pp.right = s;
2964 >                    if (sr != null)
2965 >                        replacement = sr;
2966 >                    else
2967 >                        replacement = p;
2968 >                }
2969 >                else if (pl != null)
2970 >                    replacement = pl;
2971 >                else if (pr != null)
2972 >                    replacement = pr;
2973 >                else
2974 >                    replacement = p;
2975 >                if (replacement != p) {
2976 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2977 >                    if (pp == null)
2978 >                        r = replacement;
2979 >                    else if (p == pp.left)
2980 >                        pp.left = replacement;
2981 >                    else
2982 >                        pp.right = replacement;
2983 >                    p.left = p.right = p.parent = null;
2984 >                }
2985 >
2986 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2987 >
2988 >                if (p == replacement) {  // detach pointers
2989 >                    TreeNode<K,V> pp;
2990 >                    if ((pp = p.parent) != null) {
2991 >                        if (p == pp.left)
2992 >                            pp.left = null;
2993 >                        else if (p == pp.right)
2994 >                            pp.right = null;
2995 >                        p.parent = null;
2996 >                    }
2997 >                }
2998 >            } finally {
2999 >                unlockRoot();
3000 >            }
3001 >            assert checkInvariants(root);
3002 >            return false;
3003 >        }
3004 >
3005 >        /* ------------------------------------------------------------ */
3006 >        // Red-black tree methods, all adapted from CLR
3007 >
3008 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
3009 >                                              TreeNode<K,V> p) {
3010 >            TreeNode<K,V> r, pp, rl;
3011 >            if (p != null && (r = p.right) != null) {
3012 >                if ((rl = p.right = r.left) != null)
3013 >                    rl.parent = p;
3014 >                if ((pp = r.parent = p.parent) == null)
3015 >                    (root = r).red = false;
3016 >                else if (pp.left == p)
3017 >                    pp.left = r;
3018 >                else
3019 >                    pp.right = r;
3020 >                r.left = p;
3021 >                p.parent = r;
3022 >            }
3023 >            return root;
3024 >        }
3025 >
3026 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
3027 >                                               TreeNode<K,V> p) {
3028 >            TreeNode<K,V> l, pp, lr;
3029 >            if (p != null && (l = p.left) != null) {
3030 >                if ((lr = p.left = l.right) != null)
3031 >                    lr.parent = p;
3032 >                if ((pp = l.parent = p.parent) == null)
3033 >                    (root = l).red = false;
3034 >                else if (pp.right == p)
3035 >                    pp.right = l;
3036 >                else
3037 >                    pp.left = l;
3038 >                l.right = p;
3039 >                p.parent = l;
3040 >            }
3041 >            return root;
3042 >        }
3043 >
3044 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
3045 >                                                    TreeNode<K,V> x) {
3046 >            x.red = true;
3047 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
3048 >                if ((xp = x.parent) == null) {
3049 >                    x.red = false;
3050 >                    return x;
3051 >                }
3052 >                else if (!xp.red || (xpp = xp.parent) == null)
3053 >                    return root;
3054 >                if (xp == (xppl = xpp.left)) {
3055 >                    if ((xppr = xpp.right) != null && xppr.red) {
3056 >                        xppr.red = false;
3057 >                        xp.red = false;
3058 >                        xpp.red = true;
3059 >                        x = xpp;
3060 >                    }
3061 >                    else {
3062 >                        if (x == xp.right) {
3063 >                            root = rotateLeft(root, x = xp);
3064 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3065 >                        }
3066 >                        if (xp != null) {
3067 >                            xp.red = false;
3068 >                            if (xpp != null) {
3069 >                                xpp.red = true;
3070 >                                root = rotateRight(root, xpp);
3071 >                            }
3072 >                        }
3073 >                    }
3074 >                }
3075 >                else {
3076 >                    if (xppl != null && xppl.red) {
3077 >                        xppl.red = false;
3078 >                        xp.red = false;
3079 >                        xpp.red = true;
3080 >                        x = xpp;
3081 >                    }
3082 >                    else {
3083 >                        if (x == xp.left) {
3084 >                            root = rotateRight(root, x = xp);
3085 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3086 >                        }
3087 >                        if (xp != null) {
3088 >                            xp.red = false;
3089 >                            if (xpp != null) {
3090 >                                xpp.red = true;
3091 >                                root = rotateLeft(root, xpp);
3092 >                            }
3093 >                        }
3094 >                    }
3095 >                }
3096 >            }
3097 >        }
3098 >
3099 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3100 >                                                   TreeNode<K,V> x) {
3101 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
3102 >                if (x == null || x == root)
3103 >                    return root;
3104 >                else if ((xp = x.parent) == null) {
3105 >                    x.red = false;
3106 >                    return x;
3107 >                }
3108 >                else if (x.red) {
3109 >                    x.red = false;
3110 >                    return root;
3111 >                }
3112 >                else if ((xpl = xp.left) == x) {
3113 >                    if ((xpr = xp.right) != null && xpr.red) {
3114 >                        xpr.red = false;
3115 >                        xp.red = true;
3116 >                        root = rotateLeft(root, xp);
3117 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3118 >                    }
3119 >                    if (xpr == null)
3120 >                        x = xp;
3121 >                    else {
3122 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3123 >                        if ((sr == null || !sr.red) &&
3124 >                            (sl == null || !sl.red)) {
3125 >                            xpr.red = true;
3126 >                            x = xp;
3127 >                        }
3128 >                        else {
3129 >                            if (sr == null || !sr.red) {
3130 >                                if (sl != null)
3131 >                                    sl.red = false;
3132 >                                xpr.red = true;
3133 >                                root = rotateRight(root, xpr);
3134 >                                xpr = (xp = x.parent) == null ?
3135 >                                    null : xp.right;
3136 >                            }
3137 >                            if (xpr != null) {
3138 >                                xpr.red = (xp == null) ? false : xp.red;
3139 >                                if ((sr = xpr.right) != null)
3140 >                                    sr.red = false;
3141 >                            }
3142 >                            if (xp != null) {
3143 >                                xp.red = false;
3144 >                                root = rotateLeft(root, xp);
3145 >                            }
3146 >                            x = root;
3147 >                        }
3148 >                    }
3149 >                }
3150 >                else { // symmetric
3151 >                    if (xpl != null && xpl.red) {
3152 >                        xpl.red = false;
3153 >                        xp.red = true;
3154 >                        root = rotateRight(root, xp);
3155 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3156 >                    }
3157 >                    if (xpl == null)
3158 >                        x = xp;
3159 >                    else {
3160 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3161 >                        if ((sl == null || !sl.red) &&
3162 >                            (sr == null || !sr.red)) {
3163 >                            xpl.red = true;
3164 >                            x = xp;
3165 >                        }
3166 >                        else {
3167 >                            if (sl == null || !sl.red) {
3168 >                                if (sr != null)
3169 >                                    sr.red = false;
3170 >                                xpl.red = true;
3171 >                                root = rotateLeft(root, xpl);
3172 >                                xpl = (xp = x.parent) == null ?
3173 >                                    null : xp.left;
3174 >                            }
3175 >                            if (xpl != null) {
3176 >                                xpl.red = (xp == null) ? false : xp.red;
3177 >                                if ((sl = xpl.left) != null)
3178 >                                    sl.red = false;
3179 >                            }
3180 >                            if (xp != null) {
3181 >                                xp.red = false;
3182 >                                root = rotateRight(root, xp);
3183 >                            }
3184 >                            x = root;
3185 >                        }
3186 >                    }
3187 >                }
3188 >            }
3189 >        }
3190 >
3191 >        /**
3192 >         * Recursive invariant check
3193 >         */
3194 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3195 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3196 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3197 >            if (tb != null && tb.next != t)
3198 >                return false;
3199 >            if (tn != null && tn.prev != t)
3200 >                return false;
3201 >            if (tp != null && t != tp.left && t != tp.right)
3202 >                return false;
3203 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3204 >                return false;
3205 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3206 >                return false;
3207 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3208 >                return false;
3209 >            if (tl != null && !checkInvariants(tl))
3210 >                return false;
3211 >            if (tr != null && !checkInvariants(tr))
3212 >                return false;
3213 >            return true;
3214 >        }
3215 >
3216 >        private static final sun.misc.Unsafe U;
3217 >        private static final long LOCKSTATE;
3218 >        static {
3219 >            try {
3220 >                U = sun.misc.Unsafe.getUnsafe();
3221 >                Class<?> k = TreeBin.class;
3222 >                LOCKSTATE = U.objectFieldOffset
3223 >                    (k.getDeclaredField("lockState"));
3224 >            } catch (Exception e) {
3225 >                throw new Error(e);
3226              }
3227          }
3248        return true;
3228      }
3229  
3230 <    /* ----------------Iterators -------------- */
3230 >    /* ----------------Table Traversal -------------- */
3231 >
3232 >    /**
3233 >     * Records the table, its length, and current traversal index for a
3234 >     * traverser that must process a region of a forwarded table before
3235 >     * proceeding with current table.
3236 >     */
3237 >    static final class TableStack<K,V> {
3238 >        int length;
3239 >        int index;
3240 >        Node<K,V>[] tab;
3241 >        TableStack<K,V> next;
3242 >    }
3243 >
3244 >    /**
3245 >     * Encapsulates traversal for methods such as containsValue; also
3246 >     * serves as a base class for other iterators and spliterators.
3247 >     *
3248 >     * Method advance visits once each still-valid node that was
3249 >     * reachable upon iterator construction. It might miss some that
3250 >     * were added to a bin after the bin was visited, which is OK wrt
3251 >     * consistency guarantees. Maintaining this property in the face
3252 >     * of possible ongoing resizes requires a fair amount of
3253 >     * bookkeeping state that is difficult to optimize away amidst
3254 >     * volatile accesses.  Even so, traversal maintains reasonable
3255 >     * throughput.
3256 >     *
3257 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3258 >     * However, if the table has been resized, then all future steps
3259 >     * must traverse both the bin at the current index as well as at
3260 >     * (index + baseSize); and so on for further resizings. To
3261 >     * paranoically cope with potential sharing by users of iterators
3262 >     * across threads, iteration terminates if a bounds checks fails
3263 >     * for a table read.
3264 >     */
3265 >    static class Traverser<K,V> {
3266 >        Node<K,V>[] tab;        // current table; updated if resized
3267 >        Node<K,V> next;         // the next entry to use
3268 >        TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3269 >        int index;              // index of bin to use next
3270 >        int baseIndex;          // current index of initial table
3271 >        int baseLimit;          // index bound for initial table
3272 >        final int baseSize;     // initial table size
3273 >
3274 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3275 >            this.tab = tab;
3276 >            this.baseSize = size;
3277 >            this.baseIndex = this.index = index;
3278 >            this.baseLimit = limit;
3279 >            this.next = null;
3280 >        }
3281 >
3282 >        /**
3283 >         * Advances if possible, returning next valid node, or null if none.
3284 >         */
3285 >        final Node<K,V> advance() {
3286 >            Node<K,V> e;
3287 >            if ((e = next) != null)
3288 >                e = e.next;
3289 >            for (;;) {
3290 >                Node<K,V>[] t; int i, n;  // must use locals in checks
3291 >                if (e != null)
3292 >                    return next = e;
3293 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3294 >                    (n = t.length) <= (i = index) || i < 0)
3295 >                    return next = null;
3296 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
3297 >                    if (e instanceof ForwardingNode) {
3298 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3299 >                        e = null;
3300 >                        pushState(t, i, n);
3301 >                        continue;
3302 >                    }
3303 >                    else if (e instanceof TreeBin)
3304 >                        e = ((TreeBin<K,V>)e).first;
3305 >                    else
3306 >                        e = null;
3307 >                }
3308 >                if (stack != null)
3309 >                    recoverState(n);
3310 >                else if ((index = i + baseSize) >= n)
3311 >                    index = ++baseIndex; // visit upper slots if present
3312 >            }
3313 >        }
3314  
3315 <    @SuppressWarnings("serial") static final class KeyIterator<K,V> extends Traverser<K,V,Object>
3316 <        implements Spliterator<K>, Enumeration<K> {
3317 <        KeyIterator(ConcurrentHashMap<K, V> map) { super(map); }
3318 <        KeyIterator(Traverser<K,V,Object> it) {
3319 <            super(it);
3315 >        /**
3316 >         * Saves traversal state upon encountering a forwarding node.
3317 >         */
3318 >        private void pushState(Node<K,V>[] t, int i, int n) {
3319 >            TableStack<K,V> s = spare;  // reuse if possible
3320 >            if (s != null)
3321 >                spare = s.next;
3322 >            else
3323 >                s = new TableStack<K,V>();
3324 >            s.tab = t;
3325 >            s.length = n;
3326 >            s.index = i;
3327 >            s.next = stack;
3328 >            stack = s;
3329          }
3330 <        public KeyIterator<K,V> split() {
3331 <            if (nextKey != null)
3330 >
3331 >        /**
3332 >         * Possibly pops traversal state.
3333 >         *
3334 >         * @param n length of current table
3335 >         */
3336 >        private void recoverState(int n) {
3337 >            TableStack<K,V> s; int len;
3338 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
3339 >                n = len;
3340 >                index = s.index;
3341 >                tab = s.tab;
3342 >                s.tab = null;
3343 >                TableStack<K,V> next = s.next;
3344 >                s.next = spare; // save for reuse
3345 >                stack = next;
3346 >                spare = s;
3347 >            }
3348 >            if (s == null && (index += baseSize) >= n)
3349 >                index = ++baseIndex;
3350 >        }
3351 >    }
3352 >
3353 >    /**
3354 >     * Base of key, value, and entry Iterators. Adds fields to
3355 >     * Traverser to support iterator.remove.
3356 >     */
3357 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3358 >        final ConcurrentHashMap<K,V> map;
3359 >        Node<K,V> lastReturned;
3360 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3361 >                    ConcurrentHashMap<K,V> map) {
3362 >            super(tab, size, index, limit);
3363 >            this.map = map;
3364 >            advance();
3365 >        }
3366 >
3367 >        public final boolean hasNext() { return next != null; }
3368 >        public final boolean hasMoreElements() { return next != null; }
3369 >
3370 >        public final void remove() {
3371 >            Node<K,V> p;
3372 >            if ((p = lastReturned) == null)
3373                  throw new IllegalStateException();
3374 <            return new KeyIterator<K,V>(this);
3374 >            lastReturned = null;
3375 >            map.replaceNode(p.key, null, null);
3376          }
3377 <        @SuppressWarnings("unchecked") public final K next() {
3378 <            if (nextVal == null && advance() == null)
3377 >    }
3378 >
3379 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3380 >        implements Iterator<K>, Enumeration<K> {
3381 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3382 >                    ConcurrentHashMap<K,V> map) {
3383 >            super(tab, index, size, limit, map);
3384 >        }
3385 >
3386 >        public final K next() {
3387 >            Node<K,V> p;
3388 >            if ((p = next) == null)
3389                  throw new NoSuchElementException();
3390 <            Object k = nextKey;
3391 <            nextVal = null;
3392 <            return (K) k;
3390 >            K k = p.key;
3391 >            lastReturned = p;
3392 >            advance();
3393 >            return k;
3394          }
3395  
3396          public final K nextElement() { return next(); }
3397      }
3398  
3399 <    @SuppressWarnings("serial") static final class ValueIterator<K,V> extends Traverser<K,V,Object>
3400 <        implements Spliterator<V>, Enumeration<V> {
3401 <        ValueIterator(ConcurrentHashMap<K, V> map) { super(map); }
3402 <        ValueIterator(Traverser<K,V,Object> it) {
3403 <            super(it);
3280 <        }
3281 <        public ValueIterator<K,V> split() {
3282 <            if (nextKey != null)
3283 <                throw new IllegalStateException();
3284 <            return new ValueIterator<K,V>(this);
3399 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3400 >        implements Iterator<V>, Enumeration<V> {
3401 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3402 >                      ConcurrentHashMap<K,V> map) {
3403 >            super(tab, index, size, limit, map);
3404          }
3405  
3406 <        @SuppressWarnings("unchecked") public final V next() {
3407 <            Object v;
3408 <            if ((v = nextVal) == null && (v = advance()) == null)
3406 >        public final V next() {
3407 >            Node<K,V> p;
3408 >            if ((p = next) == null)
3409                  throw new NoSuchElementException();
3410 <            nextVal = null;
3411 <            return (V) v;
3410 >            V v = p.val;
3411 >            lastReturned = p;
3412 >            advance();
3413 >            return v;
3414          }
3415  
3416          public final V nextElement() { return next(); }
3417      }
3418  
3419 <    @SuppressWarnings("serial") static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3420 <        implements Spliterator<Map.Entry<K,V>> {
3421 <        EntryIterator(ConcurrentHashMap<K, V> map) { super(map); }
3422 <        EntryIterator(Traverser<K,V,Object> it) {
3423 <            super(it);
3303 <        }
3304 <        public EntryIterator<K,V> split() {
3305 <            if (nextKey != null)
3306 <                throw new IllegalStateException();
3307 <            return new EntryIterator<K,V>(this);
3419 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3420 >        implements Iterator<Map.Entry<K,V>> {
3421 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3422 >                      ConcurrentHashMap<K,V> map) {
3423 >            super(tab, index, size, limit, map);
3424          }
3425  
3426 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3427 <            Object v;
3428 <            if ((v = nextVal) == null && (v = advance()) == null)
3426 >        public final Map.Entry<K,V> next() {
3427 >            Node<K,V> p;
3428 >            if ((p = next) == null)
3429                  throw new NoSuchElementException();
3430 <            Object k = nextKey;
3431 <            nextVal = null;
3432 <            return new MapEntry<K,V>((K)k, (V)v, map);
3430 >            K k = p.key;
3431 >            V v = p.val;
3432 >            lastReturned = p;
3433 >            advance();
3434 >            return new MapEntry<K,V>(k, v, map);
3435          }
3436      }
3437  
3438      /**
3439 <     * Exported Entry for iterators
3439 >     * Exported Entry for EntryIterator
3440       */
3441 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3441 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3442          final K key; // non-null
3443          V val;       // non-null
3444 <        final ConcurrentHashMap<K, V> map;
3445 <        MapEntry(K key, V val, ConcurrentHashMap<K, V> map) {
3444 >        final ConcurrentHashMap<K,V> map;
3445 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3446              this.key = key;
3447              this.val = val;
3448              this.map = map;
3449          }
3450 <        public final K getKey()       { return key; }
3451 <        public final V getValue()     { return val; }
3452 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3453 <        public final String toString(){ return key + "=" + val; }
3450 >        public K getKey()        { return key; }
3451 >        public V getValue()      { return val; }
3452 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3453 >        public String toString() { return key + "=" + val; }
3454  
3455 <        public final boolean equals(Object o) {
3455 >        public boolean equals(Object o) {
3456              Object k, v; Map.Entry<?,?> e;
3457              return ((o instanceof Map.Entry) &&
3458                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3348 | Line 3466 | public class ConcurrentHashMap<K, V>
3466           * value to return is somewhat arbitrary here. Since we do not
3467           * necessarily track asynchronous changes, the most recent
3468           * "previous" value could be different from what we return (or
3469 <         * could even have been removed in which case the put will
3469 >         * could even have been removed, in which case the put will
3470           * re-establish). We do not and cannot guarantee more.
3471           */
3472 <        public final V setValue(V value) {
3472 >        public V setValue(V value) {
3473              if (value == null) throw new NullPointerException();
3474              V v = val;
3475              val = value;
# Line 3360 | Line 3478 | public class ConcurrentHashMap<K, V>
3478          }
3479      }
3480  
3481 <    /* ----------------Views -------------- */
3481 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3482 >        implements Spliterator<K> {
3483 >        long est;               // size estimate
3484 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3485 >                       long est) {
3486 >            super(tab, size, index, limit);
3487 >            this.est = est;
3488 >        }
3489 >
3490 >        public Spliterator<K> trySplit() {
3491 >            int i, f, h;
3492 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3493 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3494 >                                        f, est >>>= 1);
3495 >        }
3496  
3497 <    /**
3498 <     * Base class for views.
3499 <     */
3500 <    static abstract class CHMView<K, V> {
3501 <        final ConcurrentHashMap<K, V> map;
3370 <        CHMView(ConcurrentHashMap<K, V> map)  { this.map = map; }
3371 <        public final int size()                 { return map.size(); }
3372 <        public final boolean isEmpty()          { return map.isEmpty(); }
3373 <        public final void clear()               { map.clear(); }
3497 >        public void forEachRemaining(Consumer<? super K> action) {
3498 >            if (action == null) throw new NullPointerException();
3499 >            for (Node<K,V> p; (p = advance()) != null;)
3500 >                action.accept(p.key);
3501 >        }
3502  
3503 <        // implementations below rely on concrete classes supplying these
3504 <        abstract public Iterator<?> iterator();
3505 <        abstract public boolean contains(Object o);
3506 <        abstract public boolean remove(Object o);
3503 >        public boolean tryAdvance(Consumer<? super K> action) {
3504 >            if (action == null) throw new NullPointerException();
3505 >            Node<K,V> p;
3506 >            if ((p = advance()) == null)
3507 >                return false;
3508 >            action.accept(p.key);
3509 >            return true;
3510 >        }
3511  
3512 <        private static final String oomeMsg = "Required array size too large";
3512 >        public long estimateSize() { return est; }
3513  
3514 <        public final Object[] toArray() {
3515 <            long sz = map.mappingCount();
3516 <            if (sz > (long)(MAX_ARRAY_SIZE))
3385 <                throw new OutOfMemoryError(oomeMsg);
3386 <            int n = (int)sz;
3387 <            Object[] r = new Object[n];
3388 <            int i = 0;
3389 <            Iterator<?> it = iterator();
3390 <            while (it.hasNext()) {
3391 <                if (i == n) {
3392 <                    if (n >= MAX_ARRAY_SIZE)
3393 <                        throw new OutOfMemoryError(oomeMsg);
3394 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
3395 <                        n = MAX_ARRAY_SIZE;
3396 <                    else
3397 <                        n += (n >>> 1) + 1;
3398 <                    r = Arrays.copyOf(r, n);
3399 <                }
3400 <                r[i++] = it.next();
3401 <            }
3402 <            return (i == n) ? r : Arrays.copyOf(r, i);
3514 >        public int characteristics() {
3515 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3516 >                Spliterator.NONNULL;
3517          }
3518 +    }
3519  
3520 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
3521 <            long sz = map.mappingCount();
3522 <            if (sz > (long)(MAX_ARRAY_SIZE))
3523 <                throw new OutOfMemoryError(oomeMsg);
3524 <            int m = (int)sz;
3525 <            T[] r = (a.length >= m) ? a :
3526 <                (T[])java.lang.reflect.Array
3412 <                .newInstance(a.getClass().getComponentType(), m);
3413 <            int n = r.length;
3414 <            int i = 0;
3415 <            Iterator<?> it = iterator();
3416 <            while (it.hasNext()) {
3417 <                if (i == n) {
3418 <                    if (n >= MAX_ARRAY_SIZE)
3419 <                        throw new OutOfMemoryError(oomeMsg);
3420 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
3421 <                        n = MAX_ARRAY_SIZE;
3422 <                    else
3423 <                        n += (n >>> 1) + 1;
3424 <                    r = Arrays.copyOf(r, n);
3425 <                }
3426 <                r[i++] = (T)it.next();
3427 <            }
3428 <            if (a == r && i < n) {
3429 <                r[i] = null; // null-terminate
3430 <                return r;
3431 <            }
3432 <            return (i == n) ? r : Arrays.copyOf(r, i);
3520 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3521 >        implements Spliterator<V> {
3522 >        long est;               // size estimate
3523 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3524 >                         long est) {
3525 >            super(tab, size, index, limit);
3526 >            this.est = est;
3527          }
3528  
3529 <        public final int hashCode() {
3530 <            int h = 0;
3531 <            for (Iterator<?> it = iterator(); it.hasNext();)
3532 <                h += it.next().hashCode();
3533 <            return h;
3529 >        public Spliterator<V> trySplit() {
3530 >            int i, f, h;
3531 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3532 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3533 >                                          f, est >>>= 1);
3534          }
3535  
3536 <        public final String toString() {
3537 <            StringBuilder sb = new StringBuilder();
3538 <            sb.append('[');
3539 <            Iterator<?> it = iterator();
3446 <            if (it.hasNext()) {
3447 <                for (;;) {
3448 <                    Object e = it.next();
3449 <                    sb.append(e == this ? "(this Collection)" : e);
3450 <                    if (!it.hasNext())
3451 <                        break;
3452 <                    sb.append(',').append(' ');
3453 <                }
3454 <            }
3455 <            return sb.append(']').toString();
3536 >        public void forEachRemaining(Consumer<? super V> action) {
3537 >            if (action == null) throw new NullPointerException();
3538 >            for (Node<K,V> p; (p = advance()) != null;)
3539 >                action.accept(p.val);
3540          }
3541  
3542 <        public final boolean containsAll(Collection<?> c) {
3543 <            if (c != this) {
3544 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
3545 <                    Object e = it.next();
3546 <                    if (e == null || !contains(e))
3547 <                        return false;
3464 <                }
3465 <            }
3542 >        public boolean tryAdvance(Consumer<? super V> action) {
3543 >            if (action == null) throw new NullPointerException();
3544 >            Node<K,V> p;
3545 >            if ((p = advance()) == null)
3546 >                return false;
3547 >            action.accept(p.val);
3548              return true;
3549          }
3550  
3551 <        public final boolean removeAll(Collection<?> c) {
3470 <            boolean modified = false;
3471 <            for (Iterator<?> it = iterator(); it.hasNext();) {
3472 <                if (c.contains(it.next())) {
3473 <                    it.remove();
3474 <                    modified = true;
3475 <                }
3476 <            }
3477 <            return modified;
3478 <        }
3551 >        public long estimateSize() { return est; }
3552  
3553 <        public final boolean retainAll(Collection<?> c) {
3554 <            boolean modified = false;
3482 <            for (Iterator<?> it = iterator(); it.hasNext();) {
3483 <                if (!c.contains(it.next())) {
3484 <                    it.remove();
3485 <                    modified = true;
3486 <                }
3487 <            }
3488 <            return modified;
3553 >        public int characteristics() {
3554 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3555          }
3490
3556      }
3557  
3558 <    static final class Values<K,V> extends CHMView<K,V>
3559 <        implements Collection<V> {
3560 <        Values(ConcurrentHashMap<K, V> map)   { super(map); }
3561 <        public final boolean contains(Object o) { return map.containsValue(o); }
3562 <        public final boolean remove(Object o) {
3563 <            if (o != null) {
3564 <                Iterator<V> it = new ValueIterator<K,V>(map);
3565 <                while (it.hasNext()) {
3566 <                    if (o.equals(it.next())) {
3502 <                        it.remove();
3503 <                        return true;
3504 <                    }
3505 <                }
3506 <            }
3507 <            return false;
3508 <        }
3509 <        public final Iterator<V> iterator() {
3510 <            return new ValueIterator<K,V>(map);
3511 <        }
3512 <        public final boolean add(V e) {
3513 <            throw new UnsupportedOperationException();
3514 <        }
3515 <        public final boolean addAll(Collection<? extends V> c) {
3516 <            throw new UnsupportedOperationException();
3558 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3559 >        implements Spliterator<Map.Entry<K,V>> {
3560 >        final ConcurrentHashMap<K,V> map; // To export MapEntry
3561 >        long est;               // size estimate
3562 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3563 >                         long est, ConcurrentHashMap<K,V> map) {
3564 >            super(tab, size, index, limit);
3565 >            this.map = map;
3566 >            this.est = est;
3567          }
3568  
3569 <    }
3570 <
3571 <    static final class EntrySet<K,V> extends CHMView<K,V>
3572 <        implements Set<Map.Entry<K,V>> {
3573 <        EntrySet(ConcurrentHashMap<K, V> map) { super(map); }
3524 <        public final boolean contains(Object o) {
3525 <            Object k, v, r; Map.Entry<?,?> e;
3526 <            return ((o instanceof Map.Entry) &&
3527 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3528 <                    (r = map.get(k)) != null &&
3529 <                    (v = e.getValue()) != null &&
3530 <                    (v == r || v.equals(r)));
3531 <        }
3532 <        public final boolean remove(Object o) {
3533 <            Object k, v; Map.Entry<?,?> e;
3534 <            return ((o instanceof Map.Entry) &&
3535 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3536 <                    (v = e.getValue()) != null &&
3537 <                    map.remove(k, v));
3538 <        }
3539 <        public final Iterator<Map.Entry<K,V>> iterator() {
3540 <            return new EntryIterator<K,V>(map);
3541 <        }
3542 <        public final boolean add(Entry<K,V> e) {
3543 <            throw new UnsupportedOperationException();
3544 <        }
3545 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
3546 <            throw new UnsupportedOperationException();
3569 >        public Spliterator<Map.Entry<K,V>> trySplit() {
3570 >            int i, f, h;
3571 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3572 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3573 >                                          f, est >>>= 1, map);
3574          }
3575 <        public boolean equals(Object o) {
3576 <            Set<?> c;
3577 <            return ((o instanceof Set) &&
3578 <                    ((c = (Set<?>)o) == this ||
3579 <                     (containsAll(c) && c.containsAll(this))));
3575 >
3576 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3577 >            if (action == null) throw new NullPointerException();
3578 >            for (Node<K,V> p; (p = advance()) != null; )
3579 >                action.accept(new MapEntry<K,V>(p.key, p.val, map));
3580          }
3554    }
3581  
3582 <    /* ---------------- Serialization Support -------------- */
3582 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3583 >            if (action == null) throw new NullPointerException();
3584 >            Node<K,V> p;
3585 >            if ((p = advance()) == null)
3586 >                return false;
3587 >            action.accept(new MapEntry<K,V>(p.key, p.val, map));
3588 >            return true;
3589 >        }
3590  
3591 <    /**
3559 <     * Stripped-down version of helper class used in previous version,
3560 <     * declared for the sake of serialization compatibility
3561 <     */
3562 <    static class Segment<K,V> implements Serializable {
3563 <        private static final long serialVersionUID = 2249069246763182397L;
3564 <        final float loadFactor;
3565 <        Segment(float lf) { this.loadFactor = lf; }
3566 <    }
3591 >        public long estimateSize() { return est; }
3592  
3593 <    /**
3594 <     * Saves the state of the {@code ConcurrentHashMap} instance to a
3595 <     * stream (i.e., serializes it).
3571 <     * @param s the stream
3572 <     * @serialData
3573 <     * the key (Object) and value (Object)
3574 <     * for each key-value mapping, followed by a null pair.
3575 <     * The key-value mappings are emitted in no particular order.
3576 <     */
3577 <    @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s)
3578 <        throws java.io.IOException {
3579 <        if (segments == null) { // for serialization compatibility
3580 <            segments = (Segment<K,V>[])
3581 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3582 <            for (int i = 0; i < segments.length; ++i)
3583 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3584 <        }
3585 <        s.defaultWriteObject();
3586 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3587 <        Object v;
3588 <        while ((v = it.advance()) != null) {
3589 <            s.writeObject(it.nextKey);
3590 <            s.writeObject(v);
3593 >        public int characteristics() {
3594 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3595 >                Spliterator.NONNULL;
3596          }
3592        s.writeObject(null);
3593        s.writeObject(null);
3594        segments = null; // throw away
3597      }
3598  
3599 +    // Parallel bulk operations
3600 +
3601      /**
3602 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3603 <     * @param s the stream
3602 >     * Computes initial batch value for bulk tasks. The returned value
3603 >     * is approximately exp2 of the number of times (minus one) to
3604 >     * split task by two before executing leaf action. This value is
3605 >     * faster to compute and more convenient to use as a guide to
3606 >     * splitting than is the depth, since it is used while dividing by
3607 >     * two anyway.
3608       */
3609 <    @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
3610 <        throws java.io.IOException, ClassNotFoundException {
3611 <        s.defaultReadObject();
3612 <        this.segments = null; // unneeded
3613 <        // initialize transient final field
3614 <        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
3607 <
3608 <        // Create all nodes, then place in table once size is known
3609 <        long size = 0L;
3610 <        Node p = null;
3611 <        for (;;) {
3612 <            K k = (K) s.readObject();
3613 <            V v = (V) s.readObject();
3614 <            if (k != null && v != null) {
3615 <                int h = spread(k.hashCode());
3616 <                p = new Node(h, k, v, p);
3617 <                ++size;
3618 <            }
3619 <            else
3620 <                break;
3621 <        }
3622 <        if (p != null) {
3623 <            boolean init = false;
3624 <            int n;
3625 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3626 <                n = MAXIMUM_CAPACITY;
3627 <            else {
3628 <                int sz = (int)size;
3629 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3630 <            }
3631 <            int sc = sizeCtl;
3632 <            boolean collide = false;
3633 <            if (n > sc &&
3634 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3635 <                try {
3636 <                    if (table == null) {
3637 <                        init = true;
3638 <                        Node[] tab = new Node[n];
3639 <                        int mask = n - 1;
3640 <                        while (p != null) {
3641 <                            int j = p.hash & mask;
3642 <                            Node next = p.next;
3643 <                            Node q = p.next = tabAt(tab, j);
3644 <                            setTabAt(tab, j, p);
3645 <                            if (!collide && q != null && q.hash == p.hash)
3646 <                                collide = true;
3647 <                            p = next;
3648 <                        }
3649 <                        table = tab;
3650 <                        counter.add(size);
3651 <                        sc = n - (n >>> 2);
3652 <                    }
3653 <                } finally {
3654 <                    sizeCtl = sc;
3655 <                }
3656 <                if (collide) { // rescan and convert to TreeBins
3657 <                    Node[] tab = table;
3658 <                    for (int i = 0; i < tab.length; ++i) {
3659 <                        int c = 0;
3660 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3661 <                            if (++c > TREE_THRESHOLD &&
3662 <                                (e.key instanceof Comparable)) {
3663 <                                replaceWithTreeBin(tab, i, e.key);
3664 <                                break;
3665 <                            }
3666 <                        }
3667 <                    }
3668 <                }
3669 <            }
3670 <            if (!init) { // Can only happen if unsafely published.
3671 <                while (p != null) {
3672 <                    internalPut(p.key, p.val);
3673 <                    p = p.next;
3674 <                }
3675 <            }
3676 <        }
3609 >    final int batchFor(long b) {
3610 >        long n;
3611 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3612 >            return 0;
3613 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3614 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3615      }
3616  
3679
3680    // -------------------------------------------------------
3681
3682    // Sams
3683    /** Interface describing a void action of one argument */
3684    public interface Action<A> { void apply(A a); }
3685    /** Interface describing a void action of two arguments */
3686    public interface BiAction<A,B> { void apply(A a, B b); }
3687    /** Interface describing a function of one argument */
3688    public interface Fun<A,T> { T apply(A a); }
3689    /** Interface describing a function of two arguments */
3690    public interface BiFun<A,B,T> { T apply(A a, B b); }
3691    /** Interface describing a function of no arguments */
3692    public interface Generator<T> { T apply(); }
3693    /** Interface describing a function mapping its argument to a double */
3694    public interface ObjectToDouble<A> { double apply(A a); }
3695    /** Interface describing a function mapping its argument to a long */
3696    public interface ObjectToLong<A> { long apply(A a); }
3697    /** Interface describing a function mapping its argument to an int */
3698    public interface ObjectToInt<A> {int apply(A a); }
3699    /** Interface describing a function mapping two arguments to a double */
3700    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
3701    /** Interface describing a function mapping two arguments to a long */
3702    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
3703    /** Interface describing a function mapping two arguments to an int */
3704    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
3705    /** Interface describing a function mapping a double to a double */
3706    public interface DoubleToDouble { double apply(double a); }
3707    /** Interface describing a function mapping a long to a long */
3708    public interface LongToLong { long apply(long a); }
3709    /** Interface describing a function mapping an int to an int */
3710    public interface IntToInt { int apply(int a); }
3711    /** Interface describing a function mapping two doubles to a double */
3712    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3713    /** Interface describing a function mapping two longs to a long */
3714    public interface LongByLongToLong { long apply(long a, long b); }
3715    /** Interface describing a function mapping two ints to an int */
3716    public interface IntByIntToInt { int apply(int a, int b); }
3717
3718
3719    // -------------------------------------------------------
3720
3617      /**
3618       * Performs the given action for each (key, value).
3619       *
3620 +     * @param parallelismThreshold the (estimated) number of elements
3621 +     * needed for this operation to be executed in parallel
3622       * @param action the action
3623 +     * @since 1.8
3624       */
3625 <    public void forEach(BiAction<K,V> action) {
3626 <        ForkJoinTasks.forEach
3627 <            (this, action).invoke();
3625 >    public void forEach(long parallelismThreshold,
3626 >                        BiConsumer<? super K,? super V> action) {
3627 >        if (action == null) throw new NullPointerException();
3628 >        new ForEachMappingTask<K,V>
3629 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3630 >             action).invoke();
3631      }
3632  
3633      /**
3634       * Performs the given action for each non-null transformation
3635       * of each (key, value).
3636       *
3637 +     * @param parallelismThreshold the (estimated) number of elements
3638 +     * needed for this operation to be executed in parallel
3639       * @param transformer a function returning the transformation
3640 <     * for an element, or null of there is no transformation (in
3641 <     * which case the action is not applied).
3640 >     * for an element, or null if there is no transformation (in
3641 >     * which case the action is not applied)
3642       * @param action the action
3643 +     * @param <U> the return type of the transformer
3644 +     * @since 1.8
3645       */
3646 <    public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3647 <                            Action<U> action) {
3648 <        ForkJoinTasks.forEach
3649 <            (this, transformer, action).invoke();
3646 >    public <U> void forEach(long parallelismThreshold,
3647 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3648 >                            Consumer<? super U> action) {
3649 >        if (transformer == null || action == null)
3650 >            throw new NullPointerException();
3651 >        new ForEachTransformedMappingTask<K,V,U>
3652 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3653 >             transformer, action).invoke();
3654      }
3655  
3656      /**
# Line 3750 | Line 3660 | public class ConcurrentHashMap<K, V>
3660       * results of any other parallel invocations of the search
3661       * function are ignored.
3662       *
3663 +     * @param parallelismThreshold the (estimated) number of elements
3664 +     * needed for this operation to be executed in parallel
3665       * @param searchFunction a function returning a non-null
3666       * result on success, else null
3667 +     * @param <U> the return type of the search function
3668       * @return a non-null result from applying the given search
3669       * function on each (key, value), or null if none
3670 +     * @since 1.8
3671       */
3672 <    public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3673 <        return ForkJoinTasks.search
3674 <            (this, searchFunction).invoke();
3672 >    public <U> U search(long parallelismThreshold,
3673 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3674 >        if (searchFunction == null) throw new NullPointerException();
3675 >        return new SearchMappingsTask<K,V,U>
3676 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3677 >             searchFunction, new AtomicReference<U>()).invoke();
3678      }
3679  
3680      /**
# Line 3765 | Line 3682 | public class ConcurrentHashMap<K, V>
3682       * of all (key, value) pairs using the given reducer to
3683       * combine values, or null if none.
3684       *
3685 +     * @param parallelismThreshold the (estimated) number of elements
3686 +     * needed for this operation to be executed in parallel
3687       * @param transformer a function returning the transformation
3688 <     * for an element, or null of there is no transformation (in
3689 <     * which case it is not combined).
3688 >     * for an element, or null if there is no transformation (in
3689 >     * which case it is not combined)
3690       * @param reducer a commutative associative combining function
3691 +     * @param <U> the return type of the transformer
3692       * @return the result of accumulating the given transformation
3693       * of all (key, value) pairs
3694 +     * @since 1.8
3695       */
3696 <    public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3697 <                        BiFun<? super U, ? super U, ? extends U> reducer) {
3698 <        return ForkJoinTasks.reduce
3699 <            (this, transformer, reducer).invoke();
3696 >    public <U> U reduce(long parallelismThreshold,
3697 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3698 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3699 >        if (transformer == null || reducer == null)
3700 >            throw new NullPointerException();
3701 >        return new MapReduceMappingsTask<K,V,U>
3702 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3703 >             null, transformer, reducer).invoke();
3704      }
3705  
3706      /**
# Line 3783 | Line 3708 | public class ConcurrentHashMap<K, V>
3708       * of all (key, value) pairs using the given reducer to
3709       * combine values, and the given basis as an identity value.
3710       *
3711 +     * @param parallelismThreshold the (estimated) number of elements
3712 +     * needed for this operation to be executed in parallel
3713       * @param transformer a function returning the transformation
3714       * for an element
3715       * @param basis the identity (initial default value) for the reduction
3716       * @param reducer a commutative associative combining function
3717       * @return the result of accumulating the given transformation
3718       * of all (key, value) pairs
3719 +     * @since 1.8
3720       */
3721 <    public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
3721 >    public double reduceToDouble(long parallelismThreshold,
3722 >                                 ToDoubleBiFunction<? super K, ? super V> transformer,
3723                                   double basis,
3724 <                                 DoubleByDoubleToDouble reducer) {
3725 <        return ForkJoinTasks.reduceToDouble
3726 <            (this, transformer, basis, reducer).invoke();
3724 >                                 DoubleBinaryOperator reducer) {
3725 >        if (transformer == null || reducer == null)
3726 >            throw new NullPointerException();
3727 >        return new MapReduceMappingsToDoubleTask<K,V>
3728 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3729 >             null, transformer, basis, reducer).invoke();
3730      }
3731  
3732      /**
# Line 3802 | Line 3734 | public class ConcurrentHashMap<K, V>
3734       * of all (key, value) pairs using the given reducer to
3735       * combine values, and the given basis as an identity value.
3736       *
3737 +     * @param parallelismThreshold the (estimated) number of elements
3738 +     * needed for this operation to be executed in parallel
3739       * @param transformer a function returning the transformation
3740       * for an element
3741       * @param basis the identity (initial default value) for the reduction
3742       * @param reducer a commutative associative combining function
3743       * @return the result of accumulating the given transformation
3744       * of all (key, value) pairs
3745 +     * @since 1.8
3746       */
3747 <    public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
3747 >    public long reduceToLong(long parallelismThreshold,
3748 >                             ToLongBiFunction<? super K, ? super V> transformer,
3749                               long basis,
3750 <                             LongByLongToLong reducer) {
3751 <        return ForkJoinTasks.reduceToLong
3752 <            (this, transformer, basis, reducer).invoke();
3750 >                             LongBinaryOperator reducer) {
3751 >        if (transformer == null || reducer == null)
3752 >            throw new NullPointerException();
3753 >        return new MapReduceMappingsToLongTask<K,V>
3754 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3755 >             null, transformer, basis, reducer).invoke();
3756      }
3757  
3758      /**
# Line 3821 | Line 3760 | public class ConcurrentHashMap<K, V>
3760       * of all (key, value) pairs using the given reducer to
3761       * combine values, and the given basis as an identity value.
3762       *
3763 +     * @param parallelismThreshold the (estimated) number of elements
3764 +     * needed for this operation to be executed in parallel
3765       * @param transformer a function returning the transformation
3766       * for an element
3767       * @param basis the identity (initial default value) for the reduction
3768       * @param reducer a commutative associative combining function
3769       * @return the result of accumulating the given transformation
3770       * of all (key, value) pairs
3771 +     * @since 1.8
3772       */
3773 <    public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
3773 >    public int reduceToInt(long parallelismThreshold,
3774 >                           ToIntBiFunction<? super K, ? super V> transformer,
3775                             int basis,
3776 <                           IntByIntToInt reducer) {
3777 <        return ForkJoinTasks.reduceToInt
3778 <            (this, transformer, basis, reducer).invoke();
3776 >                           IntBinaryOperator reducer) {
3777 >        if (transformer == null || reducer == null)
3778 >            throw new NullPointerException();
3779 >        return new MapReduceMappingsToIntTask<K,V>
3780 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3781 >             null, transformer, basis, reducer).invoke();
3782      }
3783  
3784      /**
3785       * Performs the given action for each key.
3786       *
3787 +     * @param parallelismThreshold the (estimated) number of elements
3788 +     * needed for this operation to be executed in parallel
3789       * @param action the action
3790 +     * @since 1.8
3791       */
3792 <    public void forEachKey(Action<K> action) {
3793 <        ForkJoinTasks.forEachKey
3794 <            (this, action).invoke();
3792 >    public void forEachKey(long parallelismThreshold,
3793 >                           Consumer<? super K> action) {
3794 >        if (action == null) throw new NullPointerException();
3795 >        new ForEachKeyTask<K,V>
3796 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3797 >             action).invoke();
3798      }
3799  
3800      /**
3801       * Performs the given action for each non-null transformation
3802       * of each key.
3803       *
3804 +     * @param parallelismThreshold the (estimated) number of elements
3805 +     * needed for this operation to be executed in parallel
3806       * @param transformer a function returning the transformation
3807 <     * for an element, or null of there is no transformation (in
3808 <     * which case the action is not applied).
3807 >     * for an element, or null if there is no transformation (in
3808 >     * which case the action is not applied)
3809       * @param action the action
3810 +     * @param <U> the return type of the transformer
3811 +     * @since 1.8
3812       */
3813 <    public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
3814 <                               Action<U> action) {
3815 <        ForkJoinTasks.forEachKey
3816 <            (this, transformer, action).invoke();
3813 >    public <U> void forEachKey(long parallelismThreshold,
3814 >                               Function<? super K, ? extends U> transformer,
3815 >                               Consumer<? super U> action) {
3816 >        if (transformer == null || action == null)
3817 >            throw new NullPointerException();
3818 >        new ForEachTransformedKeyTask<K,V,U>
3819 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3820 >             transformer, action).invoke();
3821      }
3822  
3823      /**
# Line 3867 | Line 3827 | public class ConcurrentHashMap<K, V>
3827       * any other parallel invocations of the search function are
3828       * ignored.
3829       *
3830 +     * @param parallelismThreshold the (estimated) number of elements
3831 +     * needed for this operation to be executed in parallel
3832       * @param searchFunction a function returning a non-null
3833       * result on success, else null
3834 +     * @param <U> the return type of the search function
3835       * @return a non-null result from applying the given search
3836       * function on each key, or null if none
3837 +     * @since 1.8
3838       */
3839 <    public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
3840 <        return ForkJoinTasks.searchKeys
3841 <            (this, searchFunction).invoke();
3839 >    public <U> U searchKeys(long parallelismThreshold,
3840 >                            Function<? super K, ? extends U> searchFunction) {
3841 >        if (searchFunction == null) throw new NullPointerException();
3842 >        return new SearchKeysTask<K,V,U>
3843 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3844 >             searchFunction, new AtomicReference<U>()).invoke();
3845      }
3846  
3847      /**
3848       * Returns the result of accumulating all keys using the given
3849       * reducer to combine values, or null if none.
3850       *
3851 +     * @param parallelismThreshold the (estimated) number of elements
3852 +     * needed for this operation to be executed in parallel
3853       * @param reducer a commutative associative combining function
3854       * @return the result of accumulating all keys using the given
3855       * reducer to combine values, or null if none
3856 +     * @since 1.8
3857       */
3858 <    public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
3859 <        return ForkJoinTasks.reduceKeys
3860 <            (this, reducer).invoke();
3858 >    public K reduceKeys(long parallelismThreshold,
3859 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3860 >        if (reducer == null) throw new NullPointerException();
3861 >        return new ReduceKeysTask<K,V>
3862 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3863 >             null, reducer).invoke();
3864      }
3865  
3866      /**
# Line 3895 | Line 3868 | public class ConcurrentHashMap<K, V>
3868       * of all keys using the given reducer to combine values, or
3869       * null if none.
3870       *
3871 +     * @param parallelismThreshold the (estimated) number of elements
3872 +     * needed for this operation to be executed in parallel
3873       * @param transformer a function returning the transformation
3874 <     * for an element, or null of there is no transformation (in
3875 <     * which case it is not combined).
3874 >     * for an element, or null if there is no transformation (in
3875 >     * which case it is not combined)
3876       * @param reducer a commutative associative combining function
3877 +     * @param <U> the return type of the transformer
3878       * @return the result of accumulating the given transformation
3879       * of all keys
3880 +     * @since 1.8
3881       */
3882 <    public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
3883 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
3884 <        return ForkJoinTasks.reduceKeys
3885 <            (this, transformer, reducer).invoke();
3882 >    public <U> U reduceKeys(long parallelismThreshold,
3883 >                            Function<? super K, ? extends U> transformer,
3884 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3885 >        if (transformer == null || reducer == null)
3886 >            throw new NullPointerException();
3887 >        return new MapReduceKeysTask<K,V,U>
3888 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3889 >             null, transformer, reducer).invoke();
3890      }
3891  
3892      /**
# Line 3913 | Line 3894 | public class ConcurrentHashMap<K, V>
3894       * of all keys using the given reducer to combine values, and
3895       * the given basis as an identity value.
3896       *
3897 +     * @param parallelismThreshold the (estimated) number of elements
3898 +     * needed for this operation to be executed in parallel
3899       * @param transformer a function returning the transformation
3900       * for an element
3901       * @param basis the identity (initial default value) for the reduction
3902       * @param reducer a commutative associative combining function
3903 <     * @return  the result of accumulating the given transformation
3903 >     * @return the result of accumulating the given transformation
3904       * of all keys
3905 +     * @since 1.8
3906       */
3907 <    public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
3907 >    public double reduceKeysToDouble(long parallelismThreshold,
3908 >                                     ToDoubleFunction<? super K> transformer,
3909                                       double basis,
3910 <                                     DoubleByDoubleToDouble reducer) {
3911 <        return ForkJoinTasks.reduceKeysToDouble
3912 <            (this, transformer, basis, reducer).invoke();
3910 >                                     DoubleBinaryOperator reducer) {
3911 >        if (transformer == null || reducer == null)
3912 >            throw new NullPointerException();
3913 >        return new MapReduceKeysToDoubleTask<K,V>
3914 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3915 >             null, transformer, basis, reducer).invoke();
3916      }
3917  
3918      /**
# Line 3932 | Line 3920 | public class ConcurrentHashMap<K, V>
3920       * of all keys using the given reducer to combine values, and
3921       * the given basis as an identity value.
3922       *
3923 +     * @param parallelismThreshold the (estimated) number of elements
3924 +     * needed for this operation to be executed in parallel
3925       * @param transformer a function returning the transformation
3926       * for an element
3927       * @param basis the identity (initial default value) for the reduction
3928       * @param reducer a commutative associative combining function
3929       * @return the result of accumulating the given transformation
3930       * of all keys
3931 +     * @since 1.8
3932       */
3933 <    public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3933 >    public long reduceKeysToLong(long parallelismThreshold,
3934 >                                 ToLongFunction<? super K> transformer,
3935                                   long basis,
3936 <                                 LongByLongToLong reducer) {
3937 <        return ForkJoinTasks.reduceKeysToLong
3938 <            (this, transformer, basis, reducer).invoke();
3936 >                                 LongBinaryOperator reducer) {
3937 >        if (transformer == null || reducer == null)
3938 >            throw new NullPointerException();
3939 >        return new MapReduceKeysToLongTask<K,V>
3940 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3941 >             null, transformer, basis, reducer).invoke();
3942      }
3943  
3944      /**
# Line 3951 | Line 3946 | public class ConcurrentHashMap<K, V>
3946       * of all keys using the given reducer to combine values, and
3947       * the given basis as an identity value.
3948       *
3949 +     * @param parallelismThreshold the (estimated) number of elements
3950 +     * needed for this operation to be executed in parallel
3951       * @param transformer a function returning the transformation
3952       * for an element
3953       * @param basis the identity (initial default value) for the reduction
3954       * @param reducer a commutative associative combining function
3955       * @return the result of accumulating the given transformation
3956       * of all keys
3957 +     * @since 1.8
3958       */
3959 <    public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3959 >    public int reduceKeysToInt(long parallelismThreshold,
3960 >                               ToIntFunction<? super K> transformer,
3961                                 int basis,
3962 <                               IntByIntToInt reducer) {
3963 <        return ForkJoinTasks.reduceKeysToInt
3964 <            (this, transformer, basis, reducer).invoke();
3962 >                               IntBinaryOperator reducer) {
3963 >        if (transformer == null || reducer == null)
3964 >            throw new NullPointerException();
3965 >        return new MapReduceKeysToIntTask<K,V>
3966 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3967 >             null, transformer, basis, reducer).invoke();
3968      }
3969  
3970      /**
3971       * Performs the given action for each value.
3972       *
3973 +     * @param parallelismThreshold the (estimated) number of elements
3974 +     * needed for this operation to be executed in parallel
3975       * @param action the action
3976 +     * @since 1.8
3977       */
3978 <    public void forEachValue(Action<V> action) {
3979 <        ForkJoinTasks.forEachValue
3980 <            (this, action).invoke();
3978 >    public void forEachValue(long parallelismThreshold,
3979 >                             Consumer<? super V> action) {
3980 >        if (action == null)
3981 >            throw new NullPointerException();
3982 >        new ForEachValueTask<K,V>
3983 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3984 >             action).invoke();
3985      }
3986  
3987      /**
3988       * Performs the given action for each non-null transformation
3989       * of each value.
3990       *
3991 +     * @param parallelismThreshold the (estimated) number of elements
3992 +     * needed for this operation to be executed in parallel
3993       * @param transformer a function returning the transformation
3994 <     * for an element, or null of there is no transformation (in
3995 <     * which case the action is not applied).
3994 >     * for an element, or null if there is no transformation (in
3995 >     * which case the action is not applied)
3996 >     * @param action the action
3997 >     * @param <U> the return type of the transformer
3998 >     * @since 1.8
3999       */
4000 <    public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
4001 <                                 Action<U> action) {
4002 <        ForkJoinTasks.forEachValue
4003 <            (this, transformer, action).invoke();
4000 >    public <U> void forEachValue(long parallelismThreshold,
4001 >                                 Function<? super V, ? extends U> transformer,
4002 >                                 Consumer<? super U> action) {
4003 >        if (transformer == null || action == null)
4004 >            throw new NullPointerException();
4005 >        new ForEachTransformedValueTask<K,V,U>
4006 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4007 >             transformer, action).invoke();
4008      }
4009  
4010      /**
# Line 3996 | Line 4014 | public class ConcurrentHashMap<K, V>
4014       * any other parallel invocations of the search function are
4015       * ignored.
4016       *
4017 +     * @param parallelismThreshold the (estimated) number of elements
4018 +     * needed for this operation to be executed in parallel
4019       * @param searchFunction a function returning a non-null
4020       * result on success, else null
4021 +     * @param <U> the return type of the search function
4022       * @return a non-null result from applying the given search
4023       * function on each value, or null if none
4024 <     *
4024 >     * @since 1.8
4025       */
4026 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
4027 <        return ForkJoinTasks.searchValues
4028 <            (this, searchFunction).invoke();
4026 >    public <U> U searchValues(long parallelismThreshold,
4027 >                              Function<? super V, ? extends U> searchFunction) {
4028 >        if (searchFunction == null) throw new NullPointerException();
4029 >        return new SearchValuesTask<K,V,U>
4030 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4031 >             searchFunction, new AtomicReference<U>()).invoke();
4032      }
4033  
4034      /**
4035       * Returns the result of accumulating all values using the
4036       * given reducer to combine values, or null if none.
4037       *
4038 +     * @param parallelismThreshold the (estimated) number of elements
4039 +     * needed for this operation to be executed in parallel
4040       * @param reducer a commutative associative combining function
4041 <     * @return  the result of accumulating all values
4041 >     * @return the result of accumulating all values
4042 >     * @since 1.8
4043       */
4044 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
4045 <        return ForkJoinTasks.reduceValues
4046 <            (this, reducer).invoke();
4044 >    public V reduceValues(long parallelismThreshold,
4045 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
4046 >        if (reducer == null) throw new NullPointerException();
4047 >        return new ReduceValuesTask<K,V>
4048 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4049 >             null, reducer).invoke();
4050      }
4051  
4052      /**
# Line 4024 | Line 4054 | public class ConcurrentHashMap<K, V>
4054       * of all values using the given reducer to combine values, or
4055       * null if none.
4056       *
4057 +     * @param parallelismThreshold the (estimated) number of elements
4058 +     * needed for this operation to be executed in parallel
4059       * @param transformer a function returning the transformation
4060 <     * for an element, or null of there is no transformation (in
4061 <     * which case it is not combined).
4060 >     * for an element, or null if there is no transformation (in
4061 >     * which case it is not combined)
4062       * @param reducer a commutative associative combining function
4063 +     * @param <U> the return type of the transformer
4064       * @return the result of accumulating the given transformation
4065       * of all values
4066 +     * @since 1.8
4067       */
4068 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
4069 <                              BiFun<? super U, ? super U, ? extends U> reducer) {
4070 <        return ForkJoinTasks.reduceValues
4071 <            (this, transformer, reducer).invoke();
4068 >    public <U> U reduceValues(long parallelismThreshold,
4069 >                              Function<? super V, ? extends U> transformer,
4070 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
4071 >        if (transformer == null || reducer == null)
4072 >            throw new NullPointerException();
4073 >        return new MapReduceValuesTask<K,V,U>
4074 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4075 >             null, transformer, reducer).invoke();
4076      }
4077  
4078      /**
# Line 4042 | Line 4080 | public class ConcurrentHashMap<K, V>
4080       * of all values using the given reducer to combine values,
4081       * and the given basis as an identity value.
4082       *
4083 +     * @param parallelismThreshold the (estimated) number of elements
4084 +     * needed for this operation to be executed in parallel
4085       * @param transformer a function returning the transformation
4086       * for an element
4087       * @param basis the identity (initial default value) for the reduction
4088       * @param reducer a commutative associative combining function
4089       * @return the result of accumulating the given transformation
4090       * of all values
4091 +     * @since 1.8
4092       */
4093 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
4093 >    public double reduceValuesToDouble(long parallelismThreshold,
4094 >                                       ToDoubleFunction<? super V> transformer,
4095                                         double basis,
4096 <                                       DoubleByDoubleToDouble reducer) {
4097 <        return ForkJoinTasks.reduceValuesToDouble
4098 <            (this, transformer, basis, reducer).invoke();
4096 >                                       DoubleBinaryOperator reducer) {
4097 >        if (transformer == null || reducer == null)
4098 >            throw new NullPointerException();
4099 >        return new MapReduceValuesToDoubleTask<K,V>
4100 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4101 >             null, transformer, basis, reducer).invoke();
4102      }
4103  
4104      /**
# Line 4061 | Line 4106 | public class ConcurrentHashMap<K, V>
4106       * of all values using the given reducer to combine values,
4107       * and the given basis as an identity value.
4108       *
4109 +     * @param parallelismThreshold the (estimated) number of elements
4110 +     * needed for this operation to be executed in parallel
4111       * @param transformer a function returning the transformation
4112       * for an element
4113       * @param basis the identity (initial default value) for the reduction
4114       * @param reducer a commutative associative combining function
4115       * @return the result of accumulating the given transformation
4116       * of all values
4117 +     * @since 1.8
4118       */
4119 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
4119 >    public long reduceValuesToLong(long parallelismThreshold,
4120 >                                   ToLongFunction<? super V> transformer,
4121                                     long basis,
4122 <                                   LongByLongToLong reducer) {
4123 <        return ForkJoinTasks.reduceValuesToLong
4124 <            (this, transformer, basis, reducer).invoke();
4122 >                                   LongBinaryOperator reducer) {
4123 >        if (transformer == null || reducer == null)
4124 >            throw new NullPointerException();
4125 >        return new MapReduceValuesToLongTask<K,V>
4126 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4127 >             null, transformer, basis, reducer).invoke();
4128      }
4129  
4130      /**
# Line 4080 | Line 4132 | public class ConcurrentHashMap<K, V>
4132       * of all values using the given reducer to combine values,
4133       * and the given basis as an identity value.
4134       *
4135 +     * @param parallelismThreshold the (estimated) number of elements
4136 +     * needed for this operation to be executed in parallel
4137       * @param transformer a function returning the transformation
4138       * for an element
4139       * @param basis the identity (initial default value) for the reduction
4140       * @param reducer a commutative associative combining function
4141       * @return the result of accumulating the given transformation
4142       * of all values
4143 +     * @since 1.8
4144       */
4145 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4145 >    public int reduceValuesToInt(long parallelismThreshold,
4146 >                                 ToIntFunction<? super V> transformer,
4147                                   int basis,
4148 <                                 IntByIntToInt reducer) {
4149 <        return ForkJoinTasks.reduceValuesToInt
4150 <            (this, transformer, basis, reducer).invoke();
4148 >                                 IntBinaryOperator reducer) {
4149 >        if (transformer == null || reducer == null)
4150 >            throw new NullPointerException();
4151 >        return new MapReduceValuesToIntTask<K,V>
4152 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4153 >             null, transformer, basis, reducer).invoke();
4154      }
4155  
4156      /**
4157       * Performs the given action for each entry.
4158       *
4159 +     * @param parallelismThreshold the (estimated) number of elements
4160 +     * needed for this operation to be executed in parallel
4161       * @param action the action
4162 +     * @since 1.8
4163       */
4164 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
4165 <        ForkJoinTasks.forEachEntry
4166 <            (this, action).invoke();
4164 >    public void forEachEntry(long parallelismThreshold,
4165 >                             Consumer<? super Map.Entry<K,V>> action) {
4166 >        if (action == null) throw new NullPointerException();
4167 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4168 >                                  action).invoke();
4169      }
4170  
4171      /**
4172       * Performs the given action for each non-null transformation
4173       * of each entry.
4174       *
4175 +     * @param parallelismThreshold the (estimated) number of elements
4176 +     * needed for this operation to be executed in parallel
4177       * @param transformer a function returning the transformation
4178 <     * for an element, or null of there is no transformation (in
4179 <     * which case the action is not applied).
4178 >     * for an element, or null if there is no transformation (in
4179 >     * which case the action is not applied)
4180       * @param action the action
4181 +     * @param <U> the return type of the transformer
4182 +     * @since 1.8
4183       */
4184 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4185 <                                 Action<U> action) {
4186 <        ForkJoinTasks.forEachEntry
4187 <            (this, transformer, action).invoke();
4184 >    public <U> void forEachEntry(long parallelismThreshold,
4185 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
4186 >                                 Consumer<? super U> action) {
4187 >        if (transformer == null || action == null)
4188 >            throw new NullPointerException();
4189 >        new ForEachTransformedEntryTask<K,V,U>
4190 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4191 >             transformer, action).invoke();
4192      }
4193  
4194      /**
# Line 4126 | Line 4198 | public class ConcurrentHashMap<K, V>
4198       * any other parallel invocations of the search function are
4199       * ignored.
4200       *
4201 +     * @param parallelismThreshold the (estimated) number of elements
4202 +     * needed for this operation to be executed in parallel
4203       * @param searchFunction a function returning a non-null
4204       * result on success, else null
4205 +     * @param <U> the return type of the search function
4206       * @return a non-null result from applying the given search
4207       * function on each entry, or null if none
4208 +     * @since 1.8
4209       */
4210 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4211 <        return ForkJoinTasks.searchEntries
4212 <            (this, searchFunction).invoke();
4210 >    public <U> U searchEntries(long parallelismThreshold,
4211 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4212 >        if (searchFunction == null) throw new NullPointerException();
4213 >        return new SearchEntriesTask<K,V,U>
4214 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4215 >             searchFunction, new AtomicReference<U>()).invoke();
4216      }
4217  
4218      /**
4219       * Returns the result of accumulating all entries using the
4220       * given reducer to combine values, or null if none.
4221       *
4222 +     * @param parallelismThreshold the (estimated) number of elements
4223 +     * needed for this operation to be executed in parallel
4224       * @param reducer a commutative associative combining function
4225       * @return the result of accumulating all entries
4226 +     * @since 1.8
4227       */
4228 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4229 <        return ForkJoinTasks.reduceEntries
4230 <            (this, reducer).invoke();
4228 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4229 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4230 >        if (reducer == null) throw new NullPointerException();
4231 >        return new ReduceEntriesTask<K,V>
4232 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4233 >             null, reducer).invoke();
4234      }
4235  
4236      /**
# Line 4153 | Line 4238 | public class ConcurrentHashMap<K, V>
4238       * of all entries using the given reducer to combine values,
4239       * or null if none.
4240       *
4241 +     * @param parallelismThreshold the (estimated) number of elements
4242 +     * needed for this operation to be executed in parallel
4243       * @param transformer a function returning the transformation
4244 <     * for an element, or null of there is no transformation (in
4245 <     * which case it is not combined).
4244 >     * for an element, or null if there is no transformation (in
4245 >     * which case it is not combined)
4246       * @param reducer a commutative associative combining function
4247 +     * @param <U> the return type of the transformer
4248       * @return the result of accumulating the given transformation
4249       * of all entries
4250 +     * @since 1.8
4251       */
4252 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4253 <                               BiFun<? super U, ? super U, ? extends U> reducer) {
4254 <        return ForkJoinTasks.reduceEntries
4255 <            (this, transformer, reducer).invoke();
4252 >    public <U> U reduceEntries(long parallelismThreshold,
4253 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
4254 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
4255 >        if (transformer == null || reducer == null)
4256 >            throw new NullPointerException();
4257 >        return new MapReduceEntriesTask<K,V,U>
4258 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4259 >             null, transformer, reducer).invoke();
4260      }
4261  
4262      /**
# Line 4171 | Line 4264 | public class ConcurrentHashMap<K, V>
4264       * of all entries using the given reducer to combine values,
4265       * and the given basis as an identity value.
4266       *
4267 +     * @param parallelismThreshold the (estimated) number of elements
4268 +     * needed for this operation to be executed in parallel
4269       * @param transformer a function returning the transformation
4270       * for an element
4271       * @param basis the identity (initial default value) for the reduction
4272       * @param reducer a commutative associative combining function
4273       * @return the result of accumulating the given transformation
4274       * of all entries
4275 +     * @since 1.8
4276       */
4277 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4277 >    public double reduceEntriesToDouble(long parallelismThreshold,
4278 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
4279                                          double basis,
4280 <                                        DoubleByDoubleToDouble reducer) {
4281 <        return ForkJoinTasks.reduceEntriesToDouble
4282 <            (this, transformer, basis, reducer).invoke();
4280 >                                        DoubleBinaryOperator reducer) {
4281 >        if (transformer == null || reducer == null)
4282 >            throw new NullPointerException();
4283 >        return new MapReduceEntriesToDoubleTask<K,V>
4284 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4285 >             null, transformer, basis, reducer).invoke();
4286      }
4287  
4288      /**
# Line 4190 | Line 4290 | public class ConcurrentHashMap<K, V>
4290       * of all entries using the given reducer to combine values,
4291       * and the given basis as an identity value.
4292       *
4293 +     * @param parallelismThreshold the (estimated) number of elements
4294 +     * needed for this operation to be executed in parallel
4295       * @param transformer a function returning the transformation
4296       * for an element
4297       * @param basis the identity (initial default value) for the reduction
4298       * @param reducer a commutative associative combining function
4299 <     * @return  the result of accumulating the given transformation
4299 >     * @return the result of accumulating the given transformation
4300       * of all entries
4301 +     * @since 1.8
4302       */
4303 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4303 >    public long reduceEntriesToLong(long parallelismThreshold,
4304 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
4305                                      long basis,
4306 <                                    LongByLongToLong reducer) {
4307 <        return ForkJoinTasks.reduceEntriesToLong
4308 <            (this, transformer, basis, reducer).invoke();
4306 >                                    LongBinaryOperator reducer) {
4307 >        if (transformer == null || reducer == null)
4308 >            throw new NullPointerException();
4309 >        return new MapReduceEntriesToLongTask<K,V>
4310 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4311 >             null, transformer, basis, reducer).invoke();
4312      }
4313  
4314      /**
# Line 4209 | Line 4316 | public class ConcurrentHashMap<K, V>
4316       * of all entries using the given reducer to combine values,
4317       * and the given basis as an identity value.
4318       *
4319 +     * @param parallelismThreshold the (estimated) number of elements
4320 +     * needed for this operation to be executed in parallel
4321       * @param transformer a function returning the transformation
4322       * for an element
4323       * @param basis the identity (initial default value) for the reduction
4324       * @param reducer a commutative associative combining function
4325       * @return the result of accumulating the given transformation
4326       * of all entries
4327 +     * @since 1.8
4328       */
4329 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4329 >    public int reduceEntriesToInt(long parallelismThreshold,
4330 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
4331                                    int basis,
4332 <                                  IntByIntToInt reducer) {
4333 <        return ForkJoinTasks.reduceEntriesToInt
4334 <            (this, transformer, basis, reducer).invoke();
4332 >                                  IntBinaryOperator reducer) {
4333 >        if (transformer == null || reducer == null)
4334 >            throw new NullPointerException();
4335 >        return new MapReduceEntriesToIntTask<K,V>
4336 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4337 >             null, transformer, basis, reducer).invoke();
4338      }
4339  
4340 <    // ---------------------------------------------------------------------
4340 >
4341 >    /* ----------------Views -------------- */
4342  
4343      /**
4344 <     * Predefined tasks for performing bulk parallel operations on
4230 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
4231 <     * for bulk operations. Each method has the same name, but returns
4232 <     * a task rather than invoking it. These methods may be useful in
4233 <     * custom applications such as submitting a task without waiting
4234 <     * for completion, using a custom pool, or combining with other
4235 <     * tasks.
4344 >     * Base class for views.
4345       */
4346 <    public static class ForkJoinTasks {
4347 <        private ForkJoinTasks() {}
4348 <
4349 <        /**
4350 <         * Returns a task that when invoked, performs the given
4242 <         * action for each (key, value)
4243 <         *
4244 <         * @param map the map
4245 <         * @param action the action
4246 <         * @return the task
4247 <         */
4248 <        public static <K,V> ForkJoinTask<Void> forEach
4249 <            (ConcurrentHashMap<K,V> map,
4250 <             BiAction<K,V> action) {
4251 <            if (action == null) throw new NullPointerException();
4252 <            return new ForEachMappingTask<K,V>(map, null, -1, null, action);
4253 <        }
4346 >    abstract static class CollectionView<K,V,E>
4347 >        implements Collection<E>, java.io.Serializable {
4348 >        private static final long serialVersionUID = 7249069246763182397L;
4349 >        final ConcurrentHashMap<K,V> map;
4350 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4351  
4352          /**
4353 <         * Returns a task that when invoked, performs the given
4257 <         * action for each non-null transformation of each (key, value)
4353 >         * Returns the map backing this view.
4354           *
4355 <         * @param map the map
4260 <         * @param transformer a function returning the transformation
4261 <         * for an element, or null if there is no transformation (in
4262 <         * which case the action is not applied)
4263 <         * @param action the action
4264 <         * @return the task
4355 >         * @return the map backing this view
4356           */
4357 <        public static <K,V,U> ForkJoinTask<Void> forEach
4267 <            (ConcurrentHashMap<K,V> map,
4268 <             BiFun<? super K, ? super V, ? extends U> transformer,
4269 <             Action<U> action) {
4270 <            if (transformer == null || action == null)
4271 <                throw new NullPointerException();
4272 <            return new ForEachTransformedMappingTask<K,V,U>
4273 <                (map, null, -1, null, transformer, action);
4274 <        }
4357 >        public ConcurrentHashMap<K,V> getMap() { return map; }
4358  
4359          /**
4360 <         * Returns a task that when invoked, returns a non-null result
4361 <         * from applying the given search function on each (key,
4279 <         * value), or null if none. Upon success, further element
4280 <         * processing is suppressed and the results of any other
4281 <         * parallel invocations of the search function are ignored.
4282 <         *
4283 <         * @param map the map
4284 <         * @param searchFunction a function returning a non-null
4285 <         * result on success, else null
4286 <         * @return the task
4360 >         * Removes all of the elements from this view, by removing all
4361 >         * the mappings from the map backing this view.
4362           */
4363 <        public static <K,V,U> ForkJoinTask<U> search
4364 <            (ConcurrentHashMap<K,V> map,
4365 <             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4291 <            if (searchFunction == null) throw new NullPointerException();
4292 <            return new SearchMappingsTask<K,V,U>
4293 <                (map, null, -1, null, searchFunction,
4294 <                 new AtomicReference<U>());
4295 <        }
4363 >        public final void clear()      { map.clear(); }
4364 >        public final int size()        { return map.size(); }
4365 >        public final boolean isEmpty() { return map.isEmpty(); }
4366  
4367 +        // implementations below rely on concrete classes supplying these
4368 +        // abstract methods
4369          /**
4370 <         * Returns a task that when invoked, returns the result of
4299 <         * accumulating the given transformation of all (key, value) pairs
4300 <         * using the given reducer to combine values, or null if none.
4370 >         * Returns an iterator over the elements in this collection.
4371           *
4372 <         * @param map the map
4373 <         * @param transformer a function returning the transformation
4304 <         * for an element, or null if there is no transformation (in
4305 <         * which case it is not combined).
4306 <         * @param reducer a commutative associative combining function
4307 <         * @return the task
4308 <         */
4309 <        public static <K,V,U> ForkJoinTask<U> reduce
4310 <            (ConcurrentHashMap<K,V> map,
4311 <             BiFun<? super K, ? super V, ? extends U> transformer,
4312 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4313 <            if (transformer == null || reducer == null)
4314 <                throw new NullPointerException();
4315 <            return new MapReduceMappingsTask<K,V,U>
4316 <                (map, null, -1, null, transformer, reducer);
4317 <        }
4318 <
4319 <        /**
4320 <         * Returns a task that when invoked, returns the result of
4321 <         * accumulating the given transformation of all (key, value) pairs
4322 <         * using the given reducer to combine values, and the given
4323 <         * basis as an identity value.
4372 >         * <p>The returned iterator is
4373 >         * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
4374           *
4375 <         * @param map the map
4326 <         * @param transformer a function returning the transformation
4327 <         * for an element
4328 <         * @param basis the identity (initial default value) for the reduction
4329 <         * @param reducer a commutative associative combining function
4330 <         * @return the task
4375 >         * @return an iterator over the elements in this collection
4376           */
4377 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4378 <            (ConcurrentHashMap<K,V> map,
4379 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
4335 <             double basis,
4336 <             DoubleByDoubleToDouble reducer) {
4337 <            if (transformer == null || reducer == null)
4338 <                throw new NullPointerException();
4339 <            return new MapReduceMappingsToDoubleTask<K,V>
4340 <                (map, null, -1, null, transformer, basis, reducer);
4341 <        }
4377 >        public abstract Iterator<E> iterator();
4378 >        public abstract boolean contains(Object o);
4379 >        public abstract boolean remove(Object o);
4380  
4381 <        /**
4344 <         * Returns a task that when invoked, returns the result of
4345 <         * accumulating the given transformation of all (key, value) pairs
4346 <         * using the given reducer to combine values, and the given
4347 <         * basis as an identity value.
4348 <         *
4349 <         * @param map the map
4350 <         * @param transformer a function returning the transformation
4351 <         * for an element
4352 <         * @param basis the identity (initial default value) for the reduction
4353 <         * @param reducer a commutative associative combining function
4354 <         * @return the task
4355 <         */
4356 <        public static <K,V> ForkJoinTask<Long> reduceToLong
4357 <            (ConcurrentHashMap<K,V> map,
4358 <             ObjectByObjectToLong<? super K, ? super V> transformer,
4359 <             long basis,
4360 <             LongByLongToLong reducer) {
4361 <            if (transformer == null || reducer == null)
4362 <                throw new NullPointerException();
4363 <            return new MapReduceMappingsToLongTask<K,V>
4364 <                (map, null, -1, null, transformer, basis, reducer);
4365 <        }
4381 >        private static final String oomeMsg = "Required array size too large";
4382  
4383 <        /**
4384 <         * Returns a task that when invoked, returns the result of
4385 <         * accumulating the given transformation of all (key, value) pairs
4386 <         * using the given reducer to combine values, and the given
4387 <         * basis as an identity value.
4388 <         *
4389 <         * @param transformer a function returning the transformation
4390 <         * for an element
4391 <         * @param basis the identity (initial default value) for the reduction
4392 <         * @param reducer a commutative associative combining function
4393 <         * @return the task
4394 <         */
4395 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
4396 <            (ConcurrentHashMap<K,V> map,
4397 <             ObjectByObjectToInt<? super K, ? super V> transformer,
4398 <             int basis,
4399 <             IntByIntToInt reducer) {
4400 <            if (transformer == null || reducer == null)
4401 <                throw new NullPointerException();
4402 <            return new MapReduceMappingsToIntTask<K,V>
4387 <                (map, null, -1, null, transformer, basis, reducer);
4383 >        public final Object[] toArray() {
4384 >            long sz = map.mappingCount();
4385 >            if (sz > MAX_ARRAY_SIZE)
4386 >                throw new OutOfMemoryError(oomeMsg);
4387 >            int n = (int)sz;
4388 >            Object[] r = new Object[n];
4389 >            int i = 0;
4390 >            for (E e : this) {
4391 >                if (i == n) {
4392 >                    if (n >= MAX_ARRAY_SIZE)
4393 >                        throw new OutOfMemoryError(oomeMsg);
4394 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4395 >                        n = MAX_ARRAY_SIZE;
4396 >                    else
4397 >                        n += (n >>> 1) + 1;
4398 >                    r = Arrays.copyOf(r, n);
4399 >                }
4400 >                r[i++] = e;
4401 >            }
4402 >            return (i == n) ? r : Arrays.copyOf(r, i);
4403          }
4404  
4405 <        /**
4406 <         * Returns a task that when invoked, performs the given action
4407 <         * for each key.
4408 <         *
4409 <         * @param map the map
4410 <         * @param action the action
4411 <         * @return the task
4412 <         */
4413 <        public static <K,V> ForkJoinTask<Void> forEachKey
4414 <            (ConcurrentHashMap<K,V> map,
4415 <             Action<K> action) {
4416 <            if (action == null) throw new NullPointerException();
4417 <            return new ForEachKeyTask<K,V>(map, null, -1, null, action);
4405 >        @SuppressWarnings("unchecked")
4406 >        public final <T> T[] toArray(T[] a) {
4407 >            long sz = map.mappingCount();
4408 >            if (sz > MAX_ARRAY_SIZE)
4409 >                throw new OutOfMemoryError(oomeMsg);
4410 >            int m = (int)sz;
4411 >            T[] r = (a.length >= m) ? a :
4412 >                (T[])java.lang.reflect.Array
4413 >                .newInstance(a.getClass().getComponentType(), m);
4414 >            int n = r.length;
4415 >            int i = 0;
4416 >            for (E e : this) {
4417 >                if (i == n) {
4418 >                    if (n >= MAX_ARRAY_SIZE)
4419 >                        throw new OutOfMemoryError(oomeMsg);
4420 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4421 >                        n = MAX_ARRAY_SIZE;
4422 >                    else
4423 >                        n += (n >>> 1) + 1;
4424 >                    r = Arrays.copyOf(r, n);
4425 >                }
4426 >                r[i++] = (T)e;
4427 >            }
4428 >            if (a == r && i < n) {
4429 >                r[i] = null; // null-terminate
4430 >                return r;
4431 >            }
4432 >            return (i == n) ? r : Arrays.copyOf(r, i);
4433          }
4434  
4435          /**
4436 <         * Returns a task that when invoked, performs the given action
4437 <         * for each non-null transformation of each key.
4436 >         * Returns a string representation of this collection.
4437 >         * The string representation consists of the string representations
4438 >         * of the collection's elements in the order they are returned by
4439 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4440 >         * Adjacent elements are separated by the characters {@code ", "}
4441 >         * (comma and space).  Elements are converted to strings as by
4442 >         * {@link String#valueOf(Object)}.
4443           *
4444 <         * @param map the map
4410 <         * @param transformer a function returning the transformation
4411 <         * for an element, or null if there is no transformation (in
4412 <         * which case the action is not applied)
4413 <         * @param action the action
4414 <         * @return the task
4444 >         * @return a string representation of this collection
4445           */
4446 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
4447 <            (ConcurrentHashMap<K,V> map,
4448 <             Fun<? super K, ? extends U> transformer,
4449 <             Action<U> action) {
4450 <            if (transformer == null || action == null)
4451 <                throw new NullPointerException();
4452 <            return new ForEachTransformedKeyTask<K,V,U>
4453 <                (map, null, -1, null, transformer, action);
4446 >        public final String toString() {
4447 >            StringBuilder sb = new StringBuilder();
4448 >            sb.append('[');
4449 >            Iterator<E> it = iterator();
4450 >            if (it.hasNext()) {
4451 >                for (;;) {
4452 >                    Object e = it.next();
4453 >                    sb.append(e == this ? "(this Collection)" : e);
4454 >                    if (!it.hasNext())
4455 >                        break;
4456 >                    sb.append(',').append(' ');
4457 >                }
4458 >            }
4459 >            return sb.append(']').toString();
4460          }
4461  
4462 <        /**
4463 <         * Returns a task that when invoked, returns a non-null result
4464 <         * from applying the given search function on each key, or
4465 <         * null if none.  Upon success, further element processing is
4466 <         * suppressed and the results of any other parallel
4467 <         * invocations of the search function are ignored.
4468 <         *
4469 <         * @param map the map
4434 <         * @param searchFunction a function returning a non-null
4435 <         * result on success, else null
4436 <         * @return the task
4437 <         */
4438 <        public static <K,V,U> ForkJoinTask<U> searchKeys
4439 <            (ConcurrentHashMap<K,V> map,
4440 <             Fun<? super K, ? extends U> searchFunction) {
4441 <            if (searchFunction == null) throw new NullPointerException();
4442 <            return new SearchKeysTask<K,V,U>
4443 <                (map, null, -1, null, searchFunction,
4444 <                 new AtomicReference<U>());
4462 >        public final boolean containsAll(Collection<?> c) {
4463 >            if (c != this) {
4464 >                for (Object e : c) {
4465 >                    if (e == null || !contains(e))
4466 >                        return false;
4467 >                }
4468 >            }
4469 >            return true;
4470          }
4471  
4472 <        /**
4473 <         * Returns a task that when invoked, returns the result of
4474 <         * accumulating all keys using the given reducer to combine
4475 <         * values, or null if none.
4476 <         *
4477 <         * @param map the map
4478 <         * @param reducer a commutative associative combining function
4479 <         * @return the task
4480 <         */
4481 <        public static <K,V> ForkJoinTask<K> reduceKeys
4457 <            (ConcurrentHashMap<K,V> map,
4458 <             BiFun<? super K, ? super K, ? extends K> reducer) {
4459 <            if (reducer == null) throw new NullPointerException();
4460 <            return new ReduceKeysTask<K,V>
4461 <                (map, null, -1, null, reducer);
4472 >        public final boolean removeAll(Collection<?> c) {
4473 >            if (c == null) throw new NullPointerException();
4474 >            boolean modified = false;
4475 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4476 >                if (c.contains(it.next())) {
4477 >                    it.remove();
4478 >                    modified = true;
4479 >                }
4480 >            }
4481 >            return modified;
4482          }
4483  
4484 <        /**
4485 <         * Returns a task that when invoked, returns the result of
4486 <         * accumulating the given transformation of all keys using the given
4487 <         * reducer to combine values, or null if none.
4488 <         *
4489 <         * @param map the map
4490 <         * @param transformer a function returning the transformation
4491 <         * for an element, or null if there is no transformation (in
4492 <         * which case it is not combined).
4493 <         * @param reducer a commutative associative combining function
4474 <         * @return the task
4475 <         */
4476 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
4477 <            (ConcurrentHashMap<K,V> map,
4478 <             Fun<? super K, ? extends U> transformer,
4479 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4480 <            if (transformer == null || reducer == null)
4481 <                throw new NullPointerException();
4482 <            return new MapReduceKeysTask<K,V,U>
4483 <                (map, null, -1, null, transformer, reducer);
4484 >        public final boolean retainAll(Collection<?> c) {
4485 >            if (c == null) throw new NullPointerException();
4486 >            boolean modified = false;
4487 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4488 >                if (!c.contains(it.next())) {
4489 >                    it.remove();
4490 >                    modified = true;
4491 >                }
4492 >            }
4493 >            return modified;
4494          }
4495  
4496 <        /**
4487 <         * Returns a task that when invoked, returns the result of
4488 <         * accumulating the given transformation of all keys using the given
4489 <         * reducer to combine values, and the given basis as an
4490 <         * identity value.
4491 <         *
4492 <         * @param map the map
4493 <         * @param transformer a function returning the transformation
4494 <         * for an element
4495 <         * @param basis the identity (initial default value) for the reduction
4496 <         * @param reducer a commutative associative combining function
4497 <         * @return the task
4498 <         */
4499 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
4500 <            (ConcurrentHashMap<K,V> map,
4501 <             ObjectToDouble<? super K> transformer,
4502 <             double basis,
4503 <             DoubleByDoubleToDouble reducer) {
4504 <            if (transformer == null || reducer == null)
4505 <                throw new NullPointerException();
4506 <            return new MapReduceKeysToDoubleTask<K,V>
4507 <                (map, null, -1, null, transformer, basis, reducer);
4508 <        }
4496 >    }
4497  
4498 <        /**
4499 <         * Returns a task that when invoked, returns the result of
4500 <         * accumulating the given transformation of all keys using the given
4501 <         * reducer to combine values, and the given basis as an
4502 <         * identity value.
4503 <         *
4504 <         * @param map the map
4505 <         * @param transformer a function returning the transformation
4506 <         * for an element
4507 <         * @param basis the identity (initial default value) for the reduction
4508 <         * @param reducer a commutative associative combining function
4509 <         * @return the task
4510 <         */
4511 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
4512 <            (ConcurrentHashMap<K,V> map,
4513 <             ObjectToLong<? super K> transformer,
4514 <             long basis,
4515 <             LongByLongToLong reducer) {
4528 <            if (transformer == null || reducer == null)
4529 <                throw new NullPointerException();
4530 <            return new MapReduceKeysToLongTask<K,V>
4531 <                (map, null, -1, null, transformer, basis, reducer);
4498 >    /**
4499 >     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4500 >     * which additions may optionally be enabled by mapping to a
4501 >     * common value.  This class cannot be directly instantiated.
4502 >     * See {@link #keySet() keySet()},
4503 >     * {@link #keySet(Object) keySet(V)},
4504 >     * {@link #newKeySet() newKeySet()},
4505 >     * {@link #newKeySet(int) newKeySet(int)}.
4506 >     *
4507 >     * @since 1.8
4508 >     */
4509 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4510 >        implements Set<K>, java.io.Serializable {
4511 >        private static final long serialVersionUID = 7249069246763182397L;
4512 >        private final V value;
4513 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4514 >            super(map);
4515 >            this.value = value;
4516          }
4517  
4518          /**
4519 <         * Returns a task that when invoked, returns the result of
4520 <         * accumulating the given transformation of all keys using the given
4537 <         * reducer to combine values, and the given basis as an
4538 <         * identity value.
4519 >         * Returns the default mapped value for additions,
4520 >         * or {@code null} if additions are not supported.
4521           *
4522 <         * @param map the map
4523 <         * @param transformer a function returning the transformation
4542 <         * for an element
4543 <         * @param basis the identity (initial default value) for the reduction
4544 <         * @param reducer a commutative associative combining function
4545 <         * @return the task
4522 >         * @return the default mapped value for additions, or {@code null}
4523 >         * if not supported
4524           */
4525 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
4548 <            (ConcurrentHashMap<K,V> map,
4549 <             ObjectToInt<? super K> transformer,
4550 <             int basis,
4551 <             IntByIntToInt reducer) {
4552 <            if (transformer == null || reducer == null)
4553 <                throw new NullPointerException();
4554 <            return new MapReduceKeysToIntTask<K,V>
4555 <                (map, null, -1, null, transformer, basis, reducer);
4556 <        }
4525 >        public V getMappedValue() { return value; }
4526  
4527          /**
4528 <         * Returns a task that when invoked, performs the given action
4529 <         * for each value.
4561 <         *
4562 <         * @param map the map
4563 <         * @param action the action
4528 >         * {@inheritDoc}
4529 >         * @throws NullPointerException if the specified key is null
4530           */
4531 <        public static <K,V> ForkJoinTask<Void> forEachValue
4566 <            (ConcurrentHashMap<K,V> map,
4567 <             Action<V> action) {
4568 <            if (action == null) throw new NullPointerException();
4569 <            return new ForEachValueTask<K,V>(map, null, -1, null, action);
4570 <        }
4531 >        public boolean contains(Object o) { return map.containsKey(o); }
4532  
4533          /**
4534 <         * Returns a task that when invoked, performs the given action
4535 <         * for each non-null transformation of each value.
4534 >         * Removes the key from this map view, by removing the key (and its
4535 >         * corresponding value) from the backing map.  This method does
4536 >         * nothing if the key is not in the map.
4537           *
4538 <         * @param map the map
4539 <         * @param transformer a function returning the transformation
4540 <         * for an element, or null if there is no transformation (in
4579 <         * which case the action is not applied)
4580 <         * @param action the action
4538 >         * @param  o the key to be removed from the backing map
4539 >         * @return {@code true} if the backing map contained the specified key
4540 >         * @throws NullPointerException if the specified key is null
4541           */
4542 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
4583 <            (ConcurrentHashMap<K,V> map,
4584 <             Fun<? super V, ? extends U> transformer,
4585 <             Action<U> action) {
4586 <            if (transformer == null || action == null)
4587 <                throw new NullPointerException();
4588 <            return new ForEachTransformedValueTask<K,V,U>
4589 <                (map, null, -1, null, transformer, action);
4590 <        }
4542 >        public boolean remove(Object o) { return map.remove(o) != null; }
4543  
4544          /**
4545 <         * Returns a task that when invoked, returns a non-null result
4594 <         * from applying the given search function on each value, or
4595 <         * null if none.  Upon success, further element processing is
4596 <         * suppressed and the results of any other parallel
4597 <         * invocations of the search function are ignored.
4598 <         *
4599 <         * @param map the map
4600 <         * @param searchFunction a function returning a non-null
4601 <         * result on success, else null
4602 <         * @return the task
4545 >         * @return an iterator over the keys of the backing map
4546           */
4547 <        public static <K,V,U> ForkJoinTask<U> searchValues
4548 <            (ConcurrentHashMap<K,V> map,
4549 <             Fun<? super V, ? extends U> searchFunction) {
4550 <            if (searchFunction == null) throw new NullPointerException();
4551 <            return new SearchValuesTask<K,V,U>
4609 <                (map, null, -1, null, searchFunction,
4610 <                 new AtomicReference<U>());
4547 >        public Iterator<K> iterator() {
4548 >            Node<K,V>[] t;
4549 >            ConcurrentHashMap<K,V> m = map;
4550 >            int f = (t = m.table) == null ? 0 : t.length;
4551 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4552          }
4553  
4554          /**
4555 <         * Returns a task that when invoked, returns the result of
4556 <         * accumulating all values using the given reducer to combine
4616 <         * values, or null if none.
4555 >         * Adds the specified key to this set view by mapping the key to
4556 >         * the default mapped value in the backing map, if defined.
4557           *
4558 <         * @param map the map
4559 <         * @param reducer a commutative associative combining function
4560 <         * @return the task
4558 >         * @param e key to be added
4559 >         * @return {@code true} if this set changed as a result of the call
4560 >         * @throws NullPointerException if the specified key is null
4561 >         * @throws UnsupportedOperationException if no default mapped value
4562 >         * for additions was provided
4563           */
4564 <        public static <K,V> ForkJoinTask<V> reduceValues
4565 <            (ConcurrentHashMap<K,V> map,
4566 <             BiFun<? super V, ? super V, ? extends V> reducer) {
4567 <            if (reducer == null) throw new NullPointerException();
4568 <            return new ReduceValuesTask<K,V>
4627 <                (map, null, -1, null, reducer);
4564 >        public boolean add(K e) {
4565 >            V v;
4566 >            if ((v = value) == null)
4567 >                throw new UnsupportedOperationException();
4568 >            return map.putVal(e, v, true) == null;
4569          }
4570  
4571          /**
4572 <         * Returns a task that when invoked, returns the result of
4573 <         * accumulating the given transformation of all values using the
4633 <         * given reducer to combine values, or null if none.
4572 >         * Adds all of the elements in the specified collection to this set,
4573 >         * as if by calling {@link #add} on each one.
4574           *
4575 <         * @param map the map
4576 <         * @param transformer a function returning the transformation
4577 <         * for an element, or null if there is no transformation (in
4578 <         * which case it is not combined).
4579 <         * @param reducer a commutative associative combining function
4580 <         * @return the task
4575 >         * @param c the elements to be inserted into this set
4576 >         * @return {@code true} if this set changed as a result of the call
4577 >         * @throws NullPointerException if the collection or any of its
4578 >         * elements are {@code null}
4579 >         * @throws UnsupportedOperationException if no default mapped value
4580 >         * for additions was provided
4581           */
4582 <        public static <K,V,U> ForkJoinTask<U> reduceValues
4583 <            (ConcurrentHashMap<K,V> map,
4584 <             Fun<? super V, ? extends U> transformer,
4585 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4586 <            if (transformer == null || reducer == null)
4587 <                throw new NullPointerException();
4588 <            return new MapReduceValuesTask<K,V,U>
4589 <                (map, null, -1, null, transformer, reducer);
4582 >        public boolean addAll(Collection<? extends K> c) {
4583 >            boolean added = false;
4584 >            V v;
4585 >            if ((v = value) == null)
4586 >                throw new UnsupportedOperationException();
4587 >            for (K e : c) {
4588 >                if (map.putVal(e, v, true) == null)
4589 >                    added = true;
4590 >            }
4591 >            return added;
4592          }
4593  
4594 <        /**
4595 <         * Returns a task that when invoked, returns the result of
4596 <         * accumulating the given transformation of all values using the
4597 <         * given reducer to combine values, and the given basis as an
4598 <         * identity value.
4657 <         *
4658 <         * @param map the map
4659 <         * @param transformer a function returning the transformation
4660 <         * for an element
4661 <         * @param basis the identity (initial default value) for the reduction
4662 <         * @param reducer a commutative associative combining function
4663 <         * @return the task
4664 <         */
4665 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
4666 <            (ConcurrentHashMap<K,V> map,
4667 <             ObjectToDouble<? super V> transformer,
4668 <             double basis,
4669 <             DoubleByDoubleToDouble reducer) {
4670 <            if (transformer == null || reducer == null)
4671 <                throw new NullPointerException();
4672 <            return new MapReduceValuesToDoubleTask<K,V>
4673 <                (map, null, -1, null, transformer, basis, reducer);
4594 >        public int hashCode() {
4595 >            int h = 0;
4596 >            for (K e : this)
4597 >                h += e.hashCode();
4598 >            return h;
4599          }
4600  
4601 <        /**
4602 <         * Returns a task that when invoked, returns the result of
4603 <         * accumulating the given transformation of all values using the
4604 <         * given reducer to combine values, and the given basis as an
4605 <         * identity value.
4681 <         *
4682 <         * @param map the map
4683 <         * @param transformer a function returning the transformation
4684 <         * for an element
4685 <         * @param basis the identity (initial default value) for the reduction
4686 <         * @param reducer a commutative associative combining function
4687 <         * @return the task
4688 <         */
4689 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
4690 <            (ConcurrentHashMap<K,V> map,
4691 <             ObjectToLong<? super V> transformer,
4692 <             long basis,
4693 <             LongByLongToLong reducer) {
4694 <            if (transformer == null || reducer == null)
4695 <                throw new NullPointerException();
4696 <            return new MapReduceValuesToLongTask<K,V>
4697 <                (map, null, -1, null, transformer, basis, reducer);
4601 >        public boolean equals(Object o) {
4602 >            Set<?> c;
4603 >            return ((o instanceof Set) &&
4604 >                    ((c = (Set<?>)o) == this ||
4605 >                     (containsAll(c) && c.containsAll(this))));
4606          }
4607  
4608 <        /**
4609 <         * Returns a task that when invoked, returns the result of
4610 <         * accumulating the given transformation of all values using the
4611 <         * given reducer to combine values, and the given basis as an
4612 <         * identity value.
4613 <         *
4706 <         * @param map the map
4707 <         * @param transformer a function returning the transformation
4708 <         * for an element
4709 <         * @param basis the identity (initial default value) for the reduction
4710 <         * @param reducer a commutative associative combining function
4711 <         * @return the task
4712 <         */
4713 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
4714 <            (ConcurrentHashMap<K,V> map,
4715 <             ObjectToInt<? super V> transformer,
4716 <             int basis,
4717 <             IntByIntToInt reducer) {
4718 <            if (transformer == null || reducer == null)
4719 <                throw new NullPointerException();
4720 <            return new MapReduceValuesToIntTask<K,V>
4721 <                (map, null, -1, null, transformer, basis, reducer);
4608 >        public Spliterator<K> spliterator() {
4609 >            Node<K,V>[] t;
4610 >            ConcurrentHashMap<K,V> m = map;
4611 >            long n = m.sumCount();
4612 >            int f = (t = m.table) == null ? 0 : t.length;
4613 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4614          }
4615  
4616 <        /**
4725 <         * Returns a task that when invoked, perform the given action
4726 <         * for each entry.
4727 <         *
4728 <         * @param map the map
4729 <         * @param action the action
4730 <         */
4731 <        public static <K,V> ForkJoinTask<Void> forEachEntry
4732 <            (ConcurrentHashMap<K,V> map,
4733 <             Action<Map.Entry<K,V>> action) {
4616 >        public void forEach(Consumer<? super K> action) {
4617              if (action == null) throw new NullPointerException();
4618 <            return new ForEachEntryTask<K,V>(map, null, -1, null, action);
4618 >            Node<K,V>[] t;
4619 >            if ((t = map.table) != null) {
4620 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4621 >                for (Node<K,V> p; (p = it.advance()) != null; )
4622 >                    action.accept(p.key);
4623 >            }
4624          }
4625 +    }
4626  
4627 <        /**
4628 <         * Returns a task that when invoked, perform the given action
4629 <         * for each non-null transformation of each entry.
4630 <         *
4631 <         * @param map the map
4632 <         * @param transformer a function returning the transformation
4633 <         * for an element, or null if there is no transformation (in
4634 <         * which case the action is not applied)
4635 <         * @param action the action
4636 <         */
4637 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
4749 <            (ConcurrentHashMap<K,V> map,
4750 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4751 <             Action<U> action) {
4752 <            if (transformer == null || action == null)
4753 <                throw new NullPointerException();
4754 <            return new ForEachTransformedEntryTask<K,V,U>
4755 <                (map, null, -1, null, transformer, action);
4627 >    /**
4628 >     * A view of a ConcurrentHashMap as a {@link Collection} of
4629 >     * values, in which additions are disabled. This class cannot be
4630 >     * directly instantiated. See {@link #values()}.
4631 >     */
4632 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4633 >        implements Collection<V>, java.io.Serializable {
4634 >        private static final long serialVersionUID = 2249069246763182397L;
4635 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4636 >        public final boolean contains(Object o) {
4637 >            return map.containsValue(o);
4638          }
4639  
4640 <        /**
4641 <         * Returns a task that when invoked, returns a non-null result
4642 <         * from applying the given search function on each entry, or
4643 <         * null if none.  Upon success, further element processing is
4644 <         * suppressed and the results of any other parallel
4645 <         * invocations of the search function are ignored.
4646 <         *
4647 <         * @param map the map
4648 <         * @param searchFunction a function returning a non-null
4649 <         * result on success, else null
4768 <         * @return the task
4769 <         */
4770 <        public static <K,V,U> ForkJoinTask<U> searchEntries
4771 <            (ConcurrentHashMap<K,V> map,
4772 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4773 <            if (searchFunction == null) throw new NullPointerException();
4774 <            return new SearchEntriesTask<K,V,U>
4775 <                (map, null, -1, null, searchFunction,
4776 <                 new AtomicReference<U>());
4640 >        public final boolean remove(Object o) {
4641 >            if (o != null) {
4642 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4643 >                    if (o.equals(it.next())) {
4644 >                        it.remove();
4645 >                        return true;
4646 >                    }
4647 >                }
4648 >            }
4649 >            return false;
4650          }
4651  
4652 <        /**
4653 <         * Returns a task that when invoked, returns the result of
4654 <         * accumulating all entries using the given reducer to combine
4655 <         * values, or null if none.
4656 <         *
4784 <         * @param map the map
4785 <         * @param reducer a commutative associative combining function
4786 <         * @return the task
4787 <         */
4788 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
4789 <            (ConcurrentHashMap<K,V> map,
4790 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4791 <            if (reducer == null) throw new NullPointerException();
4792 <            return new ReduceEntriesTask<K,V>
4793 <                (map, null, -1, null, reducer);
4652 >        public final Iterator<V> iterator() {
4653 >            ConcurrentHashMap<K,V> m = map;
4654 >            Node<K,V>[] t;
4655 >            int f = (t = m.table) == null ? 0 : t.length;
4656 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4657          }
4658  
4659 <        /**
4660 <         * Returns a task that when invoked, returns the result of
4798 <         * accumulating the given transformation of all entries using the
4799 <         * given reducer to combine values, or null if none.
4800 <         *
4801 <         * @param map the map
4802 <         * @param transformer a function returning the transformation
4803 <         * for an element, or null if there is no transformation (in
4804 <         * which case it is not combined).
4805 <         * @param reducer a commutative associative combining function
4806 <         * @return the task
4807 <         */
4808 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
4809 <            (ConcurrentHashMap<K,V> map,
4810 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4811 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4812 <            if (transformer == null || reducer == null)
4813 <                throw new NullPointerException();
4814 <            return new MapReduceEntriesTask<K,V,U>
4815 <                (map, null, -1, null, transformer, reducer);
4659 >        public final boolean add(V e) {
4660 >            throw new UnsupportedOperationException();
4661          }
4662 <
4663 <        /**
4819 <         * Returns a task that when invoked, returns the result of
4820 <         * accumulating the given transformation of all entries using the
4821 <         * given reducer to combine values, and the given basis as an
4822 <         * identity value.
4823 <         *
4824 <         * @param map the map
4825 <         * @param transformer a function returning the transformation
4826 <         * for an element
4827 <         * @param basis the identity (initial default value) for the reduction
4828 <         * @param reducer a commutative associative combining function
4829 <         * @return the task
4830 <         */
4831 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
4832 <            (ConcurrentHashMap<K,V> map,
4833 <             ObjectToDouble<Map.Entry<K,V>> transformer,
4834 <             double basis,
4835 <             DoubleByDoubleToDouble reducer) {
4836 <            if (transformer == null || reducer == null)
4837 <                throw new NullPointerException();
4838 <            return new MapReduceEntriesToDoubleTask<K,V>
4839 <                (map, null, -1, null, transformer, basis, reducer);
4662 >        public final boolean addAll(Collection<? extends V> c) {
4663 >            throw new UnsupportedOperationException();
4664          }
4665  
4666 <        /**
4667 <         * Returns a task that when invoked, returns the result of
4668 <         * accumulating the given transformation of all entries using the
4669 <         * given reducer to combine values, and the given basis as an
4670 <         * identity value.
4671 <         *
4848 <         * @param map the map
4849 <         * @param transformer a function returning the transformation
4850 <         * for an element
4851 <         * @param basis the identity (initial default value) for the reduction
4852 <         * @param reducer a commutative associative combining function
4853 <         * @return the task
4854 <         */
4855 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4856 <            (ConcurrentHashMap<K,V> map,
4857 <             ObjectToLong<Map.Entry<K,V>> transformer,
4858 <             long basis,
4859 <             LongByLongToLong reducer) {
4860 <            if (transformer == null || reducer == null)
4861 <                throw new NullPointerException();
4862 <            return new MapReduceEntriesToLongTask<K,V>
4863 <                (map, null, -1, null, transformer, basis, reducer);
4666 >        public Spliterator<V> spliterator() {
4667 >            Node<K,V>[] t;
4668 >            ConcurrentHashMap<K,V> m = map;
4669 >            long n = m.sumCount();
4670 >            int f = (t = m.table) == null ? 0 : t.length;
4671 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4672          }
4673  
4674 <        /**
4675 <         * Returns a task that when invoked, returns the result of
4676 <         * accumulating the given transformation of all entries using the
4677 <         * given reducer to combine values, and the given basis as an
4678 <         * identity value.
4679 <         *
4680 <         * @param map the map
4681 <         * @param transformer a function returning the transformation
4874 <         * for an element
4875 <         * @param basis the identity (initial default value) for the reduction
4876 <         * @param reducer a commutative associative combining function
4877 <         * @return the task
4878 <         */
4879 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4880 <            (ConcurrentHashMap<K,V> map,
4881 <             ObjectToInt<Map.Entry<K,V>> transformer,
4882 <             int basis,
4883 <             IntByIntToInt reducer) {
4884 <            if (transformer == null || reducer == null)
4885 <                throw new NullPointerException();
4886 <            return new MapReduceEntriesToIntTask<K,V>
4887 <                (map, null, -1, null, transformer, basis, reducer);
4674 >        public void forEach(Consumer<? super V> action) {
4675 >            if (action == null) throw new NullPointerException();
4676 >            Node<K,V>[] t;
4677 >            if ((t = map.table) != null) {
4678 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4679 >                for (Node<K,V> p; (p = it.advance()) != null; )
4680 >                    action.accept(p.val);
4681 >            }
4682          }
4683      }
4684  
4891    // -------------------------------------------------------
4892
4685      /**
4686 <     * Base for FJ tasks for bulk operations. This adds a variant of
4687 <     * CountedCompleters and some split and merge bookkeeping to
4688 <     * iterator functionality. The forEach and reduce methods are
4689 <     * similar to those illustrated in CountedCompleter documentation,
4690 <     * except that bottom-up reduction completions perform them within
4691 <     * their compute methods. The search methods are like forEach
4692 <     * except they continually poll for success and exit early.  Also,
4693 <     * exceptions are handled in a simpler manner, by just trying to
4902 <     * complete root task exceptionally.
4903 <     */
4904 <    @SuppressWarnings("serial") static abstract class BulkTask<K,V,R> extends Traverser<K,V,R> {
4905 <        final BulkTask<K,V,?> parent;  // completion target
4906 <        int batch;                     // split control; -1 for unknown
4907 <        int pending;                   // completion control
4686 >     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4687 >     * entries.  This class cannot be directly instantiated. See
4688 >     * {@link #entrySet()}.
4689 >     */
4690 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4691 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4692 >        private static final long serialVersionUID = 2249069246763182397L;
4693 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4694  
4695 <        BulkTask(ConcurrentHashMap<K,V> map, BulkTask<K,V,?> parent,
4696 <                 int batch) {
4697 <            super(map);
4698 <            this.parent = parent;
4699 <            this.batch = batch;
4700 <            if (parent != null && map != null) { // split parent
4701 <                Node[] t;
4916 <                if ((t = parent.tab) == null &&
4917 <                    (t = parent.tab = map.table) != null)
4918 <                    parent.baseLimit = parent.baseSize = t.length;
4919 <                this.tab = t;
4920 <                this.baseSize = parent.baseSize;
4921 <                int hi = this.baseLimit = parent.baseLimit;
4922 <                parent.baseLimit = this.index = this.baseIndex =
4923 <                    (hi + parent.baseIndex + 1) >>> 1;
4924 <            }
4695 >        public boolean contains(Object o) {
4696 >            Object k, v, r; Map.Entry<?,?> e;
4697 >            return ((o instanceof Map.Entry) &&
4698 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4699 >                    (r = map.get(k)) != null &&
4700 >                    (v = e.getValue()) != null &&
4701 >                    (v == r || v.equals(r)));
4702          }
4703  
4704 <        /**
4705 <         * Forces root task to complete.
4706 <         * @param ex if null, complete normally, else exceptionally
4707 <         * @return false to simplify use
4708 <         */
4709 <        final boolean tryCompleteComputation(Throwable ex) {
4933 <            for (BulkTask<K,V,?> a = this;;) {
4934 <                BulkTask<K,V,?> p = a.parent;
4935 <                if (p == null) {
4936 <                    if (ex != null)
4937 <                        a.completeExceptionally(ex);
4938 <                    else
4939 <                        a.quietlyComplete();
4940 <                    return false;
4941 <                }
4942 <                a = p;
4943 <            }
4704 >        public boolean remove(Object o) {
4705 >            Object k, v; Map.Entry<?,?> e;
4706 >            return ((o instanceof Map.Entry) &&
4707 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4708 >                    (v = e.getValue()) != null &&
4709 >                    map.remove(k, v));
4710          }
4711  
4712          /**
4713 <         * Version of tryCompleteComputation for function screening checks
4713 >         * @return an iterator over the entries of the backing map
4714           */
4715 <        final boolean abortOnNullFunction() {
4716 <            return tryCompleteComputation(new Error("Unexpected null function"));
4715 >        public Iterator<Map.Entry<K,V>> iterator() {
4716 >            ConcurrentHashMap<K,V> m = map;
4717 >            Node<K,V>[] t;
4718 >            int f = (t = m.table) == null ? 0 : t.length;
4719 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4720          }
4721  
4722 <        // utilities
4722 >        public boolean add(Entry<K,V> e) {
4723 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4724 >        }
4725  
4726 <        /** CompareAndSet pending count */
4727 <        final boolean casPending(int cmp, int val) {
4728 <            return U.compareAndSwapInt(this, PENDING, cmp, val);
4726 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4727 >            boolean added = false;
4728 >            for (Entry<K,V> e : c) {
4729 >                if (add(e))
4730 >                    added = true;
4731 >            }
4732 >            return added;
4733          }
4734  
4735 <        /**
4736 <         * Returns approx exp2 of the number of times (minus one) to
4737 <         * split task by two before executing leaf action. This value
4738 <         * is faster to compute and more convenient to use as a guide
4739 <         * to splitting than is the depth, since it is used while
4740 <         * dividing by two anyway.
4741 <         */
4967 <        final int batch() {
4968 <            ConcurrentHashMap<K, V> m; int b; Node[] t;  ForkJoinPool pool;
4969 <            if ((b = batch) < 0 && (m = map) != null) { // force initialization
4970 <                if ((t = tab) == null && (t = tab = m.table) != null)
4971 <                    baseLimit = baseSize = t.length;
4972 <                if (t != null) {
4973 <                    long n = m.counter.sum();
4974 <                    int par = (pool = getPool()) == null?
4975 <                        ForkJoinPool.getCommonPoolParallelism() :
4976 <                        pool.getParallelism();
4977 <                    int sp = par << 3; // slack of 8
4978 <                    b = batch = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
4735 >        public final int hashCode() {
4736 >            int h = 0;
4737 >            Node<K,V>[] t;
4738 >            if ((t = map.table) != null) {
4739 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4740 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4741 >                    h += p.hashCode();
4742                  }
4743              }
4744 <            return b;
4744 >            return h;
4745          }
4746  
4747 <        /**
4748 <         * Returns exportable snapshot entry.
4749 <         */
4750 <        static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
4751 <            return new AbstractMap.SimpleEntry<K,V>(k, v);
4747 >        public final boolean equals(Object o) {
4748 >            Set<?> c;
4749 >            return ((o instanceof Set) &&
4750 >                    ((c = (Set<?>)o) == this ||
4751 >                     (containsAll(c) && c.containsAll(this))));
4752          }
4753  
4754 <        // Unsafe mechanics
4755 <        private static final sun.misc.Unsafe U;
4756 <        private static final long PENDING;
4757 <        static {
4758 <            try {
4759 <                U = sun.misc.Unsafe.getUnsafe();
4760 <                PENDING = U.objectFieldOffset
4761 <                    (BulkTask.class.getDeclaredField("pending"));
4762 <            } catch (Exception e) {
4763 <                throw new Error(e);
4754 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4755 >            Node<K,V>[] t;
4756 >            ConcurrentHashMap<K,V> m = map;
4757 >            long n = m.sumCount();
4758 >            int f = (t = m.table) == null ? 0 : t.length;
4759 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4760 >        }
4761 >
4762 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4763 >            if (action == null) throw new NullPointerException();
4764 >            Node<K,V>[] t;
4765 >            if ((t = map.table) != null) {
4766 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4767 >                for (Node<K,V> p; (p = it.advance()) != null; )
4768 >                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
4769              }
4770          }
4771 +
4772      }
4773  
4774 +    // -------------------------------------------------------
4775 +
4776      /**
4777 <     * Base class for non-reductive actions
4777 >     * Base class for bulk tasks. Repeats some fields and code from
4778 >     * class Traverser, because we need to subclass CountedCompleter.
4779       */
4780 <    @SuppressWarnings("serial") static abstract class BulkAction<K,V,R> extends BulkTask<K,V,R> {
4781 <        BulkAction<K,V,?> nextTask;
4782 <        BulkAction(ConcurrentHashMap<K,V> map, BulkTask<K,V,?> parent,
4783 <                   int batch, BulkAction<K,V,?> nextTask) {
4784 <            super(map, parent, batch);
4785 <            this.nextTask = nextTask;
4780 >    @SuppressWarnings("serial")
4781 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4782 >        Node<K,V>[] tab;        // same as Traverser
4783 >        Node<K,V> next;
4784 >        TableStack<K,V> stack, spare;
4785 >        int index;
4786 >        int baseIndex;
4787 >        int baseLimit;
4788 >        final int baseSize;
4789 >        int batch;              // split control
4790 >
4791 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4792 >            super(par);
4793 >            this.batch = b;
4794 >            this.index = this.baseIndex = i;
4795 >            if ((this.tab = t) == null)
4796 >                this.baseSize = this.baseLimit = 0;
4797 >            else if (par == null)
4798 >                this.baseSize = this.baseLimit = t.length;
4799 >            else {
4800 >                this.baseLimit = f;
4801 >                this.baseSize = par.baseSize;
4802 >            }
4803          }
4804  
4805          /**
4806 <         * Try to complete task and upward parents. Upon hitting
5018 <         * non-completed parent, if a non-FJ task, try to help out the
5019 <         * computation.
4806 >         * Same as Traverser version
4807           */
4808 <        final void tryComplete(BulkAction<K,V,?> subtasks) {
4809 <            BulkTask<K,V,?> a = this, s = a;
4810 <            for (int c;;) {
4811 <                if ((c = a.pending) == 0) {
4812 <                    if ((a = (s = a).parent) == null) {
4813 <                        s.quietlyComplete();
4814 <                        break;
4815 <                    }
4816 <                }
4817 <                else if (a.casPending(c, c - 1)) {
4818 <                    if (subtasks != null && !inForkJoinPool()) {
4819 <                        while ((s = a.parent) != null)
4820 <                            a = s;
4821 <                        while (!a.isDone()) {
4822 <                            BulkAction<K,V,?> next = subtasks.nextTask;
4823 <                            if (subtasks.tryUnfork())
4824 <                                subtasks.exec();
5038 <                            if ((subtasks = next) == null)
5039 <                                break;
5040 <                        }
4808 >        final Node<K,V> advance() {
4809 >            Node<K,V> e;
4810 >            if ((e = next) != null)
4811 >                e = e.next;
4812 >            for (;;) {
4813 >                Node<K,V>[] t; int i, n;
4814 >                if (e != null)
4815 >                    return next = e;
4816 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4817 >                    (n = t.length) <= (i = index) || i < 0)
4818 >                    return next = null;
4819 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
4820 >                    if (e instanceof ForwardingNode) {
4821 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4822 >                        e = null;
4823 >                        pushState(t, i, n);
4824 >                        continue;
4825                      }
4826 <                    break;
4826 >                    else if (e instanceof TreeBin)
4827 >                        e = ((TreeBin<K,V>)e).first;
4828 >                    else
4829 >                        e = null;
4830                  }
4831 +                if (stack != null)
4832 +                    recoverState(n);
4833 +                else if ((index = i + baseSize) >= n)
4834 +                    index = ++baseIndex;
4835              }
4836          }
4837  
4838 +        private void pushState(Node<K,V>[] t, int i, int n) {
4839 +            TableStack<K,V> s = spare;
4840 +            if (s != null)
4841 +                spare = s.next;
4842 +            else
4843 +                s = new TableStack<K,V>();
4844 +            s.tab = t;
4845 +            s.length = n;
4846 +            s.index = i;
4847 +            s.next = stack;
4848 +            stack = s;
4849 +        }
4850 +
4851 +        private void recoverState(int n) {
4852 +            TableStack<K,V> s; int len;
4853 +            while ((s = stack) != null && (index += (len = s.length)) >= n) {
4854 +                n = len;
4855 +                index = s.index;
4856 +                tab = s.tab;
4857 +                s.tab = null;
4858 +                TableStack<K,V> next = s.next;
4859 +                s.next = spare; // save for reuse
4860 +                stack = next;
4861 +                spare = s;
4862 +            }
4863 +            if (s == null && (index += baseSize) >= n)
4864 +                index = ++baseIndex;
4865 +        }
4866      }
4867  
4868      /*
4869       * Task classes. Coded in a regular but ugly format/style to
4870       * simplify checks that each variant differs in the right way from
4871 <     * others.
4872 <     */
4873 <
4874 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4875 <        extends BulkAction<K,V,Void> {
4876 <        final Action<K> action;
4871 >     * others. The null screenings exist because compilers cannot tell
4872 >     * that we've already null-checked task arguments, so we force
4873 >     * simplest hoisted bypass to help avoid convoluted traps.
4874 >     */
4875 >    @SuppressWarnings("serial")
4876 >    static final class ForEachKeyTask<K,V>
4877 >        extends BulkTask<K,V,Void> {
4878 >        final Consumer<? super K> action;
4879          ForEachKeyTask
4880 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4881 <             ForEachKeyTask<K,V> nextTask,
4882 <             Action<K> action) {
5062 <            super(m, p, b, nextTask);
4880 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4881 >             Consumer<? super K> action) {
4882 >            super(p, b, i, f, t);
4883              this.action = action;
4884          }
4885 <        @SuppressWarnings("unchecked") public final boolean exec() {
4886 <            final Action<K> action = this.action;
4887 <            if (action == null)
4888 <                return abortOnNullFunction();
4889 <            ForEachKeyTask<K,V> subtasks = null;
4890 <            try {
4891 <                int b = batch(), c;
4892 <                while (b > 1 && baseIndex != baseLimit) {
4893 <                    do {} while (!casPending(c = pending, c+1));
4894 <                    (subtasks = new ForEachKeyTask<K,V>
4895 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4896 <                }
4897 <                while (advance() != null)
5078 <                    action.apply((K)nextKey);
5079 <            } catch (Throwable ex) {
5080 <                return tryCompleteComputation(ex);
4885 >        public final void compute() {
4886 >            final Consumer<? super K> action;
4887 >            if ((action = this.action) != null) {
4888 >                for (int i = baseIndex, f, h; batch > 0 &&
4889 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4890 >                    addToPendingCount(1);
4891 >                    new ForEachKeyTask<K,V>
4892 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4893 >                         action).fork();
4894 >                }
4895 >                for (Node<K,V> p; (p = advance()) != null;)
4896 >                    action.accept(p.key);
4897 >                propagateCompletion();
4898              }
5082            tryComplete(subtasks);
5083            return false;
4899          }
4900      }
4901  
4902 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4903 <        extends BulkAction<K,V,Void> {
4904 <        final Action<V> action;
4902 >    @SuppressWarnings("serial")
4903 >    static final class ForEachValueTask<K,V>
4904 >        extends BulkTask<K,V,Void> {
4905 >        final Consumer<? super V> action;
4906          ForEachValueTask
4907 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4908 <             ForEachValueTask<K,V> nextTask,
4909 <             Action<V> action) {
5094 <            super(m, p, b, nextTask);
4907 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4908 >             Consumer<? super V> action) {
4909 >            super(p, b, i, f, t);
4910              this.action = action;
4911          }
4912 <        @SuppressWarnings("unchecked") public final boolean exec() {
4913 <            final Action<V> action = this.action;
4914 <            if (action == null)
4915 <                return abortOnNullFunction();
4916 <            ForEachValueTask<K,V> subtasks = null;
4917 <            try {
4918 <                int b = batch(), c;
4919 <                while (b > 1 && baseIndex != baseLimit) {
4920 <                    do {} while (!casPending(c = pending, c+1));
4921 <                    (subtasks = new ForEachValueTask<K,V>
4922 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4923 <                }
4924 <                Object v;
5110 <                while ((v = advance()) != null)
5111 <                    action.apply((V)v);
5112 <            } catch (Throwable ex) {
5113 <                return tryCompleteComputation(ex);
4912 >        public final void compute() {
4913 >            final Consumer<? super V> action;
4914 >            if ((action = this.action) != null) {
4915 >                for (int i = baseIndex, f, h; batch > 0 &&
4916 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4917 >                    addToPendingCount(1);
4918 >                    new ForEachValueTask<K,V>
4919 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4920 >                         action).fork();
4921 >                }
4922 >                for (Node<K,V> p; (p = advance()) != null;)
4923 >                    action.accept(p.val);
4924 >                propagateCompletion();
4925              }
5115            tryComplete(subtasks);
5116            return false;
4926          }
4927      }
4928  
4929 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4930 <        extends BulkAction<K,V,Void> {
4931 <        final Action<Entry<K,V>> action;
4929 >    @SuppressWarnings("serial")
4930 >    static final class ForEachEntryTask<K,V>
4931 >        extends BulkTask<K,V,Void> {
4932 >        final Consumer<? super Entry<K,V>> action;
4933          ForEachEntryTask
4934 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4935 <             ForEachEntryTask<K,V> nextTask,
4936 <             Action<Entry<K,V>> action) {
5127 <            super(m, p, b, nextTask);
4934 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4935 >             Consumer<? super Entry<K,V>> action) {
4936 >            super(p, b, i, f, t);
4937              this.action = action;
4938          }
4939 <        @SuppressWarnings("unchecked") public final boolean exec() {
4940 <            final Action<Entry<K,V>> action = this.action;
4941 <            if (action == null)
4942 <                return abortOnNullFunction();
4943 <            ForEachEntryTask<K,V> subtasks = null;
4944 <            try {
4945 <                int b = batch(), c;
4946 <                while (b > 1 && baseIndex != baseLimit) {
4947 <                    do {} while (!casPending(c = pending, c+1));
4948 <                    (subtasks = new ForEachEntryTask<K,V>
4949 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4950 <                }
4951 <                Object v;
5143 <                while ((v = advance()) != null)
5144 <                    action.apply(entryFor((K)nextKey, (V)v));
5145 <            } catch (Throwable ex) {
5146 <                return tryCompleteComputation(ex);
4939 >        public final void compute() {
4940 >            final Consumer<? super Entry<K,V>> action;
4941 >            if ((action = this.action) != null) {
4942 >                for (int i = baseIndex, f, h; batch > 0 &&
4943 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4944 >                    addToPendingCount(1);
4945 >                    new ForEachEntryTask<K,V>
4946 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4947 >                         action).fork();
4948 >                }
4949 >                for (Node<K,V> p; (p = advance()) != null; )
4950 >                    action.accept(p);
4951 >                propagateCompletion();
4952              }
5148            tryComplete(subtasks);
5149            return false;
4953          }
4954      }
4955  
4956 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4957 <        extends BulkAction<K,V,Void> {
4958 <        final BiAction<K,V> action;
4956 >    @SuppressWarnings("serial")
4957 >    static final class ForEachMappingTask<K,V>
4958 >        extends BulkTask<K,V,Void> {
4959 >        final BiConsumer<? super K, ? super V> action;
4960          ForEachMappingTask
4961 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4962 <             ForEachMappingTask<K,V> nextTask,
4963 <             BiAction<K,V> action) {
5160 <            super(m, p, b, nextTask);
4961 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4962 >             BiConsumer<? super K,? super V> action) {
4963 >            super(p, b, i, f, t);
4964              this.action = action;
4965          }
4966 <        @SuppressWarnings("unchecked") public final boolean exec() {
4967 <            final BiAction<K,V> action = this.action;
4968 <            if (action == null)
4969 <                return abortOnNullFunction();
4970 <            ForEachMappingTask<K,V> subtasks = null;
4971 <            try {
4972 <                int b = batch(), c;
4973 <                while (b > 1 && baseIndex != baseLimit) {
4974 <                    do {} while (!casPending(c = pending, c+1));
4975 <                    (subtasks = new ForEachMappingTask<K,V>
4976 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4977 <                }
4978 <                Object v;
5176 <                while ((v = advance()) != null)
5177 <                    action.apply((K)nextKey, (V)v);
5178 <            } catch (Throwable ex) {
5179 <                return tryCompleteComputation(ex);
4966 >        public final void compute() {
4967 >            final BiConsumer<? super K, ? super V> action;
4968 >            if ((action = this.action) != null) {
4969 >                for (int i = baseIndex, f, h; batch > 0 &&
4970 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4971 >                    addToPendingCount(1);
4972 >                    new ForEachMappingTask<K,V>
4973 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4974 >                         action).fork();
4975 >                }
4976 >                for (Node<K,V> p; (p = advance()) != null; )
4977 >                    action.accept(p.key, p.val);
4978 >                propagateCompletion();
4979              }
5181            tryComplete(subtasks);
5182            return false;
4980          }
4981      }
4982  
4983 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4984 <        extends BulkAction<K,V,Void> {
4985 <        final Fun<? super K, ? extends U> transformer;
4986 <        final Action<U> action;
4983 >    @SuppressWarnings("serial")
4984 >    static final class ForEachTransformedKeyTask<K,V,U>
4985 >        extends BulkTask<K,V,Void> {
4986 >        final Function<? super K, ? extends U> transformer;
4987 >        final Consumer<? super U> action;
4988          ForEachTransformedKeyTask
4989 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4990 <             ForEachTransformedKeyTask<K,V,U> nextTask,
4991 <             Fun<? super K, ? extends U> transformer,
4992 <             Action<U> action) {
4993 <            super(m, p, b, nextTask);
4994 <            this.transformer = transformer;
4995 <            this.action = action;
4996 <
4997 <        }
4998 <        @SuppressWarnings("unchecked") public final boolean exec() {
4999 <            final Fun<? super K, ? extends U> transformer =
5000 <                this.transformer;
5001 <            final Action<U> action = this.action;
5002 <            if (transformer == null || action == null)
5003 <                return abortOnNullFunction();
5004 <            ForEachTransformedKeyTask<K,V,U> subtasks = null;
5005 <            try {
5006 <                int b = batch(), c;
5007 <                while (b > 1 && baseIndex != baseLimit) {
5008 <                    do {} while (!casPending(c = pending, c+1));
5009 <                    (subtasks = new ForEachTransformedKeyTask<K,V,U>
5010 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5011 <                }
5214 <                U u;
5215 <                while (advance() != null) {
5216 <                    if ((u = transformer.apply((K)nextKey)) != null)
5217 <                        action.apply(u);
5218 <                }
5219 <            } catch (Throwable ex) {
5220 <                return tryCompleteComputation(ex);
4989 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4990 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
4991 >            super(p, b, i, f, t);
4992 >            this.transformer = transformer; this.action = action;
4993 >        }
4994 >        public final void compute() {
4995 >            final Function<? super K, ? extends U> transformer;
4996 >            final Consumer<? super U> action;
4997 >            if ((transformer = this.transformer) != null &&
4998 >                (action = this.action) != null) {
4999 >                for (int i = baseIndex, f, h; batch > 0 &&
5000 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5001 >                    addToPendingCount(1);
5002 >                    new ForEachTransformedKeyTask<K,V,U>
5003 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5004 >                         transformer, action).fork();
5005 >                }
5006 >                for (Node<K,V> p; (p = advance()) != null; ) {
5007 >                    U u;
5008 >                    if ((u = transformer.apply(p.key)) != null)
5009 >                        action.accept(u);
5010 >                }
5011 >                propagateCompletion();
5012              }
5222            tryComplete(subtasks);
5223            return false;
5013          }
5014      }
5015  
5016 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5017 <        extends BulkAction<K,V,Void> {
5018 <        final Fun<? super V, ? extends U> transformer;
5019 <        final Action<U> action;
5016 >    @SuppressWarnings("serial")
5017 >    static final class ForEachTransformedValueTask<K,V,U>
5018 >        extends BulkTask<K,V,Void> {
5019 >        final Function<? super V, ? extends U> transformer;
5020 >        final Consumer<? super U> action;
5021          ForEachTransformedValueTask
5022 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5023 <             ForEachTransformedValueTask<K,V,U> nextTask,
5024 <             Fun<? super V, ? extends U> transformer,
5025 <             Action<U> action) {
5026 <            super(m, p, b, nextTask);
5027 <            this.transformer = transformer;
5028 <            this.action = action;
5029 <
5030 <        }
5031 <        @SuppressWarnings("unchecked") public final boolean exec() {
5032 <            final Fun<? super V, ? extends U> transformer =
5033 <                this.transformer;
5034 <            final Action<U> action = this.action;
5035 <            if (transformer == null || action == null)
5036 <                return abortOnNullFunction();
5037 <            ForEachTransformedValueTask<K,V,U> subtasks = null;
5038 <            try {
5039 <                int b = batch(), c;
5040 <                while (b > 1 && baseIndex != baseLimit) {
5041 <                    do {} while (!casPending(c = pending, c+1));
5042 <                    (subtasks = new ForEachTransformedValueTask<K,V,U>
5043 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5044 <                }
5255 <                Object v; U u;
5256 <                while ((v = advance()) != null) {
5257 <                    if ((u = transformer.apply((V)v)) != null)
5258 <                        action.apply(u);
5259 <                }
5260 <            } catch (Throwable ex) {
5261 <                return tryCompleteComputation(ex);
5022 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5023 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5024 >            super(p, b, i, f, t);
5025 >            this.transformer = transformer; this.action = action;
5026 >        }
5027 >        public final void compute() {
5028 >            final Function<? super V, ? extends U> transformer;
5029 >            final Consumer<? super U> action;
5030 >            if ((transformer = this.transformer) != null &&
5031 >                (action = this.action) != null) {
5032 >                for (int i = baseIndex, f, h; batch > 0 &&
5033 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5034 >                    addToPendingCount(1);
5035 >                    new ForEachTransformedValueTask<K,V,U>
5036 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5037 >                         transformer, action).fork();
5038 >                }
5039 >                for (Node<K,V> p; (p = advance()) != null; ) {
5040 >                    U u;
5041 >                    if ((u = transformer.apply(p.val)) != null)
5042 >                        action.accept(u);
5043 >                }
5044 >                propagateCompletion();
5045              }
5263            tryComplete(subtasks);
5264            return false;
5046          }
5047      }
5048  
5049 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5050 <        extends BulkAction<K,V,Void> {
5051 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5052 <        final Action<U> action;
5049 >    @SuppressWarnings("serial")
5050 >    static final class ForEachTransformedEntryTask<K,V,U>
5051 >        extends BulkTask<K,V,Void> {
5052 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5053 >        final Consumer<? super U> action;
5054          ForEachTransformedEntryTask
5055 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5056 <             ForEachTransformedEntryTask<K,V,U> nextTask,
5057 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5058 <             Action<U> action) {
5059 <            super(m, p, b, nextTask);
5060 <            this.transformer = transformer;
5061 <            this.action = action;
5062 <
5063 <        }
5064 <        @SuppressWarnings("unchecked") public final boolean exec() {
5065 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5066 <                this.transformer;
5067 <            final Action<U> action = this.action;
5068 <            if (transformer == null || action == null)
5069 <                return abortOnNullFunction();
5070 <            ForEachTransformedEntryTask<K,V,U> subtasks = null;
5071 <            try {
5072 <                int b = batch(), c;
5073 <                while (b > 1 && baseIndex != baseLimit) {
5074 <                    do {} while (!casPending(c = pending, c+1));
5075 <                    (subtasks = new ForEachTransformedEntryTask<K,V,U>
5076 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5077 <                }
5296 <                Object v; U u;
5297 <                while ((v = advance()) != null) {
5298 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5299 <                        action.apply(u);
5300 <                }
5301 <            } catch (Throwable ex) {
5302 <                return tryCompleteComputation(ex);
5055 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5056 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5057 >            super(p, b, i, f, t);
5058 >            this.transformer = transformer; this.action = action;
5059 >        }
5060 >        public final void compute() {
5061 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5062 >            final Consumer<? super U> action;
5063 >            if ((transformer = this.transformer) != null &&
5064 >                (action = this.action) != null) {
5065 >                for (int i = baseIndex, f, h; batch > 0 &&
5066 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5067 >                    addToPendingCount(1);
5068 >                    new ForEachTransformedEntryTask<K,V,U>
5069 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5070 >                         transformer, action).fork();
5071 >                }
5072 >                for (Node<K,V> p; (p = advance()) != null; ) {
5073 >                    U u;
5074 >                    if ((u = transformer.apply(p)) != null)
5075 >                        action.accept(u);
5076 >                }
5077 >                propagateCompletion();
5078              }
5304            tryComplete(subtasks);
5305            return false;
5079          }
5080      }
5081  
5082 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5083 <        extends BulkAction<K,V,Void> {
5084 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5085 <        final Action<U> action;
5082 >    @SuppressWarnings("serial")
5083 >    static final class ForEachTransformedMappingTask<K,V,U>
5084 >        extends BulkTask<K,V,Void> {
5085 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5086 >        final Consumer<? super U> action;
5087          ForEachTransformedMappingTask
5088 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5089 <             ForEachTransformedMappingTask<K,V,U> nextTask,
5090 <             BiFun<? super K, ? super V, ? extends U> transformer,
5091 <             Action<U> action) {
5092 <            super(m, p, b, nextTask);
5093 <            this.transformer = transformer;
5094 <            this.action = action;
5095 <
5096 <        }
5097 <        @SuppressWarnings("unchecked") public final boolean exec() {
5098 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5099 <                this.transformer;
5100 <            final Action<U> action = this.action;
5101 <            if (transformer == null || action == null)
5102 <                return abortOnNullFunction();
5103 <            ForEachTransformedMappingTask<K,V,U> subtasks = null;
5104 <            try {
5105 <                int b = batch(), c;
5106 <                while (b > 1 && baseIndex != baseLimit) {
5107 <                    do {} while (!casPending(c = pending, c+1));
5108 <                    (subtasks = new ForEachTransformedMappingTask<K,V,U>
5109 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5336 <                }
5337 <                Object v; U u;
5338 <                while ((v = advance()) != null) {
5339 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5340 <                        action.apply(u);
5088 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5089 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5090 >             Consumer<? super U> action) {
5091 >            super(p, b, i, f, t);
5092 >            this.transformer = transformer; this.action = action;
5093 >        }
5094 >        public final void compute() {
5095 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5096 >            final Consumer<? super U> action;
5097 >            if ((transformer = this.transformer) != null &&
5098 >                (action = this.action) != null) {
5099 >                for (int i = baseIndex, f, h; batch > 0 &&
5100 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5101 >                    addToPendingCount(1);
5102 >                    new ForEachTransformedMappingTask<K,V,U>
5103 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5104 >                         transformer, action).fork();
5105 >                }
5106 >                for (Node<K,V> p; (p = advance()) != null; ) {
5107 >                    U u;
5108 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5109 >                        action.accept(u);
5110                  }
5111 <            } catch (Throwable ex) {
5343 <                return tryCompleteComputation(ex);
5111 >                propagateCompletion();
5112              }
5345            tryComplete(subtasks);
5346            return false;
5113          }
5114      }
5115  
5116 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5117 <        extends BulkAction<K,V,U> {
5118 <        final Fun<? super K, ? extends U> searchFunction;
5116 >    @SuppressWarnings("serial")
5117 >    static final class SearchKeysTask<K,V,U>
5118 >        extends BulkTask<K,V,U> {
5119 >        final Function<? super K, ? extends U> searchFunction;
5120          final AtomicReference<U> result;
5121          SearchKeysTask
5122 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5123 <             SearchKeysTask<K,V,U> nextTask,
5357 <             Fun<? super K, ? extends U> searchFunction,
5122 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5123 >             Function<? super K, ? extends U> searchFunction,
5124               AtomicReference<U> result) {
5125 <            super(m, p, b, nextTask);
5125 >            super(p, b, i, f, t);
5126              this.searchFunction = searchFunction; this.result = result;
5127          }
5128 <        @SuppressWarnings("unchecked") public final boolean exec() {
5129 <            AtomicReference<U> result = this.result;
5130 <            final Fun<? super K, ? extends U> searchFunction =
5131 <                this.searchFunction;
5132 <            if (searchFunction == null || result == null)
5133 <                return abortOnNullFunction();
5134 <            SearchKeysTask<K,V,U> subtasks = null;
5135 <            try {
5136 <                int b = batch(), c;
5137 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5138 <                    do {} while (!casPending(c = pending, c+1));
5139 <                    (subtasks = new SearchKeysTask<K,V,U>
5140 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5141 <                }
5142 <                U u;
5143 <                while (result.get() == null && advance() != null) {
5144 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
5128 >        public final U getRawResult() { return result.get(); }
5129 >        public final void compute() {
5130 >            final Function<? super K, ? extends U> searchFunction;
5131 >            final AtomicReference<U> result;
5132 >            if ((searchFunction = this.searchFunction) != null &&
5133 >                (result = this.result) != null) {
5134 >                for (int i = baseIndex, f, h; batch > 0 &&
5135 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5136 >                    if (result.get() != null)
5137 >                        return;
5138 >                    addToPendingCount(1);
5139 >                    new SearchKeysTask<K,V,U>
5140 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5141 >                         searchFunction, result).fork();
5142 >                }
5143 >                while (result.get() == null) {
5144 >                    U u;
5145 >                    Node<K,V> p;
5146 >                    if ((p = advance()) == null) {
5147 >                        propagateCompletion();
5148 >                        break;
5149 >                    }
5150 >                    if ((u = searchFunction.apply(p.key)) != null) {
5151                          if (result.compareAndSet(null, u))
5152 <                            tryCompleteComputation(null);
5152 >                            quietlyCompleteRoot();
5153                          break;
5154                      }
5155                  }
5384            } catch (Throwable ex) {
5385                return tryCompleteComputation(ex);
5156              }
5387            tryComplete(subtasks);
5388            return false;
5157          }
5390        public final U getRawResult() { return result.get(); }
5158      }
5159  
5160 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5161 <        extends BulkAction<K,V,U> {
5162 <        final Fun<? super V, ? extends U> searchFunction;
5160 >    @SuppressWarnings("serial")
5161 >    static final class SearchValuesTask<K,V,U>
5162 >        extends BulkTask<K,V,U> {
5163 >        final Function<? super V, ? extends U> searchFunction;
5164          final AtomicReference<U> result;
5165          SearchValuesTask
5166 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5167 <             SearchValuesTask<K,V,U> nextTask,
5400 <             Fun<? super V, ? extends U> searchFunction,
5166 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5167 >             Function<? super V, ? extends U> searchFunction,
5168               AtomicReference<U> result) {
5169 <            super(m, p, b, nextTask);
5169 >            super(p, b, i, f, t);
5170              this.searchFunction = searchFunction; this.result = result;
5171          }
5172 <        @SuppressWarnings("unchecked") public final boolean exec() {
5173 <            AtomicReference<U> result = this.result;
5174 <            final Fun<? super V, ? extends U> searchFunction =
5175 <                this.searchFunction;
5176 <            if (searchFunction == null || result == null)
5177 <                return abortOnNullFunction();
5178 <            SearchValuesTask<K,V,U> subtasks = null;
5179 <            try {
5180 <                int b = batch(), c;
5181 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5182 <                    do {} while (!casPending(c = pending, c+1));
5183 <                    (subtasks = new SearchValuesTask<K,V,U>
5184 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5185 <                }
5186 <                Object v; U u;
5187 <                while (result.get() == null && (v = advance()) != null) {
5188 <                    if ((u = searchFunction.apply((V)v)) != null) {
5172 >        public final U getRawResult() { return result.get(); }
5173 >        public final void compute() {
5174 >            final Function<? super V, ? extends U> searchFunction;
5175 >            final AtomicReference<U> result;
5176 >            if ((searchFunction = this.searchFunction) != null &&
5177 >                (result = this.result) != null) {
5178 >                for (int i = baseIndex, f, h; batch > 0 &&
5179 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5180 >                    if (result.get() != null)
5181 >                        return;
5182 >                    addToPendingCount(1);
5183 >                    new SearchValuesTask<K,V,U>
5184 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5185 >                         searchFunction, result).fork();
5186 >                }
5187 >                while (result.get() == null) {
5188 >                    U u;
5189 >                    Node<K,V> p;
5190 >                    if ((p = advance()) == null) {
5191 >                        propagateCompletion();
5192 >                        break;
5193 >                    }
5194 >                    if ((u = searchFunction.apply(p.val)) != null) {
5195                          if (result.compareAndSet(null, u))
5196 <                            tryCompleteComputation(null);
5196 >                            quietlyCompleteRoot();
5197                          break;
5198                      }
5199                  }
5427            } catch (Throwable ex) {
5428                return tryCompleteComputation(ex);
5200              }
5430            tryComplete(subtasks);
5431            return false;
5201          }
5433        public final U getRawResult() { return result.get(); }
5202      }
5203  
5204 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5205 <        extends BulkAction<K,V,U> {
5206 <        final Fun<Entry<K,V>, ? extends U> searchFunction;
5204 >    @SuppressWarnings("serial")
5205 >    static final class SearchEntriesTask<K,V,U>
5206 >        extends BulkTask<K,V,U> {
5207 >        final Function<Entry<K,V>, ? extends U> searchFunction;
5208          final AtomicReference<U> result;
5209          SearchEntriesTask
5210 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5211 <             SearchEntriesTask<K,V,U> nextTask,
5443 <             Fun<Entry<K,V>, ? extends U> searchFunction,
5210 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5211 >             Function<Entry<K,V>, ? extends U> searchFunction,
5212               AtomicReference<U> result) {
5213 <            super(m, p, b, nextTask);
5213 >            super(p, b, i, f, t);
5214              this.searchFunction = searchFunction; this.result = result;
5215          }
5216 <        @SuppressWarnings("unchecked") public final boolean exec() {
5217 <            AtomicReference<U> result = this.result;
5218 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
5219 <                this.searchFunction;
5220 <            if (searchFunction == null || result == null)
5221 <                return abortOnNullFunction();
5222 <            SearchEntriesTask<K,V,U> subtasks = null;
5223 <            try {
5224 <                int b = batch(), c;
5225 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5226 <                    do {} while (!casPending(c = pending, c+1));
5227 <                    (subtasks = new SearchEntriesTask<K,V,U>
5228 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5229 <                }
5230 <                Object v; U u;
5231 <                while (result.get() == null && (v = advance()) != null) {
5232 <                    if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
5233 <                        if (result.compareAndSet(null, u))
5234 <                            tryCompleteComputation(null);
5216 >        public final U getRawResult() { return result.get(); }
5217 >        public final void compute() {
5218 >            final Function<Entry<K,V>, ? extends U> searchFunction;
5219 >            final AtomicReference<U> result;
5220 >            if ((searchFunction = this.searchFunction) != null &&
5221 >                (result = this.result) != null) {
5222 >                for (int i = baseIndex, f, h; batch > 0 &&
5223 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5224 >                    if (result.get() != null)
5225 >                        return;
5226 >                    addToPendingCount(1);
5227 >                    new SearchEntriesTask<K,V,U>
5228 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5229 >                         searchFunction, result).fork();
5230 >                }
5231 >                while (result.get() == null) {
5232 >                    U u;
5233 >                    Node<K,V> p;
5234 >                    if ((p = advance()) == null) {
5235 >                        propagateCompletion();
5236                          break;
5237                      }
5238 +                    if ((u = searchFunction.apply(p)) != null) {
5239 +                        if (result.compareAndSet(null, u))
5240 +                            quietlyCompleteRoot();
5241 +                        return;
5242 +                    }
5243                  }
5470            } catch (Throwable ex) {
5471                return tryCompleteComputation(ex);
5244              }
5473            tryComplete(subtasks);
5474            return false;
5245          }
5476        public final U getRawResult() { return result.get(); }
5246      }
5247  
5248 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5249 <        extends BulkAction<K,V,U> {
5250 <        final BiFun<? super K, ? super V, ? extends U> searchFunction;
5248 >    @SuppressWarnings("serial")
5249 >    static final class SearchMappingsTask<K,V,U>
5250 >        extends BulkTask<K,V,U> {
5251 >        final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5252          final AtomicReference<U> result;
5253          SearchMappingsTask
5254 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5255 <             SearchMappingsTask<K,V,U> nextTask,
5486 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
5254 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5255 >             BiFunction<? super K, ? super V, ? extends U> searchFunction,
5256               AtomicReference<U> result) {
5257 <            super(m, p, b, nextTask);
5257 >            super(p, b, i, f, t);
5258              this.searchFunction = searchFunction; this.result = result;
5259          }
5260 <        @SuppressWarnings("unchecked") public final boolean exec() {
5261 <            AtomicReference<U> result = this.result;
5262 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
5263 <                this.searchFunction;
5264 <            if (searchFunction == null || result == null)
5265 <                return abortOnNullFunction();
5266 <            SearchMappingsTask<K,V,U> subtasks = null;
5267 <            try {
5268 <                int b = batch(), c;
5269 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5270 <                    do {} while (!casPending(c = pending, c+1));
5271 <                    (subtasks = new SearchMappingsTask<K,V,U>
5272 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5273 <                }
5274 <                Object v; U u;
5275 <                while (result.get() == null && (v = advance()) != null) {
5276 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5260 >        public final U getRawResult() { return result.get(); }
5261 >        public final void compute() {
5262 >            final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5263 >            final AtomicReference<U> result;
5264 >            if ((searchFunction = this.searchFunction) != null &&
5265 >                (result = this.result) != null) {
5266 >                for (int i = baseIndex, f, h; batch > 0 &&
5267 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5268 >                    if (result.get() != null)
5269 >                        return;
5270 >                    addToPendingCount(1);
5271 >                    new SearchMappingsTask<K,V,U>
5272 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5273 >                         searchFunction, result).fork();
5274 >                }
5275 >                while (result.get() == null) {
5276 >                    U u;
5277 >                    Node<K,V> p;
5278 >                    if ((p = advance()) == null) {
5279 >                        propagateCompletion();
5280 >                        break;
5281 >                    }
5282 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5283                          if (result.compareAndSet(null, u))
5284 <                            tryCompleteComputation(null);
5284 >                            quietlyCompleteRoot();
5285                          break;
5286                      }
5287                  }
5513            } catch (Throwable ex) {
5514                return tryCompleteComputation(ex);
5288              }
5516            tryComplete(subtasks);
5517            return false;
5289          }
5519        public final U getRawResult() { return result.get(); }
5290      }
5291  
5292 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5292 >    @SuppressWarnings("serial")
5293 >    static final class ReduceKeysTask<K,V>
5294          extends BulkTask<K,V,K> {
5295 <        final BiFun<? super K, ? super K, ? extends K> reducer;
5295 >        final BiFunction<? super K, ? super K, ? extends K> reducer;
5296          K result;
5297          ReduceKeysTask<K,V> rights, nextRight;
5298          ReduceKeysTask
5299 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5299 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5300               ReduceKeysTask<K,V> nextRight,
5301 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5302 <            super(m, p, b); this.nextRight = nextRight;
5301 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
5302 >            super(p, b, i, f, t); this.nextRight = nextRight;
5303              this.reducer = reducer;
5304          }
5305 <        @SuppressWarnings("unchecked") public final boolean exec() {
5306 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5307 <                this.reducer;
5308 <            if (reducer == null)
5309 <                return abortOnNullFunction();
5310 <            try {
5311 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5541 <                    do {} while (!casPending(c = pending, c+1));
5305 >        public final K getRawResult() { return result; }
5306 >        public final void compute() {
5307 >            final BiFunction<? super K, ? super K, ? extends K> reducer;
5308 >            if ((reducer = this.reducer) != null) {
5309 >                for (int i = baseIndex, f, h; batch > 0 &&
5310 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5311 >                    addToPendingCount(1);
5312                      (rights = new ReduceKeysTask<K,V>
5313 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5313 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5314 >                      rights, reducer)).fork();
5315                  }
5316                  K r = null;
5317 <                while (advance() != null) {
5318 <                    K u = (K)nextKey;
5319 <                    r = (r == null) ? u : reducer.apply(r, u);
5317 >                for (Node<K,V> p; (p = advance()) != null; ) {
5318 >                    K u = p.key;
5319 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5320                  }
5321                  result = r;
5322 <                for (ReduceKeysTask<K,V> t = this, s;;) {
5323 <                    int c; BulkTask<K,V,?> par; K tr, sr;
5324 <                    if ((c = t.pending) == 0) {
5325 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5326 <                            if ((sr = s.result) != null)
5327 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5328 <                        }
5329 <                        if ((par = t.parent) == null ||
5330 <                            !(par instanceof ReduceKeysTask)) {
5331 <                            t.quietlyComplete();
5332 <                            break;
5333 <                        }
5563 <                        t = (ReduceKeysTask<K,V>)par;
5322 >                CountedCompleter<?> c;
5323 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5324 >                    @SuppressWarnings("unchecked")
5325 >                    ReduceKeysTask<K,V>
5326 >                        t = (ReduceKeysTask<K,V>)c,
5327 >                        s = t.rights;
5328 >                    while (s != null) {
5329 >                        K tr, sr;
5330 >                        if ((sr = s.result) != null)
5331 >                            t.result = (((tr = t.result) == null) ? sr :
5332 >                                        reducer.apply(tr, sr));
5333 >                        s = t.rights = s.nextRight;
5334                      }
5565                    else if (t.casPending(c, c - 1))
5566                        break;
5335                  }
5568            } catch (Throwable ex) {
5569                return tryCompleteComputation(ex);
5336              }
5571            ReduceKeysTask<K,V> s = rights;
5572            if (s != null && !inForkJoinPool()) {
5573                do  {
5574                    if (s.tryUnfork())
5575                        s.exec();
5576                } while ((s = s.nextRight) != null);
5577            }
5578            return false;
5337          }
5580        public final K getRawResult() { return result; }
5338      }
5339  
5340 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5340 >    @SuppressWarnings("serial")
5341 >    static final class ReduceValuesTask<K,V>
5342          extends BulkTask<K,V,V> {
5343 <        final BiFun<? super V, ? super V, ? extends V> reducer;
5343 >        final BiFunction<? super V, ? super V, ? extends V> reducer;
5344          V result;
5345          ReduceValuesTask<K,V> rights, nextRight;
5346          ReduceValuesTask
5347 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5347 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5348               ReduceValuesTask<K,V> nextRight,
5349 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5350 <            super(m, p, b); this.nextRight = nextRight;
5349 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
5350 >            super(p, b, i, f, t); this.nextRight = nextRight;
5351              this.reducer = reducer;
5352          }
5353 <        @SuppressWarnings("unchecked") public final boolean exec() {
5354 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5355 <                this.reducer;
5356 <            if (reducer == null)
5357 <                return abortOnNullFunction();
5358 <            try {
5359 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5602 <                    do {} while (!casPending(c = pending, c+1));
5353 >        public final V getRawResult() { return result; }
5354 >        public final void compute() {
5355 >            final BiFunction<? super V, ? super V, ? extends V> reducer;
5356 >            if ((reducer = this.reducer) != null) {
5357 >                for (int i = baseIndex, f, h; batch > 0 &&
5358 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5359 >                    addToPendingCount(1);
5360                      (rights = new ReduceValuesTask<K,V>
5361 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5361 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5362 >                      rights, reducer)).fork();
5363                  }
5364                  V r = null;
5365 <                Object v;
5366 <                while ((v = advance()) != null) {
5367 <                    V u = (V)v;
5610 <                    r = (r == null) ? u : reducer.apply(r, u);
5365 >                for (Node<K,V> p; (p = advance()) != null; ) {
5366 >                    V v = p.val;
5367 >                    r = (r == null) ? v : reducer.apply(r, v);
5368                  }
5369                  result = r;
5370 <                for (ReduceValuesTask<K,V> t = this, s;;) {
5371 <                    int c; BulkTask<K,V,?> par; V tr, sr;
5372 <                    if ((c = t.pending) == 0) {
5373 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5374 <                            if ((sr = s.result) != null)
5375 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5376 <                        }
5377 <                        if ((par = t.parent) == null ||
5378 <                            !(par instanceof ReduceValuesTask)) {
5379 <                            t.quietlyComplete();
5380 <                            break;
5381 <                        }
5625 <                        t = (ReduceValuesTask<K,V>)par;
5370 >                CountedCompleter<?> c;
5371 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5372 >                    @SuppressWarnings("unchecked")
5373 >                    ReduceValuesTask<K,V>
5374 >                        t = (ReduceValuesTask<K,V>)c,
5375 >                        s = t.rights;
5376 >                    while (s != null) {
5377 >                        V tr, sr;
5378 >                        if ((sr = s.result) != null)
5379 >                            t.result = (((tr = t.result) == null) ? sr :
5380 >                                        reducer.apply(tr, sr));
5381 >                        s = t.rights = s.nextRight;
5382                      }
5627                    else if (t.casPending(c, c - 1))
5628                        break;
5383                  }
5630            } catch (Throwable ex) {
5631                return tryCompleteComputation(ex);
5384              }
5633            ReduceValuesTask<K,V> s = rights;
5634            if (s != null && !inForkJoinPool()) {
5635                do  {
5636                    if (s.tryUnfork())
5637                        s.exec();
5638                } while ((s = s.nextRight) != null);
5639            }
5640            return false;
5385          }
5642        public final V getRawResult() { return result; }
5386      }
5387  
5388 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5388 >    @SuppressWarnings("serial")
5389 >    static final class ReduceEntriesTask<K,V>
5390          extends BulkTask<K,V,Map.Entry<K,V>> {
5391 <        final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5391 >        final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5392          Map.Entry<K,V> result;
5393          ReduceEntriesTask<K,V> rights, nextRight;
5394          ReduceEntriesTask
5395 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5395 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5396               ReduceEntriesTask<K,V> nextRight,
5397 <             BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5398 <            super(m, p, b); this.nextRight = nextRight;
5397 >             BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5398 >            super(p, b, i, f, t); this.nextRight = nextRight;
5399              this.reducer = reducer;
5400          }
5401 <        @SuppressWarnings("unchecked") public final boolean exec() {
5402 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
5403 <                this.reducer;
5404 <            if (reducer == null)
5405 <                return abortOnNullFunction();
5406 <            try {
5407 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5664 <                    do {} while (!casPending(c = pending, c+1));
5401 >        public final Map.Entry<K,V> getRawResult() { return result; }
5402 >        public final void compute() {
5403 >            final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5404 >            if ((reducer = this.reducer) != null) {
5405 >                for (int i = baseIndex, f, h; batch > 0 &&
5406 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5407 >                    addToPendingCount(1);
5408                      (rights = new ReduceEntriesTask<K,V>
5409 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5409 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5410 >                      rights, reducer)).fork();
5411                  }
5412                  Map.Entry<K,V> r = null;
5413 <                Object v;
5414 <                while ((v = advance()) != null) {
5671 <                    Map.Entry<K,V> u = entryFor((K)nextKey, (V)v);
5672 <                    r = (r == null) ? u : reducer.apply(r, u);
5673 <                }
5413 >                for (Node<K,V> p; (p = advance()) != null; )
5414 >                    r = (r == null) ? p : reducer.apply(r, p);
5415                  result = r;
5416 <                for (ReduceEntriesTask<K,V> t = this, s;;) {
5417 <                    int c; BulkTask<K,V,?> par; Map.Entry<K,V> tr, sr;
5418 <                    if ((c = t.pending) == 0) {
5419 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5420 <                            if ((sr = s.result) != null)
5421 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5422 <                        }
5423 <                        if ((par = t.parent) == null ||
5424 <                            !(par instanceof ReduceEntriesTask)) {
5425 <                            t.quietlyComplete();
5426 <                            break;
5427 <                        }
5687 <                        t = (ReduceEntriesTask<K,V>)par;
5416 >                CountedCompleter<?> c;
5417 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5418 >                    @SuppressWarnings("unchecked")
5419 >                    ReduceEntriesTask<K,V>
5420 >                        t = (ReduceEntriesTask<K,V>)c,
5421 >                        s = t.rights;
5422 >                    while (s != null) {
5423 >                        Map.Entry<K,V> tr, sr;
5424 >                        if ((sr = s.result) != null)
5425 >                            t.result = (((tr = t.result) == null) ? sr :
5426 >                                        reducer.apply(tr, sr));
5427 >                        s = t.rights = s.nextRight;
5428                      }
5689                    else if (t.casPending(c, c - 1))
5690                        break;
5429                  }
5692            } catch (Throwable ex) {
5693                return tryCompleteComputation(ex);
5430              }
5695            ReduceEntriesTask<K,V> s = rights;
5696            if (s != null && !inForkJoinPool()) {
5697                do  {
5698                    if (s.tryUnfork())
5699                        s.exec();
5700                } while ((s = s.nextRight) != null);
5701            }
5702            return false;
5431          }
5704        public final Map.Entry<K,V> getRawResult() { return result; }
5432      }
5433  
5434 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5434 >    @SuppressWarnings("serial")
5435 >    static final class MapReduceKeysTask<K,V,U>
5436          extends BulkTask<K,V,U> {
5437 <        final Fun<? super K, ? extends U> transformer;
5438 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5437 >        final Function<? super K, ? extends U> transformer;
5438 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5439          U result;
5440          MapReduceKeysTask<K,V,U> rights, nextRight;
5441          MapReduceKeysTask
5442 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5442 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5443               MapReduceKeysTask<K,V,U> nextRight,
5444 <             Fun<? super K, ? extends U> transformer,
5445 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5446 <            super(m, p, b); this.nextRight = nextRight;
5444 >             Function<? super K, ? extends U> transformer,
5445 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5446 >            super(p, b, i, f, t); this.nextRight = nextRight;
5447              this.transformer = transformer;
5448              this.reducer = reducer;
5449          }
5450 <        @SuppressWarnings("unchecked") public final boolean exec() {
5451 <            final Fun<? super K, ? extends U> transformer =
5452 <                this.transformer;
5453 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5454 <                this.reducer;
5455 <            if (transformer == null || reducer == null)
5456 <                return abortOnNullFunction();
5457 <            try {
5458 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5731 <                    do {} while (!casPending(c = pending, c+1));
5450 >        public final U getRawResult() { return result; }
5451 >        public final void compute() {
5452 >            final Function<? super K, ? extends U> transformer;
5453 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5454 >            if ((transformer = this.transformer) != null &&
5455 >                (reducer = this.reducer) != null) {
5456 >                for (int i = baseIndex, f, h; batch > 0 &&
5457 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5458 >                    addToPendingCount(1);
5459                      (rights = new MapReduceKeysTask<K,V,U>
5460 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5460 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5461 >                      rights, transformer, reducer)).fork();
5462                  }
5463 <                U r = null, u;
5464 <                while (advance() != null) {
5465 <                    if ((u = transformer.apply((K)nextKey)) != null)
5463 >                U r = null;
5464 >                for (Node<K,V> p; (p = advance()) != null; ) {
5465 >                    U u;
5466 >                    if ((u = transformer.apply(p.key)) != null)
5467                          r = (r == null) ? u : reducer.apply(r, u);
5468                  }
5469                  result = r;
5470 <                for (MapReduceKeysTask<K,V,U> t = this, s;;) {
5471 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5472 <                    if ((c = t.pending) == 0) {
5473 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5474 <                            if ((sr = s.result) != null)
5475 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5476 <                        }
5477 <                        if ((par = t.parent) == null ||
5478 <                            !(par instanceof MapReduceKeysTask)) {
5479 <                            t.quietlyComplete();
5480 <                            break;
5481 <                        }
5753 <                        t = (MapReduceKeysTask<K,V,U>)par;
5470 >                CountedCompleter<?> c;
5471 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5472 >                    @SuppressWarnings("unchecked")
5473 >                    MapReduceKeysTask<K,V,U>
5474 >                        t = (MapReduceKeysTask<K,V,U>)c,
5475 >                        s = t.rights;
5476 >                    while (s != null) {
5477 >                        U tr, sr;
5478 >                        if ((sr = s.result) != null)
5479 >                            t.result = (((tr = t.result) == null) ? sr :
5480 >                                        reducer.apply(tr, sr));
5481 >                        s = t.rights = s.nextRight;
5482                      }
5755                    else if (t.casPending(c, c - 1))
5756                        break;
5483                  }
5758            } catch (Throwable ex) {
5759                return tryCompleteComputation(ex);
5760            }
5761            MapReduceKeysTask<K,V,U> s = rights;
5762            if (s != null && !inForkJoinPool()) {
5763                do  {
5764                    if (s.tryUnfork())
5765                        s.exec();
5766                } while ((s = s.nextRight) != null);
5484              }
5768            return false;
5485          }
5770        public final U getRawResult() { return result; }
5486      }
5487  
5488 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5488 >    @SuppressWarnings("serial")
5489 >    static final class MapReduceValuesTask<K,V,U>
5490          extends BulkTask<K,V,U> {
5491 <        final Fun<? super V, ? extends U> transformer;
5492 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5491 >        final Function<? super V, ? extends U> transformer;
5492 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5493          U result;
5494          MapReduceValuesTask<K,V,U> rights, nextRight;
5495          MapReduceValuesTask
5496 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5496 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5497               MapReduceValuesTask<K,V,U> nextRight,
5498 <             Fun<? super V, ? extends U> transformer,
5499 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5500 <            super(m, p, b); this.nextRight = nextRight;
5498 >             Function<? super V, ? extends U> transformer,
5499 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5500 >            super(p, b, i, f, t); this.nextRight = nextRight;
5501              this.transformer = transformer;
5502              this.reducer = reducer;
5503          }
5504 <        @SuppressWarnings("unchecked") public final boolean exec() {
5505 <            final Fun<? super V, ? extends U> transformer =
5506 <                this.transformer;
5507 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5508 <                this.reducer;
5509 <            if (transformer == null || reducer == null)
5510 <                return abortOnNullFunction();
5511 <            try {
5512 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5797 <                    do {} while (!casPending(c = pending, c+1));
5504 >        public final U getRawResult() { return result; }
5505 >        public final void compute() {
5506 >            final Function<? super V, ? extends U> transformer;
5507 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5508 >            if ((transformer = this.transformer) != null &&
5509 >                (reducer = this.reducer) != null) {
5510 >                for (int i = baseIndex, f, h; batch > 0 &&
5511 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5512 >                    addToPendingCount(1);
5513                      (rights = new MapReduceValuesTask<K,V,U>
5514 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5514 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5515 >                      rights, transformer, reducer)).fork();
5516                  }
5517 <                U r = null, u;
5518 <                Object v;
5519 <                while ((v = advance()) != null) {
5520 <                    if ((u = transformer.apply((V)v)) != null)
5517 >                U r = null;
5518 >                for (Node<K,V> p; (p = advance()) != null; ) {
5519 >                    U u;
5520 >                    if ((u = transformer.apply(p.val)) != null)
5521                          r = (r == null) ? u : reducer.apply(r, u);
5522                  }
5523                  result = r;
5524 <                for (MapReduceValuesTask<K,V,U> t = this, s;;) {
5525 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5526 <                    if ((c = t.pending) == 0) {
5527 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5528 <                            if ((sr = s.result) != null)
5529 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5530 <                        }
5531 <                        if ((par = t.parent) == null ||
5532 <                            !(par instanceof MapReduceValuesTask)) {
5533 <                            t.quietlyComplete();
5534 <                            break;
5535 <                        }
5820 <                        t = (MapReduceValuesTask<K,V,U>)par;
5524 >                CountedCompleter<?> c;
5525 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5526 >                    @SuppressWarnings("unchecked")
5527 >                    MapReduceValuesTask<K,V,U>
5528 >                        t = (MapReduceValuesTask<K,V,U>)c,
5529 >                        s = t.rights;
5530 >                    while (s != null) {
5531 >                        U tr, sr;
5532 >                        if ((sr = s.result) != null)
5533 >                            t.result = (((tr = t.result) == null) ? sr :
5534 >                                        reducer.apply(tr, sr));
5535 >                        s = t.rights = s.nextRight;
5536                      }
5822                    else if (t.casPending(c, c - 1))
5823                        break;
5537                  }
5825            } catch (Throwable ex) {
5826                return tryCompleteComputation(ex);
5538              }
5828            MapReduceValuesTask<K,V,U> s = rights;
5829            if (s != null && !inForkJoinPool()) {
5830                do  {
5831                    if (s.tryUnfork())
5832                        s.exec();
5833                } while ((s = s.nextRight) != null);
5834            }
5835            return false;
5539          }
5837        public final U getRawResult() { return result; }
5540      }
5541  
5542 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5542 >    @SuppressWarnings("serial")
5543 >    static final class MapReduceEntriesTask<K,V,U>
5544          extends BulkTask<K,V,U> {
5545 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5546 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5545 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5546 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5547          U result;
5548          MapReduceEntriesTask<K,V,U> rights, nextRight;
5549          MapReduceEntriesTask
5550 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5550 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5551               MapReduceEntriesTask<K,V,U> nextRight,
5552 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5553 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5554 <            super(m, p, b); this.nextRight = nextRight;
5552 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5553 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5554 >            super(p, b, i, f, t); this.nextRight = nextRight;
5555              this.transformer = transformer;
5556              this.reducer = reducer;
5557          }
5558 <        @SuppressWarnings("unchecked") public final boolean exec() {
5559 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5560 <                this.transformer;
5561 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5562 <                this.reducer;
5563 <            if (transformer == null || reducer == null)
5564 <                return abortOnNullFunction();
5565 <            try {
5566 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5864 <                    do {} while (!casPending(c = pending, c+1));
5558 >        public final U getRawResult() { return result; }
5559 >        public final void compute() {
5560 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5561 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5562 >            if ((transformer = this.transformer) != null &&
5563 >                (reducer = this.reducer) != null) {
5564 >                for (int i = baseIndex, f, h; batch > 0 &&
5565 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5566 >                    addToPendingCount(1);
5567                      (rights = new MapReduceEntriesTask<K,V,U>
5568 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5568 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5569 >                      rights, transformer, reducer)).fork();
5570                  }
5571 <                U r = null, u;
5572 <                Object v;
5573 <                while ((v = advance()) != null) {
5574 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5571 >                U r = null;
5572 >                for (Node<K,V> p; (p = advance()) != null; ) {
5573 >                    U u;
5574 >                    if ((u = transformer.apply(p)) != null)
5575                          r = (r == null) ? u : reducer.apply(r, u);
5576                  }
5577                  result = r;
5578 <                for (MapReduceEntriesTask<K,V,U> t = this, s;;) {
5579 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5580 <                    if ((c = t.pending) == 0) {
5581 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5582 <                            if ((sr = s.result) != null)
5583 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5584 <                        }
5585 <                        if ((par = t.parent) == null ||
5586 <                            !(par instanceof MapReduceEntriesTask)) {
5587 <                            t.quietlyComplete();
5588 <                            break;
5589 <                        }
5887 <                        t = (MapReduceEntriesTask<K,V,U>)par;
5578 >                CountedCompleter<?> c;
5579 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5580 >                    @SuppressWarnings("unchecked")
5581 >                    MapReduceEntriesTask<K,V,U>
5582 >                        t = (MapReduceEntriesTask<K,V,U>)c,
5583 >                        s = t.rights;
5584 >                    while (s != null) {
5585 >                        U tr, sr;
5586 >                        if ((sr = s.result) != null)
5587 >                            t.result = (((tr = t.result) == null) ? sr :
5588 >                                        reducer.apply(tr, sr));
5589 >                        s = t.rights = s.nextRight;
5590                      }
5889                    else if (t.casPending(c, c - 1))
5890                        break;
5591                  }
5892            } catch (Throwable ex) {
5893                return tryCompleteComputation(ex);
5592              }
5895            MapReduceEntriesTask<K,V,U> s = rights;
5896            if (s != null && !inForkJoinPool()) {
5897                do  {
5898                    if (s.tryUnfork())
5899                        s.exec();
5900                } while ((s = s.nextRight) != null);
5901            }
5902            return false;
5593          }
5904        public final U getRawResult() { return result; }
5594      }
5595  
5596 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5596 >    @SuppressWarnings("serial")
5597 >    static final class MapReduceMappingsTask<K,V,U>
5598          extends BulkTask<K,V,U> {
5599 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5600 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5599 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5600 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5601          U result;
5602          MapReduceMappingsTask<K,V,U> rights, nextRight;
5603          MapReduceMappingsTask
5604 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5604 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5605               MapReduceMappingsTask<K,V,U> nextRight,
5606 <             BiFun<? super K, ? super V, ? extends U> transformer,
5607 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5608 <            super(m, p, b); this.nextRight = nextRight;
5606 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5607 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5608 >            super(p, b, i, f, t); this.nextRight = nextRight;
5609              this.transformer = transformer;
5610              this.reducer = reducer;
5611          }
5612 <        @SuppressWarnings("unchecked") public final boolean exec() {
5613 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5614 <                this.transformer;
5615 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5616 <                this.reducer;
5617 <            if (transformer == null || reducer == null)
5618 <                return abortOnNullFunction();
5619 <            try {
5620 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5931 <                    do {} while (!casPending(c = pending, c+1));
5612 >        public final U getRawResult() { return result; }
5613 >        public final void compute() {
5614 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5615 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5616 >            if ((transformer = this.transformer) != null &&
5617 >                (reducer = this.reducer) != null) {
5618 >                for (int i = baseIndex, f, h; batch > 0 &&
5619 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5620 >                    addToPendingCount(1);
5621                      (rights = new MapReduceMappingsTask<K,V,U>
5622 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5622 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5623 >                      rights, transformer, reducer)).fork();
5624                  }
5625 <                U r = null, u;
5626 <                Object v;
5627 <                while ((v = advance()) != null) {
5628 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5625 >                U r = null;
5626 >                for (Node<K,V> p; (p = advance()) != null; ) {
5627 >                    U u;
5628 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5629                          r = (r == null) ? u : reducer.apply(r, u);
5630                  }
5631                  result = r;
5632 <                for (MapReduceMappingsTask<K,V,U> t = this, s;;) {
5633 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5634 <                    if ((c = t.pending) == 0) {
5635 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5636 <                            if ((sr = s.result) != null)
5637 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5638 <                        }
5639 <                        if ((par = t.parent) == null ||
5640 <                            !(par instanceof MapReduceMappingsTask)) {
5641 <                            t.quietlyComplete();
5642 <                            break;
5643 <                        }
5954 <                        t = (MapReduceMappingsTask<K,V,U>)par;
5632 >                CountedCompleter<?> c;
5633 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5634 >                    @SuppressWarnings("unchecked")
5635 >                    MapReduceMappingsTask<K,V,U>
5636 >                        t = (MapReduceMappingsTask<K,V,U>)c,
5637 >                        s = t.rights;
5638 >                    while (s != null) {
5639 >                        U tr, sr;
5640 >                        if ((sr = s.result) != null)
5641 >                            t.result = (((tr = t.result) == null) ? sr :
5642 >                                        reducer.apply(tr, sr));
5643 >                        s = t.rights = s.nextRight;
5644                      }
5956                    else if (t.casPending(c, c - 1))
5957                        break;
5645                  }
5959            } catch (Throwable ex) {
5960                return tryCompleteComputation(ex);
5646              }
5962            MapReduceMappingsTask<K,V,U> s = rights;
5963            if (s != null && !inForkJoinPool()) {
5964                do  {
5965                    if (s.tryUnfork())
5966                        s.exec();
5967                } while ((s = s.nextRight) != null);
5968            }
5969            return false;
5647          }
5971        public final U getRawResult() { return result; }
5648      }
5649  
5650 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5650 >    @SuppressWarnings("serial")
5651 >    static final class MapReduceKeysToDoubleTask<K,V>
5652          extends BulkTask<K,V,Double> {
5653 <        final ObjectToDouble<? super K> transformer;
5654 <        final DoubleByDoubleToDouble reducer;
5653 >        final ToDoubleFunction<? super K> transformer;
5654 >        final DoubleBinaryOperator reducer;
5655          final double basis;
5656          double result;
5657          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5658          MapReduceKeysToDoubleTask
5659 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5659 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5660               MapReduceKeysToDoubleTask<K,V> nextRight,
5661 <             ObjectToDouble<? super K> transformer,
5661 >             ToDoubleFunction<? super K> transformer,
5662               double basis,
5663 <             DoubleByDoubleToDouble reducer) {
5664 <            super(m, p, b); this.nextRight = nextRight;
5663 >             DoubleBinaryOperator reducer) {
5664 >            super(p, b, i, f, t); this.nextRight = nextRight;
5665              this.transformer = transformer;
5666              this.basis = basis; this.reducer = reducer;
5667          }
5668 <        @SuppressWarnings("unchecked") public final boolean exec() {
5669 <            final ObjectToDouble<? super K> transformer =
5670 <                this.transformer;
5671 <            final DoubleByDoubleToDouble reducer = this.reducer;
5672 <            if (transformer == null || reducer == null)
5673 <                return abortOnNullFunction();
5674 <            try {
5675 <                final double id = this.basis;
5676 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5677 <                    do {} while (!casPending(c = pending, c+1));
5668 >        public final Double getRawResult() { return result; }
5669 >        public final void compute() {
5670 >            final ToDoubleFunction<? super K> transformer;
5671 >            final DoubleBinaryOperator reducer;
5672 >            if ((transformer = this.transformer) != null &&
5673 >                (reducer = this.reducer) != null) {
5674 >                double r = this.basis;
5675 >                for (int i = baseIndex, f, h; batch > 0 &&
5676 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5677 >                    addToPendingCount(1);
5678                      (rights = new MapReduceKeysToDoubleTask<K,V>
5679 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5679 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5680 >                      rights, transformer, r, reducer)).fork();
5681                  }
5682 <                double r = id;
5683 <                while (advance() != null)
6006 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5682 >                for (Node<K,V> p; (p = advance()) != null; )
5683 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5684                  result = r;
5685 <                for (MapReduceKeysToDoubleTask<K,V> t = this, s;;) {
5686 <                    int c; BulkTask<K,V,?> par;
5687 <                    if ((c = t.pending) == 0) {
5688 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5689 <                            t.result = reducer.apply(t.result, s.result);
5690 <                        }
5691 <                        if ((par = t.parent) == null ||
5692 <                            !(par instanceof MapReduceKeysToDoubleTask)) {
5693 <                            t.quietlyComplete();
6017 <                            break;
6018 <                        }
6019 <                        t = (MapReduceKeysToDoubleTask<K,V>)par;
5685 >                CountedCompleter<?> c;
5686 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5687 >                    @SuppressWarnings("unchecked")
5688 >                    MapReduceKeysToDoubleTask<K,V>
5689 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
5690 >                        s = t.rights;
5691 >                    while (s != null) {
5692 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5693 >                        s = t.rights = s.nextRight;
5694                      }
6021                    else if (t.casPending(c, c - 1))
6022                        break;
5695                  }
6024            } catch (Throwable ex) {
6025                return tryCompleteComputation(ex);
6026            }
6027            MapReduceKeysToDoubleTask<K,V> s = rights;
6028            if (s != null && !inForkJoinPool()) {
6029                do  {
6030                    if (s.tryUnfork())
6031                        s.exec();
6032                } while ((s = s.nextRight) != null);
5696              }
6034            return false;
5697          }
6036        public final Double getRawResult() { return result; }
5698      }
5699  
5700 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5700 >    @SuppressWarnings("serial")
5701 >    static final class MapReduceValuesToDoubleTask<K,V>
5702          extends BulkTask<K,V,Double> {
5703 <        final ObjectToDouble<? super V> transformer;
5704 <        final DoubleByDoubleToDouble reducer;
5703 >        final ToDoubleFunction<? super V> transformer;
5704 >        final DoubleBinaryOperator reducer;
5705          final double basis;
5706          double result;
5707          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5708          MapReduceValuesToDoubleTask
5709 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5709 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5710               MapReduceValuesToDoubleTask<K,V> nextRight,
5711 <             ObjectToDouble<? super V> transformer,
5711 >             ToDoubleFunction<? super V> transformer,
5712               double basis,
5713 <             DoubleByDoubleToDouble reducer) {
5714 <            super(m, p, b); this.nextRight = nextRight;
5713 >             DoubleBinaryOperator reducer) {
5714 >            super(p, b, i, f, t); this.nextRight = nextRight;
5715              this.transformer = transformer;
5716              this.basis = basis; this.reducer = reducer;
5717          }
5718 <        @SuppressWarnings("unchecked") public final boolean exec() {
5719 <            final ObjectToDouble<? super V> transformer =
5720 <                this.transformer;
5721 <            final DoubleByDoubleToDouble reducer = this.reducer;
5722 <            if (transformer == null || reducer == null)
5723 <                return abortOnNullFunction();
5724 <            try {
5725 <                final double id = this.basis;
5726 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5727 <                    do {} while (!casPending(c = pending, c+1));
5718 >        public final Double getRawResult() { return result; }
5719 >        public final void compute() {
5720 >            final ToDoubleFunction<? super V> transformer;
5721 >            final DoubleBinaryOperator reducer;
5722 >            if ((transformer = this.transformer) != null &&
5723 >                (reducer = this.reducer) != null) {
5724 >                double r = this.basis;
5725 >                for (int i = baseIndex, f, h; batch > 0 &&
5726 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5727 >                    addToPendingCount(1);
5728                      (rights = new MapReduceValuesToDoubleTask<K,V>
5729 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5729 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5730 >                      rights, transformer, r, reducer)).fork();
5731                  }
5732 <                double r = id;
5733 <                Object v;
6071 <                while ((v = advance()) != null)
6072 <                    r = reducer.apply(r, transformer.apply((V)v));
5732 >                for (Node<K,V> p; (p = advance()) != null; )
5733 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5734                  result = r;
5735 <                for (MapReduceValuesToDoubleTask<K,V> t = this, s;;) {
5736 <                    int c; BulkTask<K,V,?> par;
5737 <                    if ((c = t.pending) == 0) {
5738 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5739 <                            t.result = reducer.apply(t.result, s.result);
5740 <                        }
5741 <                        if ((par = t.parent) == null ||
5742 <                            !(par instanceof MapReduceValuesToDoubleTask)) {
5743 <                            t.quietlyComplete();
6083 <                            break;
6084 <                        }
6085 <                        t = (MapReduceValuesToDoubleTask<K,V>)par;
5735 >                CountedCompleter<?> c;
5736 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5737 >                    @SuppressWarnings("unchecked")
5738 >                    MapReduceValuesToDoubleTask<K,V>
5739 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
5740 >                        s = t.rights;
5741 >                    while (s != null) {
5742 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5743 >                        s = t.rights = s.nextRight;
5744                      }
6087                    else if (t.casPending(c, c - 1))
6088                        break;
5745                  }
6090            } catch (Throwable ex) {
6091                return tryCompleteComputation(ex);
5746              }
6093            MapReduceValuesToDoubleTask<K,V> s = rights;
6094            if (s != null && !inForkJoinPool()) {
6095                do  {
6096                    if (s.tryUnfork())
6097                        s.exec();
6098                } while ((s = s.nextRight) != null);
6099            }
6100            return false;
5747          }
6102        public final Double getRawResult() { return result; }
5748      }
5749  
5750 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5750 >    @SuppressWarnings("serial")
5751 >    static final class MapReduceEntriesToDoubleTask<K,V>
5752          extends BulkTask<K,V,Double> {
5753 <        final ObjectToDouble<Map.Entry<K,V>> transformer;
5754 <        final DoubleByDoubleToDouble reducer;
5753 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
5754 >        final DoubleBinaryOperator reducer;
5755          final double basis;
5756          double result;
5757          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5758          MapReduceEntriesToDoubleTask
5759 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5759 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5760               MapReduceEntriesToDoubleTask<K,V> nextRight,
5761 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5761 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5762               double basis,
5763 <             DoubleByDoubleToDouble reducer) {
5764 <            super(m, p, b); this.nextRight = nextRight;
5763 >             DoubleBinaryOperator reducer) {
5764 >            super(p, b, i, f, t); this.nextRight = nextRight;
5765              this.transformer = transformer;
5766              this.basis = basis; this.reducer = reducer;
5767          }
5768 <        @SuppressWarnings("unchecked") public final boolean exec() {
5769 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
5770 <                this.transformer;
5771 <            final DoubleByDoubleToDouble reducer = this.reducer;
5772 <            if (transformer == null || reducer == null)
5773 <                return abortOnNullFunction();
5774 <            try {
5775 <                final double id = this.basis;
5776 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5777 <                    do {} while (!casPending(c = pending, c+1));
5768 >        public final Double getRawResult() { return result; }
5769 >        public final void compute() {
5770 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
5771 >            final DoubleBinaryOperator reducer;
5772 >            if ((transformer = this.transformer) != null &&
5773 >                (reducer = this.reducer) != null) {
5774 >                double r = this.basis;
5775 >                for (int i = baseIndex, f, h; batch > 0 &&
5776 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5777 >                    addToPendingCount(1);
5778                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5779 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5779 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5780 >                      rights, transformer, r, reducer)).fork();
5781                  }
5782 <                double r = id;
5783 <                Object v;
6137 <                while ((v = advance()) != null)
6138 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5782 >                for (Node<K,V> p; (p = advance()) != null; )
5783 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5784                  result = r;
5785 <                for (MapReduceEntriesToDoubleTask<K,V> t = this, s;;) {
5786 <                    int c; BulkTask<K,V,?> par;
5787 <                    if ((c = t.pending) == 0) {
5788 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5789 <                            t.result = reducer.apply(t.result, s.result);
5790 <                        }
5791 <                        if ((par = t.parent) == null ||
5792 <                            !(par instanceof MapReduceEntriesToDoubleTask)) {
5793 <                            t.quietlyComplete();
6149 <                            break;
6150 <                        }
6151 <                        t = (MapReduceEntriesToDoubleTask<K,V>)par;
5785 >                CountedCompleter<?> c;
5786 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5787 >                    @SuppressWarnings("unchecked")
5788 >                    MapReduceEntriesToDoubleTask<K,V>
5789 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
5790 >                        s = t.rights;
5791 >                    while (s != null) {
5792 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5793 >                        s = t.rights = s.nextRight;
5794                      }
6153                    else if (t.casPending(c, c - 1))
6154                        break;
5795                  }
6156            } catch (Throwable ex) {
6157                return tryCompleteComputation(ex);
5796              }
6159            MapReduceEntriesToDoubleTask<K,V> s = rights;
6160            if (s != null && !inForkJoinPool()) {
6161                do  {
6162                    if (s.tryUnfork())
6163                        s.exec();
6164                } while ((s = s.nextRight) != null);
6165            }
6166            return false;
5797          }
6168        public final Double getRawResult() { return result; }
5798      }
5799  
5800 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5800 >    @SuppressWarnings("serial")
5801 >    static final class MapReduceMappingsToDoubleTask<K,V>
5802          extends BulkTask<K,V,Double> {
5803 <        final ObjectByObjectToDouble<? super K, ? super V> transformer;
5804 <        final DoubleByDoubleToDouble reducer;
5803 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
5804 >        final DoubleBinaryOperator reducer;
5805          final double basis;
5806          double result;
5807          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5808          MapReduceMappingsToDoubleTask
5809 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5809 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5810               MapReduceMappingsToDoubleTask<K,V> nextRight,
5811 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
5811 >             ToDoubleBiFunction<? super K, ? super V> transformer,
5812               double basis,
5813 <             DoubleByDoubleToDouble reducer) {
5814 <            super(m, p, b); this.nextRight = nextRight;
5813 >             DoubleBinaryOperator reducer) {
5814 >            super(p, b, i, f, t); this.nextRight = nextRight;
5815              this.transformer = transformer;
5816              this.basis = basis; this.reducer = reducer;
5817          }
5818 <        @SuppressWarnings("unchecked") public final boolean exec() {
5819 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
5820 <                this.transformer;
5821 <            final DoubleByDoubleToDouble reducer = this.reducer;
5822 <            if (transformer == null || reducer == null)
5823 <                return abortOnNullFunction();
5824 <            try {
5825 <                final double id = this.basis;
5826 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5827 <                    do {} while (!casPending(c = pending, c+1));
5818 >        public final Double getRawResult() { return result; }
5819 >        public final void compute() {
5820 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
5821 >            final DoubleBinaryOperator reducer;
5822 >            if ((transformer = this.transformer) != null &&
5823 >                (reducer = this.reducer) != null) {
5824 >                double r = this.basis;
5825 >                for (int i = baseIndex, f, h; batch > 0 &&
5826 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5827 >                    addToPendingCount(1);
5828                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5829 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5829 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5830 >                      rights, transformer, r, reducer)).fork();
5831                  }
5832 <                double r = id;
5833 <                Object v;
6203 <                while ((v = advance()) != null)
6204 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5832 >                for (Node<K,V> p; (p = advance()) != null; )
5833 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5834                  result = r;
5835 <                for (MapReduceMappingsToDoubleTask<K,V> t = this, s;;) {
5836 <                    int c; BulkTask<K,V,?> par;
5837 <                    if ((c = t.pending) == 0) {
5838 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5839 <                            t.result = reducer.apply(t.result, s.result);
5840 <                        }
5841 <                        if ((par = t.parent) == null ||
5842 <                            !(par instanceof MapReduceMappingsToDoubleTask)) {
5843 <                            t.quietlyComplete();
6215 <                            break;
6216 <                        }
6217 <                        t = (MapReduceMappingsToDoubleTask<K,V>)par;
5835 >                CountedCompleter<?> c;
5836 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5837 >                    @SuppressWarnings("unchecked")
5838 >                    MapReduceMappingsToDoubleTask<K,V>
5839 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
5840 >                        s = t.rights;
5841 >                    while (s != null) {
5842 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5843 >                        s = t.rights = s.nextRight;
5844                      }
6219                    else if (t.casPending(c, c - 1))
6220                        break;
5845                  }
6222            } catch (Throwable ex) {
6223                return tryCompleteComputation(ex);
6224            }
6225            MapReduceMappingsToDoubleTask<K,V> s = rights;
6226            if (s != null && !inForkJoinPool()) {
6227                do  {
6228                    if (s.tryUnfork())
6229                        s.exec();
6230                } while ((s = s.nextRight) != null);
5846              }
6232            return false;
5847          }
6234        public final Double getRawResult() { return result; }
5848      }
5849  
5850 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5850 >    @SuppressWarnings("serial")
5851 >    static final class MapReduceKeysToLongTask<K,V>
5852          extends BulkTask<K,V,Long> {
5853 <        final ObjectToLong<? super K> transformer;
5854 <        final LongByLongToLong reducer;
5853 >        final ToLongFunction<? super K> transformer;
5854 >        final LongBinaryOperator reducer;
5855          final long basis;
5856          long result;
5857          MapReduceKeysToLongTask<K,V> rights, nextRight;
5858          MapReduceKeysToLongTask
5859 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5859 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5860               MapReduceKeysToLongTask<K,V> nextRight,
5861 <             ObjectToLong<? super K> transformer,
5861 >             ToLongFunction<? super K> transformer,
5862               long basis,
5863 <             LongByLongToLong reducer) {
5864 <            super(m, p, b); this.nextRight = nextRight;
5863 >             LongBinaryOperator reducer) {
5864 >            super(p, b, i, f, t); this.nextRight = nextRight;
5865              this.transformer = transformer;
5866              this.basis = basis; this.reducer = reducer;
5867          }
5868 <        @SuppressWarnings("unchecked") public final boolean exec() {
5869 <            final ObjectToLong<? super K> transformer =
5870 <                this.transformer;
5871 <            final LongByLongToLong reducer = this.reducer;
5872 <            if (transformer == null || reducer == null)
5873 <                return abortOnNullFunction();
5874 <            try {
5875 <                final long id = this.basis;
5876 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5877 <                    do {} while (!casPending(c = pending, c+1));
5868 >        public final Long getRawResult() { return result; }
5869 >        public final void compute() {
5870 >            final ToLongFunction<? super K> transformer;
5871 >            final LongBinaryOperator reducer;
5872 >            if ((transformer = this.transformer) != null &&
5873 >                (reducer = this.reducer) != null) {
5874 >                long r = this.basis;
5875 >                for (int i = baseIndex, f, h; batch > 0 &&
5876 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5877 >                    addToPendingCount(1);
5878                      (rights = new MapReduceKeysToLongTask<K,V>
5879 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5879 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5880 >                      rights, transformer, r, reducer)).fork();
5881                  }
5882 <                long r = id;
5883 <                while (advance() != null)
6269 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5882 >                for (Node<K,V> p; (p = advance()) != null; )
5883 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5884                  result = r;
5885 <                for (MapReduceKeysToLongTask<K,V> t = this, s;;) {
5886 <                    int c; BulkTask<K,V,?> par;
5887 <                    if ((c = t.pending) == 0) {
5888 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5889 <                            t.result = reducer.apply(t.result, s.result);
5890 <                        }
5891 <                        if ((par = t.parent) == null ||
5892 <                            !(par instanceof MapReduceKeysToLongTask)) {
5893 <                            t.quietlyComplete();
6280 <                            break;
6281 <                        }
6282 <                        t = (MapReduceKeysToLongTask<K,V>)par;
5885 >                CountedCompleter<?> c;
5886 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5887 >                    @SuppressWarnings("unchecked")
5888 >                    MapReduceKeysToLongTask<K,V>
5889 >                        t = (MapReduceKeysToLongTask<K,V>)c,
5890 >                        s = t.rights;
5891 >                    while (s != null) {
5892 >                        t.result = reducer.applyAsLong(t.result, s.result);
5893 >                        s = t.rights = s.nextRight;
5894                      }
6284                    else if (t.casPending(c, c - 1))
6285                        break;
5895                  }
6287            } catch (Throwable ex) {
6288                return tryCompleteComputation(ex);
6289            }
6290            MapReduceKeysToLongTask<K,V> s = rights;
6291            if (s != null && !inForkJoinPool()) {
6292                do  {
6293                    if (s.tryUnfork())
6294                        s.exec();
6295                } while ((s = s.nextRight) != null);
5896              }
6297            return false;
5897          }
6299        public final Long getRawResult() { return result; }
5898      }
5899  
5900 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5900 >    @SuppressWarnings("serial")
5901 >    static final class MapReduceValuesToLongTask<K,V>
5902          extends BulkTask<K,V,Long> {
5903 <        final ObjectToLong<? super V> transformer;
5904 <        final LongByLongToLong reducer;
5903 >        final ToLongFunction<? super V> transformer;
5904 >        final LongBinaryOperator reducer;
5905          final long basis;
5906          long result;
5907          MapReduceValuesToLongTask<K,V> rights, nextRight;
5908          MapReduceValuesToLongTask
5909 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5909 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5910               MapReduceValuesToLongTask<K,V> nextRight,
5911 <             ObjectToLong<? super V> transformer,
5911 >             ToLongFunction<? super V> transformer,
5912               long basis,
5913 <             LongByLongToLong reducer) {
5914 <            super(m, p, b); this.nextRight = nextRight;
5913 >             LongBinaryOperator reducer) {
5914 >            super(p, b, i, f, t); this.nextRight = nextRight;
5915              this.transformer = transformer;
5916              this.basis = basis; this.reducer = reducer;
5917          }
5918 <        @SuppressWarnings("unchecked") public final boolean exec() {
5919 <            final ObjectToLong<? super V> transformer =
5920 <                this.transformer;
5921 <            final LongByLongToLong reducer = this.reducer;
5922 <            if (transformer == null || reducer == null)
5923 <                return abortOnNullFunction();
5924 <            try {
5925 <                final long id = this.basis;
5926 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5927 <                    do {} while (!casPending(c = pending, c+1));
5918 >        public final Long getRawResult() { return result; }
5919 >        public final void compute() {
5920 >            final ToLongFunction<? super V> transformer;
5921 >            final LongBinaryOperator reducer;
5922 >            if ((transformer = this.transformer) != null &&
5923 >                (reducer = this.reducer) != null) {
5924 >                long r = this.basis;
5925 >                for (int i = baseIndex, f, h; batch > 0 &&
5926 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5927 >                    addToPendingCount(1);
5928                      (rights = new MapReduceValuesToLongTask<K,V>
5929 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5929 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5930 >                      rights, transformer, r, reducer)).fork();
5931                  }
5932 <                long r = id;
5933 <                Object v;
6334 <                while ((v = advance()) != null)
6335 <                    r = reducer.apply(r, transformer.apply((V)v));
5932 >                for (Node<K,V> p; (p = advance()) != null; )
5933 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5934                  result = r;
5935 <                for (MapReduceValuesToLongTask<K,V> t = this, s;;) {
5936 <                    int c; BulkTask<K,V,?> par;
5937 <                    if ((c = t.pending) == 0) {
5938 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5939 <                            t.result = reducer.apply(t.result, s.result);
5940 <                        }
5941 <                        if ((par = t.parent) == null ||
5942 <                            !(par instanceof MapReduceValuesToLongTask)) {
5943 <                            t.quietlyComplete();
6346 <                            break;
6347 <                        }
6348 <                        t = (MapReduceValuesToLongTask<K,V>)par;
5935 >                CountedCompleter<?> c;
5936 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5937 >                    @SuppressWarnings("unchecked")
5938 >                    MapReduceValuesToLongTask<K,V>
5939 >                        t = (MapReduceValuesToLongTask<K,V>)c,
5940 >                        s = t.rights;
5941 >                    while (s != null) {
5942 >                        t.result = reducer.applyAsLong(t.result, s.result);
5943 >                        s = t.rights = s.nextRight;
5944                      }
6350                    else if (t.casPending(c, c - 1))
6351                        break;
5945                  }
6353            } catch (Throwable ex) {
6354                return tryCompleteComputation(ex);
5946              }
6356            MapReduceValuesToLongTask<K,V> s = rights;
6357            if (s != null && !inForkJoinPool()) {
6358                do  {
6359                    if (s.tryUnfork())
6360                        s.exec();
6361                } while ((s = s.nextRight) != null);
6362            }
6363            return false;
5947          }
6365        public final Long getRawResult() { return result; }
5948      }
5949  
5950 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5950 >    @SuppressWarnings("serial")
5951 >    static final class MapReduceEntriesToLongTask<K,V>
5952          extends BulkTask<K,V,Long> {
5953 <        final ObjectToLong<Map.Entry<K,V>> transformer;
5954 <        final LongByLongToLong reducer;
5953 >        final ToLongFunction<Map.Entry<K,V>> transformer;
5954 >        final LongBinaryOperator reducer;
5955          final long basis;
5956          long result;
5957          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5958          MapReduceEntriesToLongTask
5959 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5959 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5960               MapReduceEntriesToLongTask<K,V> nextRight,
5961 <             ObjectToLong<Map.Entry<K,V>> transformer,
5961 >             ToLongFunction<Map.Entry<K,V>> transformer,
5962               long basis,
5963 <             LongByLongToLong reducer) {
5964 <            super(m, p, b); this.nextRight = nextRight;
5963 >             LongBinaryOperator reducer) {
5964 >            super(p, b, i, f, t); this.nextRight = nextRight;
5965              this.transformer = transformer;
5966              this.basis = basis; this.reducer = reducer;
5967          }
5968 <        @SuppressWarnings("unchecked") public final boolean exec() {
5969 <            final ObjectToLong<Map.Entry<K,V>> transformer =
5970 <                this.transformer;
5971 <            final LongByLongToLong reducer = this.reducer;
5972 <            if (transformer == null || reducer == null)
5973 <                return abortOnNullFunction();
5974 <            try {
5975 <                final long id = this.basis;
5976 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5977 <                    do {} while (!casPending(c = pending, c+1));
5968 >        public final Long getRawResult() { return result; }
5969 >        public final void compute() {
5970 >            final ToLongFunction<Map.Entry<K,V>> transformer;
5971 >            final LongBinaryOperator reducer;
5972 >            if ((transformer = this.transformer) != null &&
5973 >                (reducer = this.reducer) != null) {
5974 >                long r = this.basis;
5975 >                for (int i = baseIndex, f, h; batch > 0 &&
5976 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5977 >                    addToPendingCount(1);
5978                      (rights = new MapReduceEntriesToLongTask<K,V>
5979 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5979 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5980 >                      rights, transformer, r, reducer)).fork();
5981                  }
5982 <                long r = id;
5983 <                Object v;
6400 <                while ((v = advance()) != null)
6401 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5982 >                for (Node<K,V> p; (p = advance()) != null; )
5983 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
5984                  result = r;
5985 <                for (MapReduceEntriesToLongTask<K,V> t = this, s;;) {
5986 <                    int c; BulkTask<K,V,?> par;
5987 <                    if ((c = t.pending) == 0) {
5988 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5989 <                            t.result = reducer.apply(t.result, s.result);
5990 <                        }
5991 <                        if ((par = t.parent) == null ||
5992 <                            !(par instanceof MapReduceEntriesToLongTask)) {
5993 <                            t.quietlyComplete();
6412 <                            break;
6413 <                        }
6414 <                        t = (MapReduceEntriesToLongTask<K,V>)par;
5985 >                CountedCompleter<?> c;
5986 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5987 >                    @SuppressWarnings("unchecked")
5988 >                    MapReduceEntriesToLongTask<K,V>
5989 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
5990 >                        s = t.rights;
5991 >                    while (s != null) {
5992 >                        t.result = reducer.applyAsLong(t.result, s.result);
5993 >                        s = t.rights = s.nextRight;
5994                      }
6416                    else if (t.casPending(c, c - 1))
6417                        break;
5995                  }
6419            } catch (Throwable ex) {
6420                return tryCompleteComputation(ex);
5996              }
6422            MapReduceEntriesToLongTask<K,V> s = rights;
6423            if (s != null && !inForkJoinPool()) {
6424                do  {
6425                    if (s.tryUnfork())
6426                        s.exec();
6427                } while ((s = s.nextRight) != null);
6428            }
6429            return false;
5997          }
6431        public final Long getRawResult() { return result; }
5998      }
5999  
6000 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6000 >    @SuppressWarnings("serial")
6001 >    static final class MapReduceMappingsToLongTask<K,V>
6002          extends BulkTask<K,V,Long> {
6003 <        final ObjectByObjectToLong<? super K, ? super V> transformer;
6004 <        final LongByLongToLong reducer;
6003 >        final ToLongBiFunction<? super K, ? super V> transformer;
6004 >        final LongBinaryOperator reducer;
6005          final long basis;
6006          long result;
6007          MapReduceMappingsToLongTask<K,V> rights, nextRight;
6008          MapReduceMappingsToLongTask
6009 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6009 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6010               MapReduceMappingsToLongTask<K,V> nextRight,
6011 <             ObjectByObjectToLong<? super K, ? super V> transformer,
6011 >             ToLongBiFunction<? super K, ? super V> transformer,
6012               long basis,
6013 <             LongByLongToLong reducer) {
6014 <            super(m, p, b); this.nextRight = nextRight;
6013 >             LongBinaryOperator reducer) {
6014 >            super(p, b, i, f, t); this.nextRight = nextRight;
6015              this.transformer = transformer;
6016              this.basis = basis; this.reducer = reducer;
6017          }
6018 <        @SuppressWarnings("unchecked") public final boolean exec() {
6019 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
6020 <                this.transformer;
6021 <            final LongByLongToLong reducer = this.reducer;
6022 <            if (transformer == null || reducer == null)
6023 <                return abortOnNullFunction();
6024 <            try {
6025 <                final long id = this.basis;
6026 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6027 <                    do {} while (!casPending(c = pending, c+1));
6018 >        public final Long getRawResult() { return result; }
6019 >        public final void compute() {
6020 >            final ToLongBiFunction<? super K, ? super V> transformer;
6021 >            final LongBinaryOperator reducer;
6022 >            if ((transformer = this.transformer) != null &&
6023 >                (reducer = this.reducer) != null) {
6024 >                long r = this.basis;
6025 >                for (int i = baseIndex, f, h; batch > 0 &&
6026 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6027 >                    addToPendingCount(1);
6028                      (rights = new MapReduceMappingsToLongTask<K,V>
6029 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6029 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6030 >                      rights, transformer, r, reducer)).fork();
6031                  }
6032 <                long r = id;
6033 <                Object v;
6466 <                while ((v = advance()) != null)
6467 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6032 >                for (Node<K,V> p; (p = advance()) != null; )
6033 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
6034                  result = r;
6035 <                for (MapReduceMappingsToLongTask<K,V> t = this, s;;) {
6036 <                    int c; BulkTask<K,V,?> par;
6037 <                    if ((c = t.pending) == 0) {
6038 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6039 <                            t.result = reducer.apply(t.result, s.result);
6040 <                        }
6041 <                        if ((par = t.parent) == null ||
6042 <                            !(par instanceof MapReduceMappingsToLongTask)) {
6043 <                            t.quietlyComplete();
6478 <                            break;
6479 <                        }
6480 <                        t = (MapReduceMappingsToLongTask<K,V>)par;
6035 >                CountedCompleter<?> c;
6036 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6037 >                    @SuppressWarnings("unchecked")
6038 >                    MapReduceMappingsToLongTask<K,V>
6039 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
6040 >                        s = t.rights;
6041 >                    while (s != null) {
6042 >                        t.result = reducer.applyAsLong(t.result, s.result);
6043 >                        s = t.rights = s.nextRight;
6044                      }
6482                    else if (t.casPending(c, c - 1))
6483                        break;
6045                  }
6485            } catch (Throwable ex) {
6486                return tryCompleteComputation(ex);
6487            }
6488            MapReduceMappingsToLongTask<K,V> s = rights;
6489            if (s != null && !inForkJoinPool()) {
6490                do  {
6491                    if (s.tryUnfork())
6492                        s.exec();
6493                } while ((s = s.nextRight) != null);
6046              }
6495            return false;
6047          }
6497        public final Long getRawResult() { return result; }
6048      }
6049  
6050 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6050 >    @SuppressWarnings("serial")
6051 >    static final class MapReduceKeysToIntTask<K,V>
6052          extends BulkTask<K,V,Integer> {
6053 <        final ObjectToInt<? super K> transformer;
6054 <        final IntByIntToInt reducer;
6053 >        final ToIntFunction<? super K> transformer;
6054 >        final IntBinaryOperator reducer;
6055          final int basis;
6056          int result;
6057          MapReduceKeysToIntTask<K,V> rights, nextRight;
6058          MapReduceKeysToIntTask
6059 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6059 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6060               MapReduceKeysToIntTask<K,V> nextRight,
6061 <             ObjectToInt<? super K> transformer,
6061 >             ToIntFunction<? super K> transformer,
6062               int basis,
6063 <             IntByIntToInt reducer) {
6064 <            super(m, p, b); this.nextRight = nextRight;
6063 >             IntBinaryOperator reducer) {
6064 >            super(p, b, i, f, t); this.nextRight = nextRight;
6065              this.transformer = transformer;
6066              this.basis = basis; this.reducer = reducer;
6067          }
6068 <        @SuppressWarnings("unchecked") public final boolean exec() {
6069 <            final ObjectToInt<? super K> transformer =
6070 <                this.transformer;
6071 <            final IntByIntToInt reducer = this.reducer;
6072 <            if (transformer == null || reducer == null)
6073 <                return abortOnNullFunction();
6074 <            try {
6075 <                final int id = this.basis;
6076 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6077 <                    do {} while (!casPending(c = pending, c+1));
6068 >        public final Integer getRawResult() { return result; }
6069 >        public final void compute() {
6070 >            final ToIntFunction<? super K> transformer;
6071 >            final IntBinaryOperator reducer;
6072 >            if ((transformer = this.transformer) != null &&
6073 >                (reducer = this.reducer) != null) {
6074 >                int r = this.basis;
6075 >                for (int i = baseIndex, f, h; batch > 0 &&
6076 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6077 >                    addToPendingCount(1);
6078                      (rights = new MapReduceKeysToIntTask<K,V>
6079 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6079 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6080 >                      rights, transformer, r, reducer)).fork();
6081                  }
6082 <                int r = id;
6083 <                while (advance() != null)
6532 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
6082 >                for (Node<K,V> p; (p = advance()) != null; )
6083 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
6084                  result = r;
6085 <                for (MapReduceKeysToIntTask<K,V> t = this, s;;) {
6086 <                    int c; BulkTask<K,V,?> par;
6087 <                    if ((c = t.pending) == 0) {
6088 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6089 <                            t.result = reducer.apply(t.result, s.result);
6090 <                        }
6091 <                        if ((par = t.parent) == null ||
6092 <                            !(par instanceof MapReduceKeysToIntTask)) {
6093 <                            t.quietlyComplete();
6543 <                            break;
6544 <                        }
6545 <                        t = (MapReduceKeysToIntTask<K,V>)par;
6085 >                CountedCompleter<?> c;
6086 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6087 >                    @SuppressWarnings("unchecked")
6088 >                    MapReduceKeysToIntTask<K,V>
6089 >                        t = (MapReduceKeysToIntTask<K,V>)c,
6090 >                        s = t.rights;
6091 >                    while (s != null) {
6092 >                        t.result = reducer.applyAsInt(t.result, s.result);
6093 >                        s = t.rights = s.nextRight;
6094                      }
6547                    else if (t.casPending(c, c - 1))
6548                        break;
6095                  }
6550            } catch (Throwable ex) {
6551                return tryCompleteComputation(ex);
6552            }
6553            MapReduceKeysToIntTask<K,V> s = rights;
6554            if (s != null && !inForkJoinPool()) {
6555                do  {
6556                    if (s.tryUnfork())
6557                        s.exec();
6558                } while ((s = s.nextRight) != null);
6096              }
6560            return false;
6097          }
6562        public final Integer getRawResult() { return result; }
6098      }
6099  
6100 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6100 >    @SuppressWarnings("serial")
6101 >    static final class MapReduceValuesToIntTask<K,V>
6102          extends BulkTask<K,V,Integer> {
6103 <        final ObjectToInt<? super V> transformer;
6104 <        final IntByIntToInt reducer;
6103 >        final ToIntFunction<? super V> transformer;
6104 >        final IntBinaryOperator reducer;
6105          final int basis;
6106          int result;
6107          MapReduceValuesToIntTask<K,V> rights, nextRight;
6108          MapReduceValuesToIntTask
6109 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6109 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6110               MapReduceValuesToIntTask<K,V> nextRight,
6111 <             ObjectToInt<? super V> transformer,
6111 >             ToIntFunction<? super V> transformer,
6112               int basis,
6113 <             IntByIntToInt reducer) {
6114 <            super(m, p, b); this.nextRight = nextRight;
6113 >             IntBinaryOperator reducer) {
6114 >            super(p, b, i, f, t); this.nextRight = nextRight;
6115              this.transformer = transformer;
6116              this.basis = basis; this.reducer = reducer;
6117          }
6118 <        @SuppressWarnings("unchecked") public final boolean exec() {
6119 <            final ObjectToInt<? super V> transformer =
6120 <                this.transformer;
6121 <            final IntByIntToInt reducer = this.reducer;
6122 <            if (transformer == null || reducer == null)
6123 <                return abortOnNullFunction();
6124 <            try {
6125 <                final int id = this.basis;
6126 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6127 <                    do {} while (!casPending(c = pending, c+1));
6118 >        public final Integer getRawResult() { return result; }
6119 >        public final void compute() {
6120 >            final ToIntFunction<? super V> transformer;
6121 >            final IntBinaryOperator reducer;
6122 >            if ((transformer = this.transformer) != null &&
6123 >                (reducer = this.reducer) != null) {
6124 >                int r = this.basis;
6125 >                for (int i = baseIndex, f, h; batch > 0 &&
6126 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6127 >                    addToPendingCount(1);
6128                      (rights = new MapReduceValuesToIntTask<K,V>
6129 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6129 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6130 >                      rights, transformer, r, reducer)).fork();
6131                  }
6132 <                int r = id;
6133 <                Object v;
6597 <                while ((v = advance()) != null)
6598 <                    r = reducer.apply(r, transformer.apply((V)v));
6132 >                for (Node<K,V> p; (p = advance()) != null; )
6133 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
6134                  result = r;
6135 <                for (MapReduceValuesToIntTask<K,V> t = this, s;;) {
6136 <                    int c; BulkTask<K,V,?> par;
6137 <                    if ((c = t.pending) == 0) {
6138 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6139 <                            t.result = reducer.apply(t.result, s.result);
6140 <                        }
6141 <                        if ((par = t.parent) == null ||
6142 <                            !(par instanceof MapReduceValuesToIntTask)) {
6143 <                            t.quietlyComplete();
6609 <                            break;
6610 <                        }
6611 <                        t = (MapReduceValuesToIntTask<K,V>)par;
6135 >                CountedCompleter<?> c;
6136 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6137 >                    @SuppressWarnings("unchecked")
6138 >                    MapReduceValuesToIntTask<K,V>
6139 >                        t = (MapReduceValuesToIntTask<K,V>)c,
6140 >                        s = t.rights;
6141 >                    while (s != null) {
6142 >                        t.result = reducer.applyAsInt(t.result, s.result);
6143 >                        s = t.rights = s.nextRight;
6144                      }
6613                    else if (t.casPending(c, c - 1))
6614                        break;
6145                  }
6616            } catch (Throwable ex) {
6617                return tryCompleteComputation(ex);
6146              }
6619            MapReduceValuesToIntTask<K,V> s = rights;
6620            if (s != null && !inForkJoinPool()) {
6621                do  {
6622                    if (s.tryUnfork())
6623                        s.exec();
6624                } while ((s = s.nextRight) != null);
6625            }
6626            return false;
6147          }
6628        public final Integer getRawResult() { return result; }
6148      }
6149  
6150 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6150 >    @SuppressWarnings("serial")
6151 >    static final class MapReduceEntriesToIntTask<K,V>
6152          extends BulkTask<K,V,Integer> {
6153 <        final ObjectToInt<Map.Entry<K,V>> transformer;
6154 <        final IntByIntToInt reducer;
6153 >        final ToIntFunction<Map.Entry<K,V>> transformer;
6154 >        final IntBinaryOperator reducer;
6155          final int basis;
6156          int result;
6157          MapReduceEntriesToIntTask<K,V> rights, nextRight;
6158          MapReduceEntriesToIntTask
6159 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6159 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6160               MapReduceEntriesToIntTask<K,V> nextRight,
6161 <             ObjectToInt<Map.Entry<K,V>> transformer,
6161 >             ToIntFunction<Map.Entry<K,V>> transformer,
6162               int basis,
6163 <             IntByIntToInt reducer) {
6164 <            super(m, p, b); this.nextRight = nextRight;
6163 >             IntBinaryOperator reducer) {
6164 >            super(p, b, i, f, t); this.nextRight = nextRight;
6165              this.transformer = transformer;
6166              this.basis = basis; this.reducer = reducer;
6167          }
6168 <        @SuppressWarnings("unchecked") public final boolean exec() {
6169 <            final ObjectToInt<Map.Entry<K,V>> transformer =
6170 <                this.transformer;
6171 <            final IntByIntToInt reducer = this.reducer;
6172 <            if (transformer == null || reducer == null)
6173 <                return abortOnNullFunction();
6174 <            try {
6175 <                final int id = this.basis;
6176 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6177 <                    do {} while (!casPending(c = pending, c+1));
6168 >        public final Integer getRawResult() { return result; }
6169 >        public final void compute() {
6170 >            final ToIntFunction<Map.Entry<K,V>> transformer;
6171 >            final IntBinaryOperator reducer;
6172 >            if ((transformer = this.transformer) != null &&
6173 >                (reducer = this.reducer) != null) {
6174 >                int r = this.basis;
6175 >                for (int i = baseIndex, f, h; batch > 0 &&
6176 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6177 >                    addToPendingCount(1);
6178                      (rights = new MapReduceEntriesToIntTask<K,V>
6179 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6179 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6180 >                      rights, transformer, r, reducer)).fork();
6181                  }
6182 <                int r = id;
6183 <                Object v;
6663 <                while ((v = advance()) != null)
6664 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6182 >                for (Node<K,V> p; (p = advance()) != null; )
6183 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
6184                  result = r;
6185 <                for (MapReduceEntriesToIntTask<K,V> t = this, s;;) {
6186 <                    int c; BulkTask<K,V,?> par;
6187 <                    if ((c = t.pending) == 0) {
6188 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6189 <                            t.result = reducer.apply(t.result, s.result);
6190 <                        }
6191 <                        if ((par = t.parent) == null ||
6192 <                            !(par instanceof MapReduceEntriesToIntTask)) {
6193 <                            t.quietlyComplete();
6675 <                            break;
6676 <                        }
6677 <                        t = (MapReduceEntriesToIntTask<K,V>)par;
6185 >                CountedCompleter<?> c;
6186 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6187 >                    @SuppressWarnings("unchecked")
6188 >                    MapReduceEntriesToIntTask<K,V>
6189 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
6190 >                        s = t.rights;
6191 >                    while (s != null) {
6192 >                        t.result = reducer.applyAsInt(t.result, s.result);
6193 >                        s = t.rights = s.nextRight;
6194                      }
6679                    else if (t.casPending(c, c - 1))
6680                        break;
6195                  }
6682            } catch (Throwable ex) {
6683                return tryCompleteComputation(ex);
6684            }
6685            MapReduceEntriesToIntTask<K,V> s = rights;
6686            if (s != null && !inForkJoinPool()) {
6687                do  {
6688                    if (s.tryUnfork())
6689                        s.exec();
6690                } while ((s = s.nextRight) != null);
6196              }
6692            return false;
6197          }
6694        public final Integer getRawResult() { return result; }
6198      }
6199  
6200 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6200 >    @SuppressWarnings("serial")
6201 >    static final class MapReduceMappingsToIntTask<K,V>
6202          extends BulkTask<K,V,Integer> {
6203 <        final ObjectByObjectToInt<? super K, ? super V> transformer;
6204 <        final IntByIntToInt reducer;
6203 >        final ToIntBiFunction<? super K, ? super V> transformer;
6204 >        final IntBinaryOperator reducer;
6205          final int basis;
6206          int result;
6207          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6208          MapReduceMappingsToIntTask
6209 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6210 <             MapReduceMappingsToIntTask<K,V> rights,
6211 <             ObjectByObjectToInt<? super K, ? super V> transformer,
6209 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6210 >             MapReduceMappingsToIntTask<K,V> nextRight,
6211 >             ToIntBiFunction<? super K, ? super V> transformer,
6212               int basis,
6213 <             IntByIntToInt reducer) {
6214 <            super(m, p, b); this.nextRight = nextRight;
6213 >             IntBinaryOperator reducer) {
6214 >            super(p, b, i, f, t); this.nextRight = nextRight;
6215              this.transformer = transformer;
6216              this.basis = basis; this.reducer = reducer;
6217          }
6218 <        @SuppressWarnings("unchecked") public final boolean exec() {
6219 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
6220 <                this.transformer;
6221 <            final IntByIntToInt reducer = this.reducer;
6222 <            if (transformer == null || reducer == null)
6223 <                return abortOnNullFunction();
6224 <            try {
6225 <                final int id = this.basis;
6226 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6227 <                    do {} while (!casPending(c = pending, c+1));
6218 >        public final Integer getRawResult() { return result; }
6219 >        public final void compute() {
6220 >            final ToIntBiFunction<? super K, ? super V> transformer;
6221 >            final IntBinaryOperator reducer;
6222 >            if ((transformer = this.transformer) != null &&
6223 >                (reducer = this.reducer) != null) {
6224 >                int r = this.basis;
6225 >                for (int i = baseIndex, f, h; batch > 0 &&
6226 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6227 >                    addToPendingCount(1);
6228                      (rights = new MapReduceMappingsToIntTask<K,V>
6229 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6229 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6230 >                      rights, transformer, r, reducer)).fork();
6231                  }
6232 <                int r = id;
6233 <                Object v;
6729 <                while ((v = advance()) != null)
6730 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6232 >                for (Node<K,V> p; (p = advance()) != null; )
6233 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6234                  result = r;
6235 <                for (MapReduceMappingsToIntTask<K,V> t = this, s;;) {
6236 <                    int c; BulkTask<K,V,?> par;
6237 <                    if ((c = t.pending) == 0) {
6238 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6239 <                            t.result = reducer.apply(t.result, s.result);
6240 <                        }
6241 <                        if ((par = t.parent) == null ||
6242 <                            !(par instanceof MapReduceMappingsToIntTask)) {
6243 <                            t.quietlyComplete();
6741 <                            break;
6742 <                        }
6743 <                        t = (MapReduceMappingsToIntTask<K,V>)par;
6235 >                CountedCompleter<?> c;
6236 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6237 >                    @SuppressWarnings("unchecked")
6238 >                    MapReduceMappingsToIntTask<K,V>
6239 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6240 >                        s = t.rights;
6241 >                    while (s != null) {
6242 >                        t.result = reducer.applyAsInt(t.result, s.result);
6243 >                        s = t.rights = s.nextRight;
6244                      }
6745                    else if (t.casPending(c, c - 1))
6746                        break;
6245                  }
6748            } catch (Throwable ex) {
6749                return tryCompleteComputation(ex);
6750            }
6751            MapReduceMappingsToIntTask<K,V> s = rights;
6752            if (s != null && !inForkJoinPool()) {
6753                do  {
6754                    if (s.tryUnfork())
6755                        s.exec();
6756                } while ((s = s.nextRight) != null);
6246              }
6758            return false;
6247          }
6760        public final Integer getRawResult() { return result; }
6248      }
6249  
6250      // Unsafe mechanics
6251 <    private static final sun.misc.Unsafe UNSAFE;
6252 <    private static final long counterOffset;
6253 <    private static final long sizeCtlOffset;
6251 >    private static final sun.misc.Unsafe U;
6252 >    private static final long SIZECTL;
6253 >    private static final long TRANSFERINDEX;
6254 >    private static final long BASECOUNT;
6255 >    private static final long CELLSBUSY;
6256 >    private static final long CELLVALUE;
6257      private static final long ABASE;
6258      private static final int ASHIFT;
6259  
6260      static {
6771        int ss;
6261          try {
6262 <            UNSAFE = sun.misc.Unsafe.getUnsafe();
6262 >            U = sun.misc.Unsafe.getUnsafe();
6263              Class<?> k = ConcurrentHashMap.class;
6264 <            counterOffset = UNSAFE.objectFieldOffset
6776 <                (k.getDeclaredField("counter"));
6777 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6264 >            SIZECTL = U.objectFieldOffset
6265                  (k.getDeclaredField("sizeCtl"));
6266 <            Class<?> sc = Node[].class;
6267 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6268 <            ss = UNSAFE.arrayIndexScale(sc);
6266 >            TRANSFERINDEX = U.objectFieldOffset
6267 >                (k.getDeclaredField("transferIndex"));
6268 >            BASECOUNT = U.objectFieldOffset
6269 >                (k.getDeclaredField("baseCount"));
6270 >            CELLSBUSY = U.objectFieldOffset
6271 >                (k.getDeclaredField("cellsBusy"));
6272 >            Class<?> ck = CounterCell.class;
6273 >            CELLVALUE = U.objectFieldOffset
6274 >                (ck.getDeclaredField("value"));
6275 >            Class<?> ak = Node[].class;
6276 >            ABASE = U.arrayBaseOffset(ak);
6277 >            int scale = U.arrayIndexScale(ak);
6278 >            if ((scale & (scale - 1)) != 0)
6279 >                throw new Error("data type scale not a power of two");
6280 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6281          } catch (Exception e) {
6282              throw new Error(e);
6283          }
6785        if ((ss & (ss-1)) != 0)
6786            throw new Error("data type scale not a power of two");
6787        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6284      }
6285   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines