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.140 by jsr166, Tue Oct 30 16:46:09 2012 UTC vs.
Revision 1.278 by jsr166, Sat Sep 12 21:55:08 2015 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;
18 < import java.util.AbstractSet;
19 < import java.util.AbstractCollection;
20 < import java.util.Hashtable;
16 > import java.util.Enumeration;
17   import java.util.HashMap;
18 + import java.util.Hashtable;
19   import java.util.Iterator;
20 < import java.util.Enumeration;
24 < import java.util.ConcurrentModificationException;
20 > import java.util.Map;
21   import java.util.NoSuchElementException;
22 < import java.util.concurrent.ConcurrentMap;
23 < import java.util.concurrent.ThreadLocalRandom;
28 < import java.util.concurrent.locks.LockSupport;
29 < import java.util.concurrent.locks.AbstractQueuedSynchronizer;
22 > import java.util.Set;
23 > import java.util.Spliterator;
24   import java.util.concurrent.atomic.AtomicReference;
25 <
26 < import java.io.Serializable;
25 > import java.util.concurrent.locks.LockSupport;
26 > import java.util.concurrent.locks.ReentrantLock;
27 > import java.util.function.BiConsumer;
28 > import java.util.function.BiFunction;
29 > import java.util.function.Consumer;
30 > import java.util.function.DoubleBinaryOperator;
31 > import java.util.function.Function;
32 > import java.util.function.IntBinaryOperator;
33 > import java.util.function.LongBinaryOperator;
34 > import java.util.function.Predicate;
35 > import java.util.function.ToDoubleBiFunction;
36 > import java.util.function.ToDoubleFunction;
37 > import java.util.function.ToIntBiFunction;
38 > import java.util.function.ToIntFunction;
39 > import java.util.function.ToLongBiFunction;
40 > import java.util.function.ToLongFunction;
41 > import java.util.stream.Stream;
42  
43   /**
44   * A hash table supporting full concurrency of retrievals and
# Line 43 | Line 52 | import java.io.Serializable;
52   * interoperable with {@code Hashtable} in programs that rely on its
53   * thread safety but not on its synchronization details.
54   *
55 < * <p> Retrieval operations (including {@code get}) generally do not
55 > * <p>Retrieval operations (including {@code get}) generally do not
56   * block, so may overlap with update operations (including {@code put}
57   * and {@code remove}). Retrievals reflect the results of the most
58   * recently <em>completed</em> update operations holding upon their
# Line 52 | Line 61 | import java.io.Serializable;
61   * that key reporting the updated value.)  For aggregate operations
62   * such as {@code putAll} and {@code clear}, concurrent retrievals may
63   * reflect insertion or removal of only some entries.  Similarly,
64 < * Iterators and Enumerations return elements reflecting the state of
65 < * the hash table at some point at or since the creation of the
64 > * Iterators, Spliterators and Enumerations return elements reflecting the
65 > * state of the hash table at some point at or since the creation of the
66   * iterator/enumeration.  They do <em>not</em> throw {@link
67 < * ConcurrentModificationException}.  However, iterators are designed
68 < * to be used by only one thread at a time.  Bear in mind that the
69 < * results of aggregate status methods including {@code size}, {@code
70 < * isEmpty}, and {@code containsValue} are typically useful only when
71 < * a map is not undergoing concurrent updates in other threads.
67 > * java.util.ConcurrentModificationException ConcurrentModificationException}.
68 > * However, iterators are designed to be used by only one thread at a time.
69 > * Bear in mind that the results of aggregate status methods including
70 > * {@code size}, {@code isEmpty}, and {@code containsValue} are typically
71 > * useful only when a map is not undergoing concurrent updates in other threads.
72   * Otherwise the results of these methods reflect transient states
73   * that may be adequate for monitoring or estimation purposes, but not
74   * for program control.
75   *
76 < * <p> The table is dynamically expanded when there are too many
76 > * <p>The table is dynamically expanded when there are too many
77   * collisions (i.e., keys that have distinct hash codes but fall into
78   * the same slot modulo the table size), with the expected average
79   * effect of maintaining roughly two bins per mapping (corresponding
# Line 83 | Line 92 | import java.io.Serializable;
92   * expected {@code concurrencyLevel} as an additional hint for
93   * internal sizing.  Note that using many keys with exactly the same
94   * {@code hashCode()} is a sure way to slow down performance of any
95 < * hash table.
95 > * hash table. To ameliorate impact, when keys are {@link Comparable},
96 > * this class may use comparison order among keys to help break ties.
97   *
98 < * <p> A {@link Set} projection of a ConcurrentHashMap may be created
98 > * <p>A {@link Set} projection of a ConcurrentHashMap may be created
99   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
100   * (using {@link #keySet(Object)} when only keys are of interest, and the
101   * mapped values are (perhaps transiently) not used or all take the
102   * same mapping value.
103   *
104 < * <p> A ConcurrentHashMap can be used as scalable frequency map (a
105 < * form of histogram or multiset) by using {@link LongAdder} values
106 < * and initializing via {@link #computeIfAbsent}. For example, to add
107 < * a count to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you
108 < * can use {@code freqs.computeIfAbsent(k -> new
109 < * LongAdder()).increment();}
104 > * <p>A ConcurrentHashMap can be used as a scalable frequency map (a
105 > * form of histogram or multiset) by using {@link
106 > * java.util.concurrent.atomic.LongAdder} values and initializing via
107 > * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count
108 > * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
109 > * {@code freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}
110   *
111   * <p>This class and its views and iterators implement all of the
112   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
113   * interfaces.
114   *
115 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
115 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
116   * does <em>not</em> allow {@code null} to be used as a key or value.
117   *
118 < * <p>ConcurrentHashMaps support parallel operations using the {@link
119 < * ForkJoinPool#commonPool}. (Tasks that may be used in other contexts
120 < * are available in class {@link ForkJoinTasks}). These operations are
121 < * designed to be safely, and often sensibly, applied even with maps
122 < * that are being concurrently updated by other threads; for example,
123 < * when computing a snapshot summary of the values in a shared
124 < * registry.  There are three kinds of operation, each with four
125 < * forms, accepting functions with Keys, Values, Entries, and (Key,
116 < * Value) arguments and/or return values. Because the elements of a
118 > * <p>ConcurrentHashMaps support a set of sequential and parallel bulk
119 > * operations that, unlike most {@link Stream} methods, are designed
120 > * to be safely, and often sensibly, applied even with maps that are
121 > * being concurrently updated by other threads; for example, when
122 > * computing a snapshot summary of the values in a shared registry.
123 > * There are three kinds of operation, each with four forms, accepting
124 > * functions with keys, values, entries, and (key, value) pairs as
125 > * arguments and/or return values. Because the elements of a
126   * ConcurrentHashMap are not ordered in any particular way, and may be
127   * processed in different orders in different parallel executions, the
128   * correctness of supplied functions should not depend on any
129   * ordering, or on any other objects or values that may transiently
130   * change while computation is in progress; and except for forEach
131 < * actions, should ideally be side-effect-free.
131 > * actions, should ideally be side-effect-free. Bulk operations on
132 > * {@link java.util.Map.Entry} objects do not support method {@code
133 > * setValue}.
134   *
135   * <ul>
136   * <li> forEach: Perform a given action on each element.
# Line 146 | Line 157 | import java.io.Serializable;
157   * <li> Reductions to scalar doubles, longs, and ints, using a
158   * given basis value.</li>
159   *
149 * </li>
160   * </ul>
161 + * </li>
162   * </ul>
163   *
164 + * <p>These bulk operations accept a {@code parallelismThreshold}
165 + * argument. Methods proceed sequentially if the current map size is
166 + * estimated to be less than the given threshold. Using a value of
167 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
168 + * of {@code 1} results in maximal parallelism by partitioning into
169 + * enough subtasks to fully utilize the {@link
170 + * ForkJoinPool#commonPool()} that is used for all parallel
171 + * computations. Normally, you would initially choose one of these
172 + * extreme values, and then measure performance of using in-between
173 + * values that trade off overhead versus throughput.
174 + *
175   * <p>The concurrency properties of bulk operations follow
176   * from those of ConcurrentHashMap: Any non-null result returned
177   * from {@code get(key)} and related access methods bears a
# Line 185 | Line 207 | import java.io.Serializable;
207   * arguments can be supplied using {@code new
208   * AbstractMap.SimpleEntry(k,v)}.
209   *
210 < * <p> Bulk operations may complete abruptly, throwing an
210 > * <p>Bulk operations may complete abruptly, throwing an
211   * exception encountered in the application of a supplied
212   * function. Bear in mind when handling such exceptions that other
213   * concurrently executing functions could also have thrown
214   * exceptions, or would have done so if the first exception had
215   * not occurred.
216   *
217 < * <p>Parallel speedups for bulk operations compared to sequential
218 < * processing are common but not guaranteed.  Operations involving
219 < * brief functions on small maps may execute more slowly than
220 < * sequential loops if the underlying work to parallelize the
221 < * computation is more expensive than the computation
222 < * itself. Similarly, parallelization may not lead to much actual
223 < * parallelism if all processors are busy performing unrelated tasks.
202 < *
203 < * <p> All arguments to all task methods must be non-null.
217 > * <p>Speedups for parallel compared to sequential forms are common
218 > * but not guaranteed.  Parallel operations involving brief functions
219 > * on small maps may execute more slowly than sequential forms if the
220 > * underlying work to parallelize the computation is more expensive
221 > * than the computation itself.  Similarly, parallelization may not
222 > * lead to much actual parallelism if all processors are busy
223 > * performing unrelated tasks.
224   *
225 < * <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>
225 > * <p>All arguments to all task methods must be non-null.
226   *
227   * <p>This class is a member of the
228   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
# Line 215 | Line 233 | import java.io.Serializable;
233   * @param <K> the type of keys maintained by this map
234   * @param <V> the type of mapped values
235   */
236 < public class ConcurrentHashMap<K, V>
237 <    implements ConcurrentMap<K, V>, Serializable {
236 > public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
237 >    implements ConcurrentMap<K,V>, Serializable {
238      private static final long serialVersionUID = 7249069246763182397L;
239  
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
240      /*
241       * Overview:
242       *
# Line 369 | Line 247 | public class ConcurrentHashMap<K, V>
247       * the same or better than java.util.HashMap, and to support high
248       * initial insertion rates on an empty table by many threads.
249       *
250 <     * Each key-value mapping is held in a Node.  Because Node fields
251 <     * can contain special values, they are defined using plain Object
252 <     * types. Similarly in turn, all internal methods that use them
253 <     * work off Object types. And similarly, so do the internal
254 <     * methods of auxiliary iterator and view classes.  All public
255 <     * generic typed methods relay in/out of these internal methods,
256 <     * supplying null-checks and casts as needed. This also allows
257 <     * many of the public methods to be factored into a smaller number
258 <     * of internal methods (although sadly not so for the five
259 <     * variants of put-related operations). The validation-based
260 <     * approach explained below leads to a lot of code sprawl because
261 <     * retry-control precludes factoring into smaller methods.
250 >     * This map usually acts as a binned (bucketed) hash table.  Each
251 >     * key-value mapping is held in a Node.  Most nodes are instances
252 >     * of the basic Node class with hash, key, value, and next
253 >     * fields. However, various subclasses exist: TreeNodes are
254 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
255 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
256 >     * of bins during resizing. ReservationNodes are used as
257 >     * placeholders while establishing values in computeIfAbsent and
258 >     * related methods.  The types TreeBin, ForwardingNode, and
259 >     * ReservationNode do not hold normal user keys, values, or
260 >     * hashes, and are readily distinguishable during search etc
261 >     * because they have negative hash fields and null key and value
262 >     * fields. (These special nodes are either uncommon or transient,
263 >     * so the impact of carrying around some unused fields is
264 >     * insignificant.)
265       *
266       * The table is lazily initialized to a power-of-two size upon the
267       * first insertion.  Each bin in the table normally contains a
# Line 388 | Line 269 | public class ConcurrentHashMap<K, V>
269       * Table accesses require volatile/atomic reads, writes, and
270       * CASes.  Because there is no other way to arrange this without
271       * adding further indirections, we use intrinsics
272 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
273 <     * are always accurately traversable under volatile reads, so long
274 <     * as lookups check hash code and non-nullness of value before
275 <     * checking key equality.
276 <     *
277 <     * 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).
272 >     * (sun.misc.Unsafe) operations.
273 >     *
274 >     * We use the top (sign) bit of Node hash fields for control
275 >     * purposes -- it is available anyway because of addressing
276 >     * constraints.  Nodes with negative hash fields are specially
277 >     * handled or ignored in map methods.
278       *
279       * Insertion (via put or its variants) of the first node in an
280       * empty bin is performed by just CASing it to the bin.  This is
# Line 414 | Line 283 | public class ConcurrentHashMap<K, V>
283       * delete, and replace) require locks.  We do not want to waste
284       * the space required to associate a distinct lock object with
285       * each bin, so instead use the first node of a bin list itself as
286 <     * a lock. Blocking support for these locks relies on the builtin
287 <     * "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.
286 >     * a lock. Locking support for these locks relies on builtin
287 >     * "synchronized" monitors.
288       *
289       * Using the first node of a list as a lock does not by itself
290       * suffice though: When a node is locked, any update must first
291       * validate that it is still the first node after locking it, and
292       * retry if not. Because new nodes are always appended to lists,
293       * once a node is first in a bin, it remains first until deleted
294 <     * 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.
294 >     * or the bin becomes invalidated (upon resizing).
295       *
296       * The main disadvantage of per-bin locks is that other update
297       * operations on other nodes in a bin list protected by the same
# Line 462 | Line 324 | public class ConcurrentHashMap<K, V>
324       * sometimes deviate significantly from uniform randomness.  This
325       * includes the case when N > (1<<30), so some keys MUST collide.
326       * Similarly for dumb or hostile usages in which multiple keys are
327 <     * designed to have identical hash codes. Also, although we guard
328 <     * against the worst effects of this (see method spread), sets of
329 <     * hashes may differ only in bits that do not impact their bin
330 <     * index for a given power-of-two mask.  So we use a secondary
331 <     * strategy that applies when the number of nodes in a bin exceeds
332 <     * 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
327 >     * designed to have identical hash codes or ones that differs only
328 >     * in masked-out high bits. So we use a secondary strategy that
329 >     * applies when the number of nodes in a bin exceeds a
330 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
331 >     * specialized form of red-black trees), bounding search time to
332 >     * O(log N).  Each search step in a TreeBin is at least twice as
333       * slow as in a regular list, but given that N cannot exceed
334       * (1<<64) (before running out of addresses) this bounds search
335       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 481 | Line 340 | public class ConcurrentHashMap<K, V>
340       * iterators in the same way.
341       *
342       * The table is resized when occupancy exceeds a percentage
343 <     * threshold (nominally, 0.75, but see below).  Only a single
344 <     * thread performs the resize (using field "sizeCtl", to arrange
345 <     * exclusion), but the table otherwise remains usable for reads
346 <     * and updates. Resizing proceeds by transferring bins, one by
347 <     * one, from the table to the next table.  Because we are using
348 <     * power-of-two expansion, the elements from each bin must either
349 <     * stay at same index, or move with a power of two offset. We
350 <     * eliminate unnecessary node creation by catching cases where old
351 <     * nodes can be reused because their next fields won't change.  On
352 <     * average, only about one-sixth of them need cloning when a table
353 <     * doubles. The nodes they replace will be garbage collectable as
354 <     * soon as they are no longer referenced by any reader thread that
355 <     * may be in the midst of concurrently traversing table.  Upon
356 <     * transfer, the old table bin contains only a special forwarding
357 <     * node (with hash field "MOVED") that contains the next table as
358 <     * its key. On encountering a forwarding node, access and update
359 <     * operations restart, using the new table.
360 <     *
361 <     * Each bin transfer requires its bin lock. However, unlike other
362 <     * cases, a transfer can skip a bin if it fails to acquire its
363 <     * lock, and revisit it later (unless it is a TreeBin). Method
364 <     * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
365 <     * have been skipped because of failure to acquire a lock, and
366 <     * blocks only if none are available (i.e., only very rarely).
367 <     * The transfer operation must also ensure that all accessible
368 <     * bins in both the old and new table are usable by any traversal.
369 <     * When there are no lock acquisition failures, this is arranged
370 <     * simply by proceeding from the last bin (table.length - 1) up
371 <     * towards the first.  Upon seeing a forwarding node, traversals
372 <     * (see class Iter) arrange to move to the new table
373 <     * without revisiting nodes.  However, when any node is skipped
374 <     * during a transfer, all earlier table bins may have become
375 <     * visible, so are initialized with a reverse-forwarding node back
376 <     * to the old table until the new ones are established. (This
377 <     * sometimes requires transiently locking a forwarding node, which
378 <     * is possible under the above encoding.) These more expensive
379 <     * mechanics trigger only when necessary.
343 >     * threshold (nominally, 0.75, but see below).  Any thread
344 >     * noticing an overfull bin may assist in resizing after the
345 >     * initiating thread allocates and sets up the replacement array.
346 >     * However, rather than stalling, these other threads may proceed
347 >     * with insertions etc.  The use of TreeBins shields us from the
348 >     * worst case effects of overfilling while resizes are in
349 >     * progress.  Resizing proceeds by transferring bins, one by one,
350 >     * from the table to the next table. However, threads claim small
351 >     * blocks of indices to transfer (via field transferIndex) before
352 >     * doing so, reducing contention.  A generation stamp in field
353 >     * sizeCtl ensures that resizings do not overlap. Because we are
354 >     * using power-of-two expansion, the elements from each bin must
355 >     * either stay at same index, or move with a power of two
356 >     * offset. We eliminate unnecessary node creation by catching
357 >     * cases where old nodes can be reused because their next fields
358 >     * won't change.  On average, only about one-sixth of them need
359 >     * cloning when a table doubles. The nodes they replace will be
360 >     * garbage collectable as soon as they are no longer referenced by
361 >     * any reader thread that may be in the midst of concurrently
362 >     * traversing table.  Upon transfer, the old table bin contains
363 >     * only a special forwarding node (with hash field "MOVED") that
364 >     * contains the next table as its key. On encountering a
365 >     * forwarding node, access and update operations restart, using
366 >     * the new table.
367 >     *
368 >     * Each bin transfer requires its bin lock, which can stall
369 >     * waiting for locks while resizing. However, because other
370 >     * threads can join in and help resize rather than contend for
371 >     * locks, average aggregate waits become shorter as resizing
372 >     * progresses.  The transfer operation must also ensure that all
373 >     * accessible bins in both the old and new table are usable by any
374 >     * traversal.  This is arranged in part by proceeding from the
375 >     * last bin (table.length - 1) up towards the first.  Upon seeing
376 >     * a forwarding node, traversals (see class Traverser) arrange to
377 >     * move to the new table without revisiting nodes.  To ensure that
378 >     * no intervening nodes are skipped even when moved out of order,
379 >     * a stack (see class TableStack) is created on first encounter of
380 >     * a forwarding node during a traversal, to maintain its place if
381 >     * later processing the current table. The need for these
382 >     * save/restore mechanics is relatively rare, but when one
383 >     * forwarding node is encountered, typically many more will be.
384 >     * So Traversers use a simple caching scheme to avoid creating so
385 >     * many new TableStack nodes. (Thanks to Peter Levart for
386 >     * suggesting use of a stack here.)
387       *
388       * The traversal scheme also applies to partial traversals of
389       * ranges of bins (via an alternate Traverser constructor)
# Line 532 | Line 398 | public class ConcurrentHashMap<K, V>
398       * These cases attempt to override the initial capacity settings,
399       * but harmlessly fail to take effect in cases of races.
400       *
401 <     * The element count is maintained using a LongAdder, which avoids
402 <     * contention on updates but can encounter cache thrashing if read
403 <     * too frequently during concurrent access. To avoid reading so
404 <     * often, resizing is attempted either when a bin lock is
405 <     * contended, or upon adding to a bin already holding two or more
406 <     * nodes (checked before adding in the xIfAbsent methods, after
407 <     * adding in others). Under uniform hash distributions, the
408 <     * probability of this occurring at threshold is around 13%,
409 <     * meaning that only about 1 in 8 puts check threshold (and after
410 <     * resizing, many fewer do so). But this approximation has high
411 <     * variance for small table sizes, so we check on any collision
412 <     * for sizes <= 64. The bulk putAll operation further reduces
413 <     * contention by only committing count updates upon these size
414 <     * checks.
401 >     * The element count is maintained using a specialization of
402 >     * LongAdder. We need to incorporate a specialization rather than
403 >     * just use a LongAdder in order to access implicit
404 >     * contention-sensing that leads to creation of multiple
405 >     * CounterCells.  The counter mechanics avoid contention on
406 >     * updates but can encounter cache thrashing if read too
407 >     * frequently during concurrent access. To avoid reading so often,
408 >     * resizing under contention is attempted only upon adding to a
409 >     * bin already holding two or more nodes. Under uniform hash
410 >     * distributions, the probability of this occurring at threshold
411 >     * is around 13%, meaning that only about 1 in 8 puts check
412 >     * threshold (and after resizing, many fewer do so).
413 >     *
414 >     * TreeBins use a special form of comparison for search and
415 >     * related operations (which is the main reason we cannot use
416 >     * existing collections such as TreeMaps). TreeBins contain
417 >     * Comparable elements, but may contain others, as well as
418 >     * elements that are Comparable but not necessarily Comparable for
419 >     * the same T, so we cannot invoke compareTo among them. To handle
420 >     * this, the tree is ordered primarily by hash value, then by
421 >     * Comparable.compareTo order if applicable.  On lookup at a node,
422 >     * if elements are not comparable or compare as 0 then both left
423 >     * and right children may need to be searched in the case of tied
424 >     * hash values. (This corresponds to the full list search that
425 >     * would be necessary if all elements were non-Comparable and had
426 >     * tied hashes.) On insertion, to keep a total ordering (or as
427 >     * close as is required here) across rebalancings, we compare
428 >     * classes and identityHashCodes as tie-breakers. The red-black
429 >     * balancing code is updated from pre-jdk-collections
430 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
431 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
432 >     * Algorithms" (CLR).
433 >     *
434 >     * TreeBins also require an additional locking mechanism.  While
435 >     * list traversal is always possible by readers even during
436 >     * updates, tree traversal is not, mainly because of tree-rotations
437 >     * that may change the root node and/or its linkages.  TreeBins
438 >     * include a simple read-write lock mechanism parasitic on the
439 >     * main bin-synchronization strategy: Structural adjustments
440 >     * associated with an insertion or removal are already bin-locked
441 >     * (and so cannot conflict with other writers) but must wait for
442 >     * ongoing readers to finish. Since there can be only one such
443 >     * waiter, we use a simple scheme using a single "waiter" field to
444 >     * block writers.  However, readers need never block.  If the root
445 >     * lock is held, they proceed along the slow traversal path (via
446 >     * next-pointers) until the lock becomes available or the list is
447 >     * exhausted, whichever comes first. These cases are not fast, but
448 >     * maximize aggregate expected throughput.
449       *
450       * Maintaining API and serialization compatibility with previous
451       * versions of this class introduces several oddities. Mainly: We
452 <     * leave untouched but unused constructor arguments refering to
452 >     * leave untouched but unused constructor arguments referring to
453       * concurrencyLevel. We accept a loadFactor constructor argument,
454       * but apply it only to initial table capacity (which is the only
455       * time that we can guarantee to honor it.) We also declare an
456       * unused "Segment" class that is instantiated in minimal form
457       * only when serializing.
458 +     *
459 +     * Also, solely for compatibility with previous versions of this
460 +     * class, it extends AbstractMap, even though all of its methods
461 +     * are overridden, so it is just useless baggage.
462 +     *
463 +     * This file is organized to make things a little easier to follow
464 +     * while reading than they might otherwise: First the main static
465 +     * declarations and utilities, then fields, then main public
466 +     * methods (with a few factorings of multiple public methods into
467 +     * internal ones), then sizing methods, trees, traversers, and
468 +     * bulk operations.
469       */
470  
471      /* ---------------- Constants -------------- */
# Line 596 | Line 507 | public class ConcurrentHashMap<K, V>
507      private static final float LOAD_FACTOR = 0.75f;
508  
509      /**
510 <     * The buffer size for skipped bins during transfers. The
511 <     * value is arbitrary but should be large enough to avoid
512 <     * most locking stalls during resizes.
510 >     * The bin count threshold for using a tree rather than list for a
511 >     * bin.  Bins are converted to trees when adding an element to a
512 >     * bin with at least this many nodes. The value must be greater
513 >     * than 2, and should be at least 8 to mesh with assumptions in
514 >     * tree removal about conversion back to plain bins upon
515 >     * shrinkage.
516       */
517 <    private static final int TRANSFER_BUFFER_SIZE = 32;
517 >    static final int TREEIFY_THRESHOLD = 8;
518  
519      /**
520 <     * The bin count threshold for using a tree rather than list for a
521 <     * bin.  The value reflects the approximate break-even point for
522 <     * using tree-based operations.
520 >     * The bin count threshold for untreeifying a (split) bin during a
521 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
522 >     * most 6 to mesh with shrinkage detection under removal.
523       */
524 <    private static final int TREE_THRESHOLD = 8;
524 >    static final int UNTREEIFY_THRESHOLD = 6;
525  
526 <    /*
527 <     * Encodings for special uses of Node hash fields. See above for
528 <     * explanation.
526 >    /**
527 >     * The smallest table capacity for which bins may be treeified.
528 >     * (Otherwise the table is resized if too many nodes in a bin.)
529 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
530 >     * conflicts between resizing and treeification thresholds.
531       */
532 <    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 -------------- */
532 >    static final int MIN_TREEIFY_CAPACITY = 64;
533  
534      /**
535 <     * The array of bins. Lazily initialized upon first insertion.
536 <     * Size is always a power of two. Accessed directly by iterators.
535 >     * Minimum number of rebinnings per transfer step. Ranges are
536 >     * subdivided to allow multiple resizer threads.  This value
537 >     * serves as a lower bound to avoid resizers encountering
538 >     * excessive memory contention.  The value should be at least
539 >     * DEFAULT_CAPACITY.
540       */
541 <    transient volatile Node[] table;
541 >    private static final int MIN_TRANSFER_STRIDE = 16;
542  
543      /**
544 <     * The counter maintaining number of elements.
544 >     * The number of bits used for generation stamp in sizeCtl.
545 >     * Must be at least 6 for 32bit arrays.
546       */
547 <    private transient final LongAdder counter;
547 >    private static int RESIZE_STAMP_BITS = 16;
548  
549      /**
550 <     * Table initialization and resizing control.  When negative, the
551 <     * 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.
550 >     * The maximum number of threads that can help resize.
551 >     * Must fit in 32 - RESIZE_STAMP_BITS bits.
552       */
553 <    private transient volatile int sizeCtl;
642 <
643 <    // views
644 <    private transient KeySetView<K,V> keySet;
645 <    private transient Values<K,V> values;
646 <    private transient EntrySet<K,V> entrySet;
647 <
648 <    /** For serialization compatibility. Null unless serialized; see below */
649 <    private Segment<K,V>[] segments;
553 >    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
554  
555 <    /* ---------------- Table element access -------------- */
555 >    /**
556 >     * The bit shift for recording size stamp in sizeCtl.
557 >     */
558 >    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
559  
560      /*
561 <     * 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.
561 >     * Encodings for Node hash fields. See above for explanation.
562       */
563 <
564 <    static final Node tabAt(Node[] tab, int i) { // used by Iter
565 <        return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
566 <    }
567 <
568 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
569 <        return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
570 <    }
571 <
572 <    private static final void setTabAt(Node[] tab, int i, Node v) {
573 <        UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
574 <    }
563 >    static final int MOVED     = -1; // hash for forwarding nodes
564 >    static final int TREEBIN   = -2; // hash for roots of trees
565 >    static final int RESERVED  = -3; // hash for transient reservations
566 >    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
567 >
568 >    /** Number of CPUS, to place bounds on some sizings */
569 >    static final int NCPU = Runtime.getRuntime().availableProcessors();
570 >
571 >    /** For serialization compatibility. */
572 >    private static final ObjectStreamField[] serialPersistentFields = {
573 >        new ObjectStreamField("segments", Segment[].class),
574 >        new ObjectStreamField("segmentMask", Integer.TYPE),
575 >        new ObjectStreamField("segmentShift", Integer.TYPE)
576 >    };
577  
578      /* ---------------- Nodes -------------- */
579  
580      /**
581 <     * Key-value entry. Note that this is never exported out as a
582 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
583 <     * field of MOVED are special, and do not contain user keys or
584 <     * values.  Otherwise, keys are never null, and null val fields
585 <     * indicate that a node is in the process of being deleted or
586 <     * created. For purposes of read-only access, a key may be read
587 <     * before a val, but can only be used after checking val to be
588 <     * non-null.
589 <     */
590 <    static class Node {
591 <        volatile int hash;
592 <        final Object key;
692 <        volatile Object val;
693 <        volatile Node next;
581 >     * Key-value entry.  This class is never exported out as a
582 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
583 >     * MapEntry below), but can be used for read-only traversals used
584 >     * in bulk tasks.  Subclasses of Node with a negative hash field
585 >     * are special, and contain null keys and values (but are never
586 >     * exported).  Otherwise, keys and vals are never null.
587 >     */
588 >    static class Node<K,V> implements Map.Entry<K,V> {
589 >        final int hash;
590 >        final K key;
591 >        volatile V val;
592 >        volatile Node<K,V> next;
593  
594 <        Node(int hash, Object key, Object val, Node next) {
594 >        Node(int hash, K key, V val, Node<K,V> next) {
595              this.hash = hash;
596              this.key = key;
597              this.val = val;
598              this.next = next;
599          }
600  
601 <        /** CompareAndSet the hash field */
602 <        final boolean casHash(int cmp, int val) {
603 <            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
604 <        }
605 <
707 <        /** 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 <            }
601 >        public final K getKey()     { return key; }
602 >        public final V getValue()   { return val; }
603 >        public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
604 >        public final String toString() {
605 >            return Helpers.mapEntryToString(key, val);
606          }
607 <
608 <        /**
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;
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.
651 <     */
652 <    private static final int spread(int h) {
653 <        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.
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 final Object internalReplace(Object k, Object v, Object cv) {
656 <        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;
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                  }
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);
2128                }
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 >                        else if (f instanceof ReservationNode)
1031 >                            throw new IllegalStateException("Recursive update");
1032 >                    }
1033 >                }
1034 >                if (binCount != 0) {
1035 >                    if (binCount >= TREEIFY_THRESHOLD)
1036 >                        treeifyBin(tab, i);
1037 >                    if (oldVal != null)
1038 >                        return oldVal;
1039 >                    break;
1040 >                }
1041 >            }
1042 >        }
1043 >        addCount(1L, binCount);
1044 >        return null;
1045 >    }
1046 >
1047 >    /**
1048 >     * Copies all of the mappings from the specified map to this one.
1049 >     * These mappings replace any mappings that this map had for any of the
1050 >     * keys currently in the specified map.
1051 >     *
1052 >     * @param m mappings to be stored in this map
1053 >     */
1054 >    public void putAll(Map<? extends K, ? extends V> m) {
1055 >        tryPresize(m.size());
1056 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1057 >            putVal(e.getKey(), e.getValue(), false);
1058 >    }
1059 >
1060 >    /**
1061 >     * Removes the key (and its corresponding value) from this map.
1062 >     * This method does nothing if the key is not in the map.
1063 >     *
1064 >     * @param  key the key that needs to be removed
1065 >     * @return the previous value associated with {@code key}, or
1066 >     *         {@code null} if there was no mapping for {@code key}
1067 >     * @throws NullPointerException if the specified key is null
1068 >     */
1069 >    public V remove(Object key) {
1070 >        return replaceNode(key, null, null);
1071 >    }
1072 >
1073 >    /**
1074 >     * Implementation for the four public remove/replace methods:
1075 >     * Replaces node value with v, conditional upon match of cv if
1076 >     * non-null.  If resulting value is null, delete.
1077 >     */
1078 >    final V replaceNode(Object key, V value, Object cv) {
1079 >        int hash = spread(key.hashCode());
1080 >        for (Node<K,V>[] tab = table;;) {
1081 >            Node<K,V> f; int n, i, fh;
1082 >            if (tab == null || (n = tab.length) == 0 ||
1083 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1084 >                break;
1085 >            else if ((fh = f.hash) == MOVED)
1086 >                tab = helpTransfer(tab, f);
1087 >            else {
1088 >                V oldVal = null;
1089 >                boolean validated = false;
1090 >                synchronized (f) {
1091 >                    if (tabAt(tab, i) == f) {
1092 >                        if (fh >= 0) {
1093 >                            validated = true;
1094 >                            for (Node<K,V> e = f, pred = null;;) {
1095 >                                K ek;
1096 >                                if (e.hash == hash &&
1097 >                                    ((ek = e.key) == key ||
1098 >                                     (ek != null && key.equals(ek)))) {
1099 >                                    V ev = e.val;
1100 >                                    if (cv == null || cv == ev ||
1101 >                                        (ev != null && cv.equals(ev))) {
1102 >                                        oldVal = ev;
1103 >                                        if (value != null)
1104 >                                            e.val = value;
1105 >                                        else if (pred != null)
1106 >                                            pred.next = e.next;
1107 >                                        else
1108 >                                            setTabAt(tab, i, e.next);
1109 >                                    }
1110 >                                    break;
1111 >                                }
1112 >                                pred = e;
1113 >                                if ((e = e.next) == null)
1114 >                                    break;
1115 >                            }
1116 >                        }
1117 >                        else if (f instanceof TreeBin) {
1118 >                            validated = true;
1119 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1120 >                            TreeNode<K,V> r, p;
1121 >                            if ((r = t.root) != null &&
1122 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1123 >                                V pv = p.val;
1124 >                                if (cv == null || cv == pv ||
1125 >                                    (pv != null && cv.equals(pv))) {
1126 >                                    oldVal = pv;
1127 >                                    if (value != null)
1128 >                                        p.val = value;
1129 >                                    else if (t.removeTreeNode(p))
1130 >                                        setTabAt(tab, i, untreeify(t.first));
1131 >                                }
1132 >                            }
1133 >                        }
1134 >                        else if (f instanceof ReservationNode)
1135 >                            throw new IllegalStateException("Recursive update");
1136 >                    }
1137 >                }
1138 >                if (validated) {
1139 >                    if (oldVal != null) {
1140 >                        if (value == null)
1141 >                            addCount(-1L, -1);
1142 >                        return oldVal;
1143 >                    }
1144 >                    break;
1145 >                }
1146 >            }
1147 >        }
1148 >        return null;
1149 >    }
1150 >
1151 >    /**
1152 >     * Removes all of the mappings from this map.
1153 >     */
1154 >    public void clear() {
1155 >        long delta = 0L; // negative number of deletions
1156 >        int i = 0;
1157 >        Node<K,V>[] tab = table;
1158 >        while (tab != null && i < tab.length) {
1159 >            int fh;
1160 >            Node<K,V> f = tabAt(tab, i);
1161 >            if (f == null)
1162 >                ++i;
1163 >            else if ((fh = f.hash) == MOVED) {
1164 >                tab = helpTransfer(tab, f);
1165 >                i = 0; // restart
1166 >            }
1167 >            else {
1168 >                synchronized (f) {
1169 >                    if (tabAt(tab, i) == f) {
1170 >                        Node<K,V> p = (fh >= 0 ? f :
1171 >                                       (f instanceof TreeBin) ?
1172 >                                       ((TreeBin<K,V>)f).first : null);
1173 >                        while (p != null) {
1174 >                            --delta;
1175 >                            p = p.next;
1176 >                        }
1177 >                        setTabAt(tab, i++, null);
1178 >                    }
1179 >                }
1180 >            }
1181 >        }
1182 >        if (delta != 0L)
1183 >            addCount(delta, -1);
1184 >    }
1185 >
1186 >    /**
1187 >     * Returns a {@link Set} view of the keys contained in this map.
1188 >     * The set is backed by the map, so changes to the map are
1189 >     * reflected in the set, and vice-versa. The set supports element
1190 >     * removal, which removes the corresponding mapping from this map,
1191 >     * via the {@code Iterator.remove}, {@code Set.remove},
1192 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1193 >     * operations.  It does not support the {@code add} or
1194 >     * {@code addAll} operations.
1195 >     *
1196 >     * <p>The view's iterators and spliterators are
1197 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1198 >     *
1199 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1200 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1201 >     *
1202 >     * @return the set view
1203 >     */
1204 >    public KeySetView<K,V> keySet() {
1205 >        KeySetView<K,V> ks;
1206 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1207 >    }
1208 >
1209 >    /**
1210 >     * Returns a {@link Collection} view of the values contained in this map.
1211 >     * The collection is backed by the map, so changes to the map are
1212 >     * reflected in the collection, and vice-versa.  The collection
1213 >     * supports element removal, which removes the corresponding
1214 >     * mapping from this map, via the {@code Iterator.remove},
1215 >     * {@code Collection.remove}, {@code removeAll},
1216 >     * {@code retainAll}, and {@code clear} operations.  It does not
1217 >     * support the {@code add} or {@code addAll} operations.
1218 >     *
1219 >     * <p>The view's iterators and spliterators are
1220 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1221 >     *
1222 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}
1223 >     * and {@link Spliterator#NONNULL}.
1224 >     *
1225 >     * @return the collection view
1226 >     */
1227 >    public Collection<V> values() {
1228 >        ValuesView<K,V> vs;
1229 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1230 >    }
1231 >
1232 >    /**
1233 >     * Returns a {@link Set} view of the mappings contained in this map.
1234 >     * The set is backed by the map, so changes to the map are
1235 >     * reflected in the set, and vice-versa.  The set supports element
1236 >     * removal, which removes the corresponding mapping from the map,
1237 >     * via the {@code Iterator.remove}, {@code Set.remove},
1238 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1239 >     * operations.
1240 >     *
1241 >     * <p>The view's iterators and spliterators are
1242 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1243 >     *
1244 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1245 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1246 >     *
1247 >     * @return the set view
1248 >     */
1249 >    public Set<Map.Entry<K,V>> entrySet() {
1250 >        EntrySetView<K,V> es;
1251 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1252 >    }
1253 >
1254 >    /**
1255 >     * Returns the hash code value for this {@link Map}, i.e.,
1256 >     * the sum of, for each key-value pair in the map,
1257 >     * {@code key.hashCode() ^ value.hashCode()}.
1258 >     *
1259 >     * @return the hash code value for this map
1260 >     */
1261 >    public int hashCode() {
1262 >        int h = 0;
1263 >        Node<K,V>[] t;
1264 >        if ((t = table) != null) {
1265 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1266 >            for (Node<K,V> p; (p = it.advance()) != null; )
1267 >                h += p.key.hashCode() ^ p.val.hashCode();
1268 >        }
1269 >        return h;
1270 >    }
1271 >
1272 >    /**
1273 >     * Returns a string representation of this map.  The string
1274 >     * representation consists of a list of key-value mappings (in no
1275 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1276 >     * mappings are separated by the characters {@code ", "} (comma
1277 >     * and space).  Each key-value mapping is rendered as the key
1278 >     * followed by an equals sign ("{@code =}") followed by the
1279 >     * associated value.
1280 >     *
1281 >     * @return a string representation of this map
1282 >     */
1283 >    public String toString() {
1284 >        Node<K,V>[] t;
1285 >        int f = (t = table) == null ? 0 : t.length;
1286 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1287 >        StringBuilder sb = new StringBuilder();
1288 >        sb.append('{');
1289 >        Node<K,V> p;
1290 >        if ((p = it.advance()) != null) {
1291 >            for (;;) {
1292 >                K k = p.key;
1293 >                V v = p.val;
1294 >                sb.append(k == this ? "(this Map)" : k);
1295 >                sb.append('=');
1296 >                sb.append(v == this ? "(this Map)" : v);
1297 >                if ((p = it.advance()) == null)
1298 >                    break;
1299 >                sb.append(',').append(' ');
1300 >            }
1301 >        }
1302 >        return sb.append('}').toString();
1303 >    }
1304 >
1305 >    /**
1306 >     * Compares the specified object with this map for equality.
1307 >     * Returns {@code true} if the given object is a map with the same
1308 >     * mappings as this map.  This operation may return misleading
1309 >     * results if either map is concurrently modified during execution
1310 >     * of this method.
1311 >     *
1312 >     * @param o object to be compared for equality with this map
1313 >     * @return {@code true} if the specified object is equal to this map
1314 >     */
1315 >    public boolean equals(Object o) {
1316 >        if (o != this) {
1317 >            if (!(o instanceof Map))
1318 >                return false;
1319 >            Map<?,?> m = (Map<?,?>) o;
1320 >            Node<K,V>[] t;
1321 >            int f = (t = table) == null ? 0 : t.length;
1322 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1323 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1324 >                V val = p.val;
1325 >                Object v = m.get(p.key);
1326 >                if (v == null || (v != val && !v.equals(val)))
1327 >                    return false;
1328 >            }
1329 >            for (Map.Entry<?,?> e : m.entrySet()) {
1330 >                Object mk, mv, v;
1331 >                if ((mk = e.getKey()) == null ||
1332 >                    (mv = e.getValue()) == null ||
1333 >                    (v = get(mk)) == null ||
1334 >                    (mv != v && !mv.equals(v)))
1335 >                    return false;
1336 >            }
1337 >        }
1338 >        return true;
1339 >    }
1340 >
1341 >    /**
1342 >     * Stripped-down version of helper class used in previous version,
1343 >     * declared for the sake of serialization compatibility
1344 >     */
1345 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1346 >        private static final long serialVersionUID = 2249069246763182397L;
1347 >        final float loadFactor;
1348 >        Segment(float lf) { this.loadFactor = lf; }
1349 >    }
1350 >
1351 >    /**
1352 >     * Saves the state of the {@code ConcurrentHashMap} instance to a
1353 >     * stream (i.e., serializes it).
1354 >     * @param s the stream
1355 >     * @throws java.io.IOException if an I/O error occurs
1356 >     * @serialData
1357 >     * the key (Object) and value (Object)
1358 >     * for each key-value mapping, followed by a null pair.
1359 >     * The key-value mappings are emitted in no particular order.
1360 >     */
1361 >    private void writeObject(java.io.ObjectOutputStream s)
1362 >        throws java.io.IOException {
1363 >        // For serialization compatibility
1364 >        // Emulate segment calculation from previous version of this class
1365 >        int sshift = 0;
1366 >        int ssize = 1;
1367 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1368 >            ++sshift;
1369 >            ssize <<= 1;
1370 >        }
1371 >        int segmentShift = 32 - sshift;
1372 >        int segmentMask = ssize - 1;
1373 >        @SuppressWarnings("unchecked")
1374 >        Segment<K,V>[] segments = (Segment<K,V>[])
1375 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1376 >        for (int i = 0; i < segments.length; ++i)
1377 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1378 >        java.io.ObjectOutputStream.PutField streamFields = s.putFields();
1379 >        streamFields.put("segments", segments);
1380 >        streamFields.put("segmentShift", segmentShift);
1381 >        streamFields.put("segmentMask", segmentMask);
1382 >        s.writeFields();
1383 >
1384 >        Node<K,V>[] t;
1385 >        if ((t = table) != null) {
1386 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1387 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1388 >                s.writeObject(p.key);
1389 >                s.writeObject(p.val);
1390 >            }
1391 >        }
1392 >        s.writeObject(null);
1393 >        s.writeObject(null);
1394 >        segments = null; // throw away
1395 >    }
1396 >
1397 >    /**
1398 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1399 >     * @param s the stream
1400 >     * @throws ClassNotFoundException if the class of a serialized object
1401 >     *         could not be found
1402 >     * @throws java.io.IOException if an I/O error occurs
1403 >     */
1404 >    private void readObject(java.io.ObjectInputStream s)
1405 >        throws java.io.IOException, ClassNotFoundException {
1406 >        /*
1407 >         * To improve performance in typical cases, we create nodes
1408 >         * while reading, then place in table once size is known.
1409 >         * However, we must also validate uniqueness and deal with
1410 >         * overpopulated bins while doing so, which requires
1411 >         * specialized versions of putVal mechanics.
1412 >         */
1413 >        sizeCtl = -1; // force exclusion for table construction
1414 >        s.defaultReadObject();
1415 >        long size = 0L;
1416 >        Node<K,V> p = null;
1417 >        for (;;) {
1418 >            @SuppressWarnings("unchecked")
1419 >            K k = (K) s.readObject();
1420 >            @SuppressWarnings("unchecked")
1421 >            V v = (V) s.readObject();
1422 >            if (k != null && v != null) {
1423 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1424 >                ++size;
1425 >            }
1426 >            else
1427 >                break;
1428 >        }
1429 >        if (size == 0L)
1430 >            sizeCtl = 0;
1431 >        else {
1432 >            int n;
1433 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1434 >                n = MAXIMUM_CAPACITY;
1435 >            else {
1436 >                int sz = (int)size;
1437 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1438 >            }
1439 >            @SuppressWarnings("unchecked")
1440 >            Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1441 >            int mask = n - 1;
1442 >            long added = 0L;
1443 >            while (p != null) {
1444 >                boolean insertAtFront;
1445 >                Node<K,V> next = p.next, first;
1446 >                int h = p.hash, j = h & mask;
1447 >                if ((first = tabAt(tab, j)) == null)
1448 >                    insertAtFront = true;
1449 >                else {
1450 >                    K k = p.key;
1451 >                    if (first.hash < 0) {
1452 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1453 >                        if (t.putTreeVal(h, k, p.val) == null)
1454 >                            ++added;
1455 >                        insertAtFront = false;
1456 >                    }
1457 >                    else {
1458 >                        int binCount = 0;
1459 >                        insertAtFront = true;
1460 >                        Node<K,V> q; K qk;
1461 >                        for (q = first; q != null; q = q.next) {
1462 >                            if (q.hash == h &&
1463 >                                ((qk = q.key) == k ||
1464 >                                 (qk != null && k.equals(qk)))) {
1465 >                                insertAtFront = false;
1466 >                                break;
1467 >                            }
1468 >                            ++binCount;
1469 >                        }
1470 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1471 >                            insertAtFront = false;
1472 >                            ++added;
1473 >                            p.next = first;
1474 >                            TreeNode<K,V> hd = null, tl = null;
1475 >                            for (q = p; q != null; q = q.next) {
1476 >                                TreeNode<K,V> t = new TreeNode<K,V>
1477 >                                    (q.hash, q.key, q.val, null, null);
1478 >                                if ((t.prev = tl) == null)
1479 >                                    hd = t;
1480 >                                else
1481 >                                    tl.next = t;
1482 >                                tl = t;
1483 >                            }
1484 >                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1485 >                        }
1486 >                    }
1487 >                }
1488 >                if (insertAtFront) {
1489 >                    ++added;
1490 >                    p.next = first;
1491 >                    setTabAt(tab, j, p);
1492 >                }
1493 >                p = next;
1494 >            }
1495 >            table = tab;
1496 >            sizeCtl = n - (n >>> 2);
1497 >            baseCount = added;
1498 >        }
1499 >    }
1500 >
1501 >    // ConcurrentMap methods
1502 >
1503 >    /**
1504 >     * {@inheritDoc}
1505 >     *
1506 >     * @return the previous value associated with the specified key,
1507 >     *         or {@code null} if there was no mapping for the key
1508 >     * @throws NullPointerException if the specified key or value is null
1509 >     */
1510 >    public V putIfAbsent(K key, V value) {
1511 >        return putVal(key, value, true);
1512 >    }
1513 >
1514 >    /**
1515 >     * {@inheritDoc}
1516 >     *
1517 >     * @throws NullPointerException if the specified key is null
1518 >     */
1519 >    public boolean remove(Object key, Object value) {
1520 >        if (key == null)
1521 >            throw new NullPointerException();
1522 >        return value != null && replaceNode(key, null, value) != null;
1523 >    }
1524 >
1525 >    /**
1526 >     * {@inheritDoc}
1527 >     *
1528 >     * @throws NullPointerException if any of the arguments are null
1529 >     */
1530 >    public boolean replace(K key, V oldValue, V newValue) {
1531 >        if (key == null || oldValue == null || newValue == null)
1532              throw new NullPointerException();
1533 <        return (V)internalPut(key, value);
1533 >        return replaceNode(key, newValue, oldValue) != null;
1534      }
1535  
1536      /**
# Line 2806 | Line 1540 | public class ConcurrentHashMap<K, V>
1540       *         or {@code null} if there was no mapping for the key
1541       * @throws NullPointerException if the specified key or value is null
1542       */
1543 <    @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) {
1543 >    public V replace(K key, V value) {
1544          if (key == null || value == null)
1545              throw new NullPointerException();
1546 <        return (V)internalPutIfAbsent(key, value);
1546 >        return replaceNode(key, value, null);
1547      }
1548  
1549 +    // Overrides of JDK8+ Map extension method defaults
1550 +
1551      /**
1552 <     * Copies all of the mappings from the specified map to this one.
1553 <     * These mappings replace any mappings that this map had for any of the
1554 <     * keys currently in the specified map.
1552 >     * Returns the value to which the specified key is mapped, or the
1553 >     * given default value if this map contains no mapping for the
1554 >     * key.
1555       *
1556 <     * @param m mappings to be stored in this map
1556 >     * @param key the key whose associated value is to be returned
1557 >     * @param defaultValue the value to return if this map contains
1558 >     * no mapping for the given key
1559 >     * @return the mapping for the key, if present; else the default value
1560 >     * @throws NullPointerException if the specified key is null
1561       */
1562 <    public void putAll(Map<? extends K, ? extends V> m) {
1563 <        internalPutAll(m);
1562 >    public V getOrDefault(Object key, V defaultValue) {
1563 >        V v;
1564 >        return (v = get(key)) == null ? defaultValue : v;
1565 >    }
1566 >
1567 >    public void forEach(BiConsumer<? super K, ? super V> action) {
1568 >        if (action == null) throw new NullPointerException();
1569 >        Node<K,V>[] t;
1570 >        if ((t = table) != null) {
1571 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1572 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1573 >                action.accept(p.key, p.val);
1574 >            }
1575 >        }
1576 >    }
1577 >
1578 >    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1579 >        if (function == null) throw new NullPointerException();
1580 >        Node<K,V>[] t;
1581 >        if ((t = table) != null) {
1582 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1583 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1584 >                V oldValue = p.val;
1585 >                for (K key = p.key;;) {
1586 >                    V newValue = function.apply(key, oldValue);
1587 >                    if (newValue == null)
1588 >                        throw new NullPointerException();
1589 >                    if (replaceNode(key, newValue, oldValue) != null ||
1590 >                        (oldValue = get(key)) == null)
1591 >                        break;
1592 >                }
1593 >            }
1594 >        }
1595 >    }
1596 >
1597 >    /**
1598 >     * Helper method for EntrySetView.removeIf
1599 >     */
1600 >    boolean removeEntryIf(Predicate<? super Entry<K,V>> function) {
1601 >        if (function == null) throw new NullPointerException();
1602 >        Node<K,V>[] t;
1603 >        boolean removed = false;
1604 >        if ((t = table) != null) {
1605 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1606 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1607 >                K k = p.key;
1608 >                V v = p.val;
1609 >                Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v);
1610 >                if (function.test(e) && replaceNode(k, null, v) != null)
1611 >                    removed = true;
1612 >            }
1613 >        }
1614 >        return removed;
1615 >    }
1616 >
1617 >    /**
1618 >     * Helper method for ValuesView.removeIf
1619 >     */
1620 >    boolean removeValueIf(Predicate<? super V> function) {
1621 >        if (function == null) throw new NullPointerException();
1622 >        Node<K,V>[] t;
1623 >        boolean removed = false;
1624 >        if ((t = table) != null) {
1625 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1626 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1627 >                K k = p.key;
1628 >                V v = p.val;
1629 >                if (function.test(v) && replaceNode(k, null, v) != null)
1630 >                    removed = true;
1631 >            }
1632 >        }
1633 >        return removed;
1634      }
1635  
1636      /**
1637       * If the specified key is not already associated with a value,
1638 <     * computes its value using the given mappingFunction and enters
1639 <     * it into the map unless null.  This is equivalent to
1640 <     * <pre> {@code
1641 <     * if (map.containsKey(key))
1642 <     *   return map.get(key);
1643 <     * value = mappingFunction.apply(key);
1644 <     * 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>
1638 >     * attempts to compute its value using the given mapping function
1639 >     * and enters it into this map unless {@code null}.  The entire
1640 >     * method invocation is performed atomically, so the function is
1641 >     * applied at most once per key.  Some attempted update operations
1642 >     * on this map by other threads may be blocked while computation
1643 >     * is in progress, so the computation should be short and simple,
1644 >     * and must not attempt to update any other mappings of this map.
1645       *
1646       * @param key key with which the specified value is to be associated
1647       * @param mappingFunction the function to compute a value
# Line 2862 | Line 1655 | public class ConcurrentHashMap<K, V>
1655       * @throws RuntimeException or Error if the mappingFunction does so,
1656       *         in which case the mapping is left unestablished
1657       */
1658 <    @SuppressWarnings("unchecked") public V computeIfAbsent
2866 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
1658 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1659          if (key == null || mappingFunction == null)
1660              throw new NullPointerException();
1661 <        return (V)internalComputeIfAbsent(key, mappingFunction);
1661 >        int h = spread(key.hashCode());
1662 >        V val = null;
1663 >        int binCount = 0;
1664 >        for (Node<K,V>[] tab = table;;) {
1665 >            Node<K,V> f; int n, i, fh;
1666 >            if (tab == null || (n = tab.length) == 0)
1667 >                tab = initTable();
1668 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1669 >                Node<K,V> r = new ReservationNode<K,V>();
1670 >                synchronized (r) {
1671 >                    if (casTabAt(tab, i, null, r)) {
1672 >                        binCount = 1;
1673 >                        Node<K,V> node = null;
1674 >                        try {
1675 >                            if ((val = mappingFunction.apply(key)) != null)
1676 >                                node = new Node<K,V>(h, key, val, null);
1677 >                        } finally {
1678 >                            setTabAt(tab, i, node);
1679 >                        }
1680 >                    }
1681 >                }
1682 >                if (binCount != 0)
1683 >                    break;
1684 >            }
1685 >            else if ((fh = f.hash) == MOVED)
1686 >                tab = helpTransfer(tab, f);
1687 >            else {
1688 >                boolean added = false;
1689 >                synchronized (f) {
1690 >                    if (tabAt(tab, i) == f) {
1691 >                        if (fh >= 0) {
1692 >                            binCount = 1;
1693 >                            for (Node<K,V> e = f;; ++binCount) {
1694 >                                K ek;
1695 >                                if (e.hash == h &&
1696 >                                    ((ek = e.key) == key ||
1697 >                                     (ek != null && key.equals(ek)))) {
1698 >                                    val = e.val;
1699 >                                    break;
1700 >                                }
1701 >                                Node<K,V> pred = e;
1702 >                                if ((e = e.next) == null) {
1703 >                                    if ((val = mappingFunction.apply(key)) != null) {
1704 >                                        if (pred.next != null)
1705 >                                            throw new IllegalStateException("Recursive update");
1706 >                                        added = true;
1707 >                                        pred.next = new Node<K,V>(h, key, val, null);
1708 >                                    }
1709 >                                    break;
1710 >                                }
1711 >                            }
1712 >                        }
1713 >                        else if (f instanceof TreeBin) {
1714 >                            binCount = 2;
1715 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1716 >                            TreeNode<K,V> r, p;
1717 >                            if ((r = t.root) != null &&
1718 >                                (p = r.findTreeNode(h, key, null)) != null)
1719 >                                val = p.val;
1720 >                            else if ((val = mappingFunction.apply(key)) != null) {
1721 >                                added = true;
1722 >                                t.putTreeVal(h, key, val);
1723 >                            }
1724 >                        }
1725 >                        else if (f instanceof ReservationNode)
1726 >                            throw new IllegalStateException("Recursive update");
1727 >                    }
1728 >                }
1729 >                if (binCount != 0) {
1730 >                    if (binCount >= TREEIFY_THRESHOLD)
1731 >                        treeifyBin(tab, i);
1732 >                    if (!added)
1733 >                        return val;
1734 >                    break;
1735 >                }
1736 >            }
1737 >        }
1738 >        if (val != null)
1739 >            addCount(1L, binCount);
1740 >        return val;
1741      }
1742  
1743      /**
1744 <     * If the given key is present, computes a new mapping value given a key and
1745 <     * its current mapped value. This is equivalent to
1746 <     *  <pre> {@code
1747 <     *   if (map.containsKey(key)) {
1748 <     *     value = remappingFunction.apply(key, map.get(key));
1749 <     *     if (value != null)
1750 <     *       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:
1744 >     * If the value for the specified key is present, attempts to
1745 >     * compute a new mapping given the key and its current mapped
1746 >     * value.  The entire method invocation is performed atomically.
1747 >     * Some attempted update operations on this map by other threads
1748 >     * may be blocked while computation is in progress, so the
1749 >     * computation should be short and simple, and must not attempt to
1750 >     * update any other mappings of this map.
1751       *
1752 <     * @param key key with which the specified value is to be associated
1752 >     * @param key key with which a value may be associated
1753       * @param remappingFunction the function to compute a value
1754       * @return the new value associated with the specified key, or null if none
1755       * @throws NullPointerException if the specified key or remappingFunction
# Line 2903 | Line 1760 | public class ConcurrentHashMap<K, V>
1760       * @throws RuntimeException or Error if the remappingFunction does so,
1761       *         in which case the mapping is unchanged
1762       */
1763 <    @SuppressWarnings("unchecked") public V computeIfPresent
2907 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1763 >    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1764          if (key == null || remappingFunction == null)
1765              throw new NullPointerException();
1766 <        return (V)internalCompute(key, true, remappingFunction);
1766 >        int h = spread(key.hashCode());
1767 >        V val = null;
1768 >        int delta = 0;
1769 >        int binCount = 0;
1770 >        for (Node<K,V>[] tab = table;;) {
1771 >            Node<K,V> f; int n, i, fh;
1772 >            if (tab == null || (n = tab.length) == 0)
1773 >                tab = initTable();
1774 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1775 >                break;
1776 >            else if ((fh = f.hash) == MOVED)
1777 >                tab = helpTransfer(tab, f);
1778 >            else {
1779 >                synchronized (f) {
1780 >                    if (tabAt(tab, i) == f) {
1781 >                        if (fh >= 0) {
1782 >                            binCount = 1;
1783 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1784 >                                K ek;
1785 >                                if (e.hash == h &&
1786 >                                    ((ek = e.key) == key ||
1787 >                                     (ek != null && key.equals(ek)))) {
1788 >                                    val = remappingFunction.apply(key, e.val);
1789 >                                    if (val != null)
1790 >                                        e.val = val;
1791 >                                    else {
1792 >                                        delta = -1;
1793 >                                        Node<K,V> en = e.next;
1794 >                                        if (pred != null)
1795 >                                            pred.next = en;
1796 >                                        else
1797 >                                            setTabAt(tab, i, en);
1798 >                                    }
1799 >                                    break;
1800 >                                }
1801 >                                pred = e;
1802 >                                if ((e = e.next) == null)
1803 >                                    break;
1804 >                            }
1805 >                        }
1806 >                        else if (f instanceof TreeBin) {
1807 >                            binCount = 2;
1808 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1809 >                            TreeNode<K,V> r, p;
1810 >                            if ((r = t.root) != null &&
1811 >                                (p = r.findTreeNode(h, key, null)) != null) {
1812 >                                val = remappingFunction.apply(key, p.val);
1813 >                                if (val != null)
1814 >                                    p.val = val;
1815 >                                else {
1816 >                                    delta = -1;
1817 >                                    if (t.removeTreeNode(p))
1818 >                                        setTabAt(tab, i, untreeify(t.first));
1819 >                                }
1820 >                            }
1821 >                        }
1822 >                        else if (f instanceof ReservationNode)
1823 >                            throw new IllegalStateException("Recursive update");
1824 >                    }
1825 >                }
1826 >                if (binCount != 0)
1827 >                    break;
1828 >            }
1829 >        }
1830 >        if (delta != 0)
1831 >            addCount((long)delta, binCount);
1832 >        return val;
1833      }
1834  
1835      /**
1836 <     * Computes a new mapping value given a key and
1837 <     * its current mapped value (or {@code null} if there is no current
1838 <     * mapping). This is equivalent to
1839 <     *  <pre> {@code
1840 <     *   value = remappingFunction.apply(key, map.get(key));
1841 <     *   if (value != null)
1842 <     *     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>
1836 >     * Attempts to compute a mapping for the specified key and its
1837 >     * current mapped value (or {@code null} if there is no current
1838 >     * mapping). The entire method invocation is performed atomically.
1839 >     * Some attempted update operations on this map by other threads
1840 >     * may be blocked while computation is in progress, so the
1841 >     * computation should be short and simple, and must not attempt to
1842 >     * update any other mappings of this Map.
1843       *
1844       * @param key key with which the specified value is to be associated
1845       * @param remappingFunction the function to compute a value
# Line 2950 | Line 1852 | public class ConcurrentHashMap<K, V>
1852       * @throws RuntimeException or Error if the remappingFunction does so,
1853       *         in which case the mapping is unchanged
1854       */
1855 <    @SuppressWarnings("unchecked") public V compute
1856 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1855 >    public V compute(K key,
1856 >                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1857          if (key == null || remappingFunction == null)
1858              throw new NullPointerException();
1859 <        return (V)internalCompute(key, false, remappingFunction);
1859 >        int h = spread(key.hashCode());
1860 >        V val = null;
1861 >        int delta = 0;
1862 >        int binCount = 0;
1863 >        for (Node<K,V>[] tab = table;;) {
1864 >            Node<K,V> f; int n, i, fh;
1865 >            if (tab == null || (n = tab.length) == 0)
1866 >                tab = initTable();
1867 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1868 >                Node<K,V> r = new ReservationNode<K,V>();
1869 >                synchronized (r) {
1870 >                    if (casTabAt(tab, i, null, r)) {
1871 >                        binCount = 1;
1872 >                        Node<K,V> node = null;
1873 >                        try {
1874 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1875 >                                delta = 1;
1876 >                                node = new Node<K,V>(h, key, val, null);
1877 >                            }
1878 >                        } finally {
1879 >                            setTabAt(tab, i, node);
1880 >                        }
1881 >                    }
1882 >                }
1883 >                if (binCount != 0)
1884 >                    break;
1885 >            }
1886 >            else if ((fh = f.hash) == MOVED)
1887 >                tab = helpTransfer(tab, f);
1888 >            else {
1889 >                synchronized (f) {
1890 >                    if (tabAt(tab, i) == f) {
1891 >                        if (fh >= 0) {
1892 >                            binCount = 1;
1893 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1894 >                                K ek;
1895 >                                if (e.hash == h &&
1896 >                                    ((ek = e.key) == key ||
1897 >                                     (ek != null && key.equals(ek)))) {
1898 >                                    val = remappingFunction.apply(key, e.val);
1899 >                                    if (val != null)
1900 >                                        e.val = val;
1901 >                                    else {
1902 >                                        delta = -1;
1903 >                                        Node<K,V> en = e.next;
1904 >                                        if (pred != null)
1905 >                                            pred.next = en;
1906 >                                        else
1907 >                                            setTabAt(tab, i, en);
1908 >                                    }
1909 >                                    break;
1910 >                                }
1911 >                                pred = e;
1912 >                                if ((e = e.next) == null) {
1913 >                                    val = remappingFunction.apply(key, null);
1914 >                                    if (val != null) {
1915 >                                        if (pred.next != null)
1916 >                                            throw new IllegalStateException("Recursive update");
1917 >                                        delta = 1;
1918 >                                        pred.next =
1919 >                                            new Node<K,V>(h, key, val, null);
1920 >                                    }
1921 >                                    break;
1922 >                                }
1923 >                            }
1924 >                        }
1925 >                        else if (f instanceof TreeBin) {
1926 >                            binCount = 1;
1927 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1928 >                            TreeNode<K,V> r, p;
1929 >                            if ((r = t.root) != null)
1930 >                                p = r.findTreeNode(h, key, null);
1931 >                            else
1932 >                                p = null;
1933 >                            V pv = (p == null) ? null : p.val;
1934 >                            val = remappingFunction.apply(key, pv);
1935 >                            if (val != null) {
1936 >                                if (p != null)
1937 >                                    p.val = val;
1938 >                                else {
1939 >                                    delta = 1;
1940 >                                    t.putTreeVal(h, key, val);
1941 >                                }
1942 >                            }
1943 >                            else if (p != null) {
1944 >                                delta = -1;
1945 >                                if (t.removeTreeNode(p))
1946 >                                    setTabAt(tab, i, untreeify(t.first));
1947 >                            }
1948 >                        }
1949 >                        else if (f instanceof ReservationNode)
1950 >                            throw new IllegalStateException("Recursive update");
1951 >                    }
1952 >                }
1953 >                if (binCount != 0) {
1954 >                    if (binCount >= TREEIFY_THRESHOLD)
1955 >                        treeifyBin(tab, i);
1956 >                    break;
1957 >                }
1958 >            }
1959 >        }
1960 >        if (delta != 0)
1961 >            addCount((long)delta, binCount);
1962 >        return val;
1963      }
1964  
1965      /**
1966 <     * If the specified key is not already associated
1967 <     * with a value, associate it with the given value.
1968 <     * Otherwise, replace the value with the results of
1969 <     * the given remapping function. This is equivalent to:
1970 <     *  <pre> {@code
1971 <     *   if (!map.containsKey(key))
1972 <     *     map.put(value);
1973 <     *   else {
1974 <     *     newValue = remappingFunction.apply(map.get(key), value);
1975 <     *     if (value != null)
1976 <     *       map.put(key, value);
1977 <     *     else
1978 <     *       map.remove(key);
1979 <     *   }
1980 <     * }</pre>
1981 <     * except that the action is performed atomically.  If the
1982 <     * function returns {@code null}, the mapping is removed.  If the
1983 <     * 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.
1966 >     * If the specified key is not already associated with a
1967 >     * (non-null) value, associates it with the given value.
1968 >     * Otherwise, replaces the value with the results of the given
1969 >     * remapping function, or removes if {@code null}. The entire
1970 >     * method invocation is performed atomically.  Some attempted
1971 >     * update operations on this map by other threads may be blocked
1972 >     * while computation is in progress, so the computation should be
1973 >     * short and simple, and must not attempt to update any other
1974 >     * mappings of this Map.
1975 >     *
1976 >     * @param key key with which the specified value is to be associated
1977 >     * @param value the value to use if absent
1978 >     * @param remappingFunction the function to recompute a value if present
1979 >     * @return the new value associated with the specified key, or null if none
1980 >     * @throws NullPointerException if the specified key or the
1981 >     *         remappingFunction is null
1982 >     * @throws RuntimeException or Error if the remappingFunction does so,
1983 >     *         in which case the mapping is unchanged
1984       */
1985 <    @SuppressWarnings("unchecked") public V merge
2986 <        (K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1985 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1986          if (key == null || value == null || remappingFunction == null)
1987              throw new NullPointerException();
1988 <        return (V)internalMerge(key, value, remappingFunction);
1988 >        int h = spread(key.hashCode());
1989 >        V val = null;
1990 >        int delta = 0;
1991 >        int binCount = 0;
1992 >        for (Node<K,V>[] tab = table;;) {
1993 >            Node<K,V> f; int n, i, fh;
1994 >            if (tab == null || (n = tab.length) == 0)
1995 >                tab = initTable();
1996 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1997 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1998 >                    delta = 1;
1999 >                    val = value;
2000 >                    break;
2001 >                }
2002 >            }
2003 >            else if ((fh = f.hash) == MOVED)
2004 >                tab = helpTransfer(tab, f);
2005 >            else {
2006 >                synchronized (f) {
2007 >                    if (tabAt(tab, i) == f) {
2008 >                        if (fh >= 0) {
2009 >                            binCount = 1;
2010 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
2011 >                                K ek;
2012 >                                if (e.hash == h &&
2013 >                                    ((ek = e.key) == key ||
2014 >                                     (ek != null && key.equals(ek)))) {
2015 >                                    val = remappingFunction.apply(e.val, value);
2016 >                                    if (val != null)
2017 >                                        e.val = val;
2018 >                                    else {
2019 >                                        delta = -1;
2020 >                                        Node<K,V> en = e.next;
2021 >                                        if (pred != null)
2022 >                                            pred.next = en;
2023 >                                        else
2024 >                                            setTabAt(tab, i, en);
2025 >                                    }
2026 >                                    break;
2027 >                                }
2028 >                                pred = e;
2029 >                                if ((e = e.next) == null) {
2030 >                                    delta = 1;
2031 >                                    val = value;
2032 >                                    pred.next =
2033 >                                        new Node<K,V>(h, key, val, null);
2034 >                                    break;
2035 >                                }
2036 >                            }
2037 >                        }
2038 >                        else if (f instanceof TreeBin) {
2039 >                            binCount = 2;
2040 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2041 >                            TreeNode<K,V> r = t.root;
2042 >                            TreeNode<K,V> p = (r == null) ? null :
2043 >                                r.findTreeNode(h, key, null);
2044 >                            val = (p == null) ? value :
2045 >                                remappingFunction.apply(p.val, value);
2046 >                            if (val != null) {
2047 >                                if (p != null)
2048 >                                    p.val = val;
2049 >                                else {
2050 >                                    delta = 1;
2051 >                                    t.putTreeVal(h, key, val);
2052 >                                }
2053 >                            }
2054 >                            else if (p != null) {
2055 >                                delta = -1;
2056 >                                if (t.removeTreeNode(p))
2057 >                                    setTabAt(tab, i, untreeify(t.first));
2058 >                            }
2059 >                        }
2060 >                        else if (f instanceof ReservationNode)
2061 >                            throw new IllegalStateException("Recursive update");
2062 >                    }
2063 >                }
2064 >                if (binCount != 0) {
2065 >                    if (binCount >= TREEIFY_THRESHOLD)
2066 >                        treeifyBin(tab, i);
2067 >                    break;
2068 >                }
2069 >            }
2070 >        }
2071 >        if (delta != 0)
2072 >            addCount((long)delta, binCount);
2073 >        return val;
2074      }
2075  
2076 +    // Hashtable legacy methods
2077 +
2078      /**
2079 <     * Removes the key (and its corresponding value) from this map.
2994 <     * This method does nothing if the key is not in the map.
2079 >     * Tests if some key maps into the specified value in this table.
2080       *
2081 <     * @param  key the key that needs to be removed
2082 <     * @return the previous value associated with {@code key}, or
2083 <     *         {@code null} if there was no mapping for {@code key}
2084 <     * @throws NullPointerException if the specified key is null
2081 >     * <p>Note that this method is identical in functionality to
2082 >     * {@link #containsValue(Object)}, and exists solely to ensure
2083 >     * full compatibility with class {@link java.util.Hashtable},
2084 >     * which supported this method prior to introduction of the Java
2085 >     * Collections Framework.
2086 >     *
2087 >     * @param  value a value to search for
2088 >     * @return {@code true} if and only if some key maps to the
2089 >     *         {@code value} argument in this table as
2090 >     *         determined by the {@code equals} method;
2091 >     *         {@code false} otherwise
2092 >     * @throws NullPointerException if the specified value is null
2093       */
2094 <    @SuppressWarnings("unchecked") public V remove(Object key) {
2095 <        if (key == null)
3003 <            throw new NullPointerException();
3004 <        return (V)internalReplace(key, null, null);
2094 >    public boolean contains(Object value) {
2095 >        return containsValue(value);
2096      }
2097  
2098      /**
2099 <     * {@inheritDoc}
2099 >     * Returns an enumeration of the keys in this table.
2100       *
2101 <     * @throws NullPointerException if the specified key is null
2101 >     * @return an enumeration of the keys in this table
2102 >     * @see #keySet()
2103       */
2104 <    public boolean remove(Object key, Object value) {
2105 <        if (key == null)
2106 <            throw new NullPointerException();
2107 <        if (value == null)
3016 <            return false;
3017 <        return internalReplace(key, null, value) != null;
2104 >    public Enumeration<K> keys() {
2105 >        Node<K,V>[] t;
2106 >        int f = (t = table) == null ? 0 : t.length;
2107 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2108      }
2109  
2110      /**
2111 <     * {@inheritDoc}
2111 >     * Returns an enumeration of the values in this table.
2112       *
2113 <     * @throws NullPointerException if any of the arguments are null
2113 >     * @return an enumeration of the values in this table
2114 >     * @see #values()
2115       */
2116 <    public boolean replace(K key, V oldValue, V newValue) {
2117 <        if (key == null || oldValue == null || newValue == null)
2118 <            throw new NullPointerException();
2119 <        return internalReplace(key, newValue, oldValue) != null;
2116 >    public Enumeration<V> elements() {
2117 >        Node<K,V>[] t;
2118 >        int f = (t = table) == null ? 0 : t.length;
2119 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2120      }
2121  
2122 +    // ConcurrentHashMap-only methods
2123 +
2124      /**
2125 <     * {@inheritDoc}
2125 >     * Returns the number of mappings. This method should be used
2126 >     * instead of {@link #size} because a ConcurrentHashMap may
2127 >     * contain more mappings than can be represented as an int. The
2128 >     * value returned is an estimate; the actual count may differ if
2129 >     * there are concurrent insertions or removals.
2130       *
2131 <     * @return the previous value associated with the specified key,
2132 <     *         or {@code null} if there was no mapping for the key
3036 <     * @throws NullPointerException if the specified key or value is null
2131 >     * @return the number of mappings
2132 >     * @since 1.8
2133       */
2134 <    @SuppressWarnings("unchecked") public V replace(K key, V value) {
2135 <        if (key == null || value == null)
2136 <            throw new NullPointerException();
3041 <        return (V)internalReplace(key, value, null);
2134 >    public long mappingCount() {
2135 >        long n = sumCount();
2136 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2137      }
2138  
2139      /**
2140 <     * Removes all of the mappings from this map.
2140 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2141 >     * from the given type to {@code Boolean.TRUE}.
2142 >     *
2143 >     * @param <K> the element type of the returned set
2144 >     * @return the new set
2145 >     * @since 1.8
2146       */
2147 <    public void clear() {
2148 <        internalClear();
2147 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2148 >        return new KeySetView<K,Boolean>
2149 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2150      }
2151  
2152      /**
2153 <     * Returns a {@link Set} view of the keys contained in this map.
2154 <     * The set is backed by the map, so changes to the map are
3054 <     * reflected in the set, and vice-versa.
2153 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2154 >     * from the given type to {@code Boolean.TRUE}.
2155       *
2156 <     * @return the set view
2156 >     * @param initialCapacity The implementation performs internal
2157 >     * sizing to accommodate this many elements.
2158 >     * @param <K> the element type of the returned set
2159 >     * @return the new set
2160 >     * @throws IllegalArgumentException if the initial capacity of
2161 >     * elements is negative
2162 >     * @since 1.8
2163       */
2164 <    public KeySetView<K,V> keySet() {
2165 <        KeySetView<K,V> ks = keySet;
2166 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2164 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2165 >        return new KeySetView<K,Boolean>
2166 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2167      }
2168  
2169      /**
2170       * Returns a {@link Set} view of the keys in this map, using the
2171       * given common mapped value for any additions (i.e., {@link
2172 <     * Collection#add} and {@link Collection#addAll}). This is of
2173 <     * course only appropriate if it is acceptable to use the same
2174 <     * value for all additions from this view.
2172 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2173 >     * This is of course only appropriate if it is acceptable to use
2174 >     * the same value for all additions from this view.
2175       *
2176 <     * @param mappedValue the mapped value to use for any
3071 <     * additions.
2176 >     * @param mappedValue the mapped value to use for any additions
2177       * @return the set view
2178       * @throws NullPointerException if the mappedValue is null
2179       */
# Line 3078 | Line 2183 | public class ConcurrentHashMap<K, V>
2183          return new KeySetView<K,V>(this, mappedValue);
2184      }
2185  
2186 +    /* ---------------- Special Nodes -------------- */
2187 +
2188      /**
2189 <     * 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.
2189 >     * A node inserted at head of bins during transfer operations.
2190       */
2191 <    public Collection<V> values() {
2192 <        Values<K,V> vs = values;
2193 <        return (vs != null) ? vs : (values = new Values<K,V>(this));
2191 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2192 >        final Node<K,V>[] nextTable;
2193 >        ForwardingNode(Node<K,V>[] tab) {
2194 >            super(MOVED, null, null, null);
2195 >            this.nextTable = tab;
2196 >        }
2197 >
2198 >        Node<K,V> find(int h, Object k) {
2199 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2200 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2201 >                Node<K,V> e; int n;
2202 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2203 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2204 >                    return null;
2205 >                for (;;) {
2206 >                    int eh; K ek;
2207 >                    if ((eh = e.hash) == h &&
2208 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2209 >                        return e;
2210 >                    if (eh < 0) {
2211 >                        if (e instanceof ForwardingNode) {
2212 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2213 >                            continue outer;
2214 >                        }
2215 >                        else
2216 >                            return e.find(h, k);
2217 >                    }
2218 >                    if ((e = e.next) == null)
2219 >                        return null;
2220 >                }
2221 >            }
2222 >        }
2223      }
2224  
2225      /**
2226 <     * 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.
2226 >     * A place-holder node used in computeIfAbsent and compute
2227       */
2228 <    public Set<Map.Entry<K,V>> entrySet() {
2229 <        EntrySet<K,V> es = entrySet;
2230 <        return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
2228 >    static final class ReservationNode<K,V> extends Node<K,V> {
2229 >        ReservationNode() {
2230 >            super(RESERVED, null, null, null);
2231 >        }
2232 >
2233 >        Node<K,V> find(int h, Object k) {
2234 >            return null;
2235 >        }
2236      }
2237  
2238 +    /* ---------------- Table Initialization and Resizing -------------- */
2239 +
2240      /**
2241 <     * Returns an enumeration of the keys in this table.
2242 <     *
3126 <     * @return an enumeration of the keys in this table
3127 <     * @see #keySet()
2241 >     * Returns the stamp bits for resizing a table of size n.
2242 >     * Must be negative when shifted left by RESIZE_STAMP_SHIFT.
2243       */
2244 <    public Enumeration<K> keys() {
2245 <        return new KeyIterator<K,V>(this);
2244 >    static final int resizeStamp(int n) {
2245 >        return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
2246      }
2247  
2248      /**
2249 <     * Returns an enumeration of the values in this table.
3135 <     *
3136 <     * @return an enumeration of the values in this table
3137 <     * @see #values()
2249 >     * Initializes table, using the size recorded in sizeCtl.
2250       */
2251 <    public Enumeration<V> elements() {
2252 <        return new ValueIterator<K,V>(this);
2251 >    private final Node<K,V>[] initTable() {
2252 >        Node<K,V>[] tab; int sc;
2253 >        while ((tab = table) == null || tab.length == 0) {
2254 >            if ((sc = sizeCtl) < 0)
2255 >                Thread.yield(); // lost initialization race; just spin
2256 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2257 >                try {
2258 >                    if ((tab = table) == null || tab.length == 0) {
2259 >                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2260 >                        @SuppressWarnings("unchecked")
2261 >                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2262 >                        table = tab = nt;
2263 >                        sc = n - (n >>> 2);
2264 >                    }
2265 >                } finally {
2266 >                    sizeCtl = sc;
2267 >                }
2268 >                break;
2269 >            }
2270 >        }
2271 >        return tab;
2272      }
2273  
2274      /**
2275 <     * Returns a partitionable iterator of the keys in this map.
2276 <     *
2277 <     * @return a partitionable iterator of the keys in this map
2278 <     */
2279 <    public Spliterator<K> keySpliterator() {
2280 <        return new KeyIterator<K,V>(this);
2275 >     * Adds to count, and if table is too small and not already
2276 >     * resizing, initiates transfer. If already resizing, helps
2277 >     * perform transfer if work is available.  Rechecks occupancy
2278 >     * after a transfer to see if another resize is already needed
2279 >     * because resizings are lagging additions.
2280 >     *
2281 >     * @param x the count to add
2282 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
2283 >     */
2284 >    private final void addCount(long x, int check) {
2285 >        CounterCell[] as; long b, s;
2286 >        if ((as = counterCells) != null ||
2287 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2288 >            CounterCell a; long v; int m;
2289 >            boolean uncontended = true;
2290 >            if (as == null || (m = as.length - 1) < 0 ||
2291 >                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
2292 >                !(uncontended =
2293 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2294 >                fullAddCount(x, uncontended);
2295 >                return;
2296 >            }
2297 >            if (check <= 1)
2298 >                return;
2299 >            s = sumCount();
2300 >        }
2301 >        if (check >= 0) {
2302 >            Node<K,V>[] tab, nt; int n, sc;
2303 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2304 >                   (n = tab.length) < MAXIMUM_CAPACITY) {
2305 >                int rs = resizeStamp(n);
2306 >                if (sc < 0) {
2307 >                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2308 >                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
2309 >                        transferIndex <= 0)
2310 >                        break;
2311 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
2312 >                        transfer(tab, nt);
2313 >                }
2314 >                else if (U.compareAndSwapInt(this, SIZECTL, sc,
2315 >                                             (rs << RESIZE_STAMP_SHIFT) + 2))
2316 >                    transfer(tab, null);
2317 >                s = sumCount();
2318 >            }
2319 >        }
2320      }
2321  
2322      /**
2323 <     * Returns a partitionable iterator of the values in this map.
3154 <     *
3155 <     * @return a partitionable iterator of the values in this map
2323 >     * Helps transfer if a resize is in progress.
2324       */
2325 <    public Spliterator<V> valueSpliterator() {
2326 <        return new ValueIterator<K,V>(this);
2325 >    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2326 >        Node<K,V>[] nextTab; int sc;
2327 >        if (tab != null && (f instanceof ForwardingNode) &&
2328 >            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2329 >            int rs = resizeStamp(tab.length);
2330 >            while (nextTab == nextTable && table == tab &&
2331 >                   (sc = sizeCtl) < 0) {
2332 >                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2333 >                    sc == rs + MAX_RESIZERS || transferIndex <= 0)
2334 >                    break;
2335 >                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
2336 >                    transfer(tab, nextTab);
2337 >                    break;
2338 >                }
2339 >            }
2340 >            return nextTab;
2341 >        }
2342 >        return table;
2343      }
2344  
2345      /**
2346 <     * Returns a partitionable iterator of the entries in this map.
2346 >     * Tries to presize table to accommodate the given number of elements.
2347       *
2348 <     * @return a partitionable iterator of the entries in this map
2348 >     * @param size number of elements (doesn't need to be perfectly accurate)
2349       */
2350 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
2351 <        return new EntryIterator<K,V>(this);
2350 >    private final void tryPresize(int size) {
2351 >        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2352 >            tableSizeFor(size + (size >>> 1) + 1);
2353 >        int sc;
2354 >        while ((sc = sizeCtl) >= 0) {
2355 >            Node<K,V>[] tab = table; int n;
2356 >            if (tab == null || (n = tab.length) == 0) {
2357 >                n = (sc > c) ? sc : c;
2358 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2359 >                    try {
2360 >                        if (table == tab) {
2361 >                            @SuppressWarnings("unchecked")
2362 >                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2363 >                            table = nt;
2364 >                            sc = n - (n >>> 2);
2365 >                        }
2366 >                    } finally {
2367 >                        sizeCtl = sc;
2368 >                    }
2369 >                }
2370 >            }
2371 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
2372 >                break;
2373 >            else if (tab == table) {
2374 >                int rs = resizeStamp(n);
2375 >                if (U.compareAndSwapInt(this, SIZECTL, sc,
2376 >                                        (rs << RESIZE_STAMP_SHIFT) + 2))
2377 >                    transfer(tab, null);
2378 >            }
2379 >        }
2380      }
2381  
2382      /**
2383 <     * Returns the hash code value for this {@link Map}, i.e.,
2384 <     * 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
2383 >     * Moves and/or copies the nodes in each bin to new table. See
2384 >     * above for explanation.
2385       */
2386 <    public int hashCode() {
2387 <        int h = 0;
2388 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2389 <        Object v;
2390 <        while ((v = it.advance()) != null) {
2391 <            h += it.nextKey.hashCode() ^ v.hashCode();
2386 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2387 >        int n = tab.length, stride;
2388 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2389 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
2390 >        if (nextTab == null) {            // initiating
2391 >            try {
2392 >                @SuppressWarnings("unchecked")
2393 >                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
2394 >                nextTab = nt;
2395 >            } catch (Throwable ex) {      // try to cope with OOME
2396 >                sizeCtl = Integer.MAX_VALUE;
2397 >                return;
2398 >            }
2399 >            nextTable = nextTab;
2400 >            transferIndex = n;
2401 >        }
2402 >        int nextn = nextTab.length;
2403 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2404 >        boolean advance = true;
2405 >        boolean finishing = false; // to ensure sweep before committing nextTab
2406 >        for (int i = 0, bound = 0;;) {
2407 >            Node<K,V> f; int fh;
2408 >            while (advance) {
2409 >                int nextIndex, nextBound;
2410 >                if (--i >= bound || finishing)
2411 >                    advance = false;
2412 >                else if ((nextIndex = transferIndex) <= 0) {
2413 >                    i = -1;
2414 >                    advance = false;
2415 >                }
2416 >                else if (U.compareAndSwapInt
2417 >                         (this, TRANSFERINDEX, nextIndex,
2418 >                          nextBound = (nextIndex > stride ?
2419 >                                       nextIndex - stride : 0))) {
2420 >                    bound = nextBound;
2421 >                    i = nextIndex - 1;
2422 >                    advance = false;
2423 >                }
2424 >            }
2425 >            if (i < 0 || i >= n || i + n >= nextn) {
2426 >                int sc;
2427 >                if (finishing) {
2428 >                    nextTable = null;
2429 >                    table = nextTab;
2430 >                    sizeCtl = (n << 1) - (n >>> 1);
2431 >                    return;
2432 >                }
2433 >                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
2434 >                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
2435 >                        return;
2436 >                    finishing = advance = true;
2437 >                    i = n; // recheck before commit
2438 >                }
2439 >            }
2440 >            else if ((f = tabAt(tab, i)) == null)
2441 >                advance = casTabAt(tab, i, null, fwd);
2442 >            else if ((fh = f.hash) == MOVED)
2443 >                advance = true; // already processed
2444 >            else {
2445 >                synchronized (f) {
2446 >                    if (tabAt(tab, i) == f) {
2447 >                        Node<K,V> ln, hn;
2448 >                        if (fh >= 0) {
2449 >                            int runBit = fh & n;
2450 >                            Node<K,V> lastRun = f;
2451 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2452 >                                int b = p.hash & n;
2453 >                                if (b != runBit) {
2454 >                                    runBit = b;
2455 >                                    lastRun = p;
2456 >                                }
2457 >                            }
2458 >                            if (runBit == 0) {
2459 >                                ln = lastRun;
2460 >                                hn = null;
2461 >                            }
2462 >                            else {
2463 >                                hn = lastRun;
2464 >                                ln = null;
2465 >                            }
2466 >                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2467 >                                int ph = p.hash; K pk = p.key; V pv = p.val;
2468 >                                if ((ph & n) == 0)
2469 >                                    ln = new Node<K,V>(ph, pk, pv, ln);
2470 >                                else
2471 >                                    hn = new Node<K,V>(ph, pk, pv, hn);
2472 >                            }
2473 >                            setTabAt(nextTab, i, ln);
2474 >                            setTabAt(nextTab, i + n, hn);
2475 >                            setTabAt(tab, i, fwd);
2476 >                            advance = true;
2477 >                        }
2478 >                        else if (f instanceof TreeBin) {
2479 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2480 >                            TreeNode<K,V> lo = null, loTail = null;
2481 >                            TreeNode<K,V> hi = null, hiTail = null;
2482 >                            int lc = 0, hc = 0;
2483 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2484 >                                int h = e.hash;
2485 >                                TreeNode<K,V> p = new TreeNode<K,V>
2486 >                                    (h, e.key, e.val, null, null);
2487 >                                if ((h & n) == 0) {
2488 >                                    if ((p.prev = loTail) == null)
2489 >                                        lo = p;
2490 >                                    else
2491 >                                        loTail.next = p;
2492 >                                    loTail = p;
2493 >                                    ++lc;
2494 >                                }
2495 >                                else {
2496 >                                    if ((p.prev = hiTail) == null)
2497 >                                        hi = p;
2498 >                                    else
2499 >                                        hiTail.next = p;
2500 >                                    hiTail = p;
2501 >                                    ++hc;
2502 >                                }
2503 >                            }
2504 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2505 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2506 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2507 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2508 >                            setTabAt(nextTab, i, ln);
2509 >                            setTabAt(nextTab, i + n, hn);
2510 >                            setTabAt(tab, i, fwd);
2511 >                            advance = true;
2512 >                        }
2513 >                    }
2514 >                }
2515 >            }
2516          }
3184        return h;
2517      }
2518  
2519 +    /* ---------------- Counter support -------------- */
2520 +
2521      /**
2522 <     * Returns a string representation of this map.  The string
2523 <     * 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
2522 >     * A padded cell for distributing counts.  Adapted from LongAdder
2523 >     * and Striped64.  See their internal docs for explanation.
2524       */
2525 <    public String toString() {
2526 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2527 <        StringBuilder sb = new StringBuilder();
2528 <        sb.append('{');
2529 <        Object v;
2530 <        if ((v = it.advance()) != null) {
2531 <            for (;;) {
2532 <                Object k = it.nextKey;
2533 <                sb.append(k == this ? "(this Map)" : k);
2534 <                sb.append('=');
2535 <                sb.append(v == this ? "(this Map)" : v);
2536 <                if ((v = it.advance()) == null)
2525 >    @sun.misc.Contended static final class CounterCell {
2526 >        volatile long value;
2527 >        CounterCell(long x) { value = x; }
2528 >    }
2529 >
2530 >    final long sumCount() {
2531 >        CounterCell[] as = counterCells; CounterCell a;
2532 >        long sum = baseCount;
2533 >        if (as != null) {
2534 >            for (int i = 0; i < as.length; ++i) {
2535 >                if ((a = as[i]) != null)
2536 >                    sum += a.value;
2537 >            }
2538 >        }
2539 >        return sum;
2540 >    }
2541 >
2542 >    // See LongAdder version for explanation
2543 >    private final void fullAddCount(long x, boolean wasUncontended) {
2544 >        int h;
2545 >        if ((h = ThreadLocalRandom.getProbe()) == 0) {
2546 >            ThreadLocalRandom.localInit();      // force initialization
2547 >            h = ThreadLocalRandom.getProbe();
2548 >            wasUncontended = true;
2549 >        }
2550 >        boolean collide = false;                // True if last slot nonempty
2551 >        for (;;) {
2552 >            CounterCell[] as; CounterCell a; int n; long v;
2553 >            if ((as = counterCells) != null && (n = as.length) > 0) {
2554 >                if ((a = as[(n - 1) & h]) == null) {
2555 >                    if (cellsBusy == 0) {            // Try to attach new Cell
2556 >                        CounterCell r = new CounterCell(x); // Optimistic create
2557 >                        if (cellsBusy == 0 &&
2558 >                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2559 >                            boolean created = false;
2560 >                            try {               // Recheck under lock
2561 >                                CounterCell[] rs; int m, j;
2562 >                                if ((rs = counterCells) != null &&
2563 >                                    (m = rs.length) > 0 &&
2564 >                                    rs[j = (m - 1) & h] == null) {
2565 >                                    rs[j] = r;
2566 >                                    created = true;
2567 >                                }
2568 >                            } finally {
2569 >                                cellsBusy = 0;
2570 >                            }
2571 >                            if (created)
2572 >                                break;
2573 >                            continue;           // Slot is now non-empty
2574 >                        }
2575 >                    }
2576 >                    collide = false;
2577 >                }
2578 >                else if (!wasUncontended)       // CAS already known to fail
2579 >                    wasUncontended = true;      // Continue after rehash
2580 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2581 >                    break;
2582 >                else if (counterCells != as || n >= NCPU)
2583 >                    collide = false;            // At max size or stale
2584 >                else if (!collide)
2585 >                    collide = true;
2586 >                else if (cellsBusy == 0 &&
2587 >                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2588 >                    try {
2589 >                        if (counterCells == as) {// Expand table unless stale
2590 >                            CounterCell[] rs = new CounterCell[n << 1];
2591 >                            for (int i = 0; i < n; ++i)
2592 >                                rs[i] = as[i];
2593 >                            counterCells = rs;
2594 >                        }
2595 >                    } finally {
2596 >                        cellsBusy = 0;
2597 >                    }
2598 >                    collide = false;
2599 >                    continue;                   // Retry with expanded table
2600 >                }
2601 >                h = ThreadLocalRandom.advanceProbe(h);
2602 >            }
2603 >            else if (cellsBusy == 0 && counterCells == as &&
2604 >                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2605 >                boolean init = false;
2606 >                try {                           // Initialize table
2607 >                    if (counterCells == as) {
2608 >                        CounterCell[] rs = new CounterCell[2];
2609 >                        rs[h & 1] = new CounterCell(x);
2610 >                        counterCells = rs;
2611 >                        init = true;
2612 >                    }
2613 >                } finally {
2614 >                    cellsBusy = 0;
2615 >                }
2616 >                if (init)
2617                      break;
3211                sb.append(',').append(' ');
2618              }
2619 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2620 +                break;                          // Fall back on using base
2621          }
3214        return sb.append('}').toString();
2622      }
2623  
2624 +    /* ---------------- Conversion from/to TreeBins -------------- */
2625 +
2626      /**
2627 <     * Compares the specified object with this map for equality.
2628 <     * Returns {@code true} if the given object is a map with the same
2629 <     * mappings as this map.  This operation may return misleading
2630 <     * results if either map is concurrently modified during execution
2631 <     * of this method.
2632 <     *
2633 <     * @param o object to be compared for equality with this map
2634 <     * @return {@code true} if the specified object is equal to this map
2627 >     * Replaces all linked nodes in bin at given index unless table is
2628 >     * too small, in which case resizes instead.
2629 >     */
2630 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2631 >        Node<K,V> b; int n;
2632 >        if (tab != null) {
2633 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
2634 >                tryPresize(n << 1);
2635 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2636 >                synchronized (b) {
2637 >                    if (tabAt(tab, index) == b) {
2638 >                        TreeNode<K,V> hd = null, tl = null;
2639 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2640 >                            TreeNode<K,V> p =
2641 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2642 >                                                  null, null);
2643 >                            if ((p.prev = tl) == null)
2644 >                                hd = p;
2645 >                            else
2646 >                                tl.next = p;
2647 >                            tl = p;
2648 >                        }
2649 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2650 >                    }
2651 >                }
2652 >            }
2653 >        }
2654 >    }
2655 >
2656 >    /**
2657 >     * Returns a list on non-TreeNodes replacing those in given list.
2658       */
2659 <    public boolean equals(Object o) {
2660 <        if (o != this) {
2661 <            if (!(o instanceof Map))
2662 <                return false;
2663 <            Map<?,?> m = (Map<?,?>) o;
2664 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2665 <            Object val;
2666 <            while ((val = it.advance()) != null) {
2667 <                Object v = m.get(it.nextKey);
2668 <                if (v == null || (v != val && !v.equals(val)))
2669 <                    return false;
2659 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2660 >        Node<K,V> hd = null, tl = null;
2661 >        for (Node<K,V> q = b; q != null; q = q.next) {
2662 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2663 >            if (tl == null)
2664 >                hd = p;
2665 >            else
2666 >                tl.next = p;
2667 >            tl = p;
2668 >        }
2669 >        return hd;
2670 >    }
2671 >
2672 >    /* ---------------- TreeNodes -------------- */
2673 >
2674 >    /**
2675 >     * Nodes for use in TreeBins
2676 >     */
2677 >    static final class TreeNode<K,V> extends Node<K,V> {
2678 >        TreeNode<K,V> parent;  // red-black tree links
2679 >        TreeNode<K,V> left;
2680 >        TreeNode<K,V> right;
2681 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2682 >        boolean red;
2683 >
2684 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2685 >                 TreeNode<K,V> parent) {
2686 >            super(hash, key, val, next);
2687 >            this.parent = parent;
2688 >        }
2689 >
2690 >        Node<K,V> find(int h, Object k) {
2691 >            return findTreeNode(h, k, null);
2692 >        }
2693 >
2694 >        /**
2695 >         * Returns the TreeNode (or null if not found) for the given key
2696 >         * starting at given root.
2697 >         */
2698 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2699 >            if (k != null) {
2700 >                TreeNode<K,V> p = this;
2701 >                do {
2702 >                    int ph, dir; K pk; TreeNode<K,V> q;
2703 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2704 >                    if ((ph = p.hash) > h)
2705 >                        p = pl;
2706 >                    else if (ph < h)
2707 >                        p = pr;
2708 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2709 >                        return p;
2710 >                    else if (pl == null)
2711 >                        p = pr;
2712 >                    else if (pr == null)
2713 >                        p = pl;
2714 >                    else if ((kc != null ||
2715 >                              (kc = comparableClassFor(k)) != null) &&
2716 >                             (dir = compareComparables(kc, k, pk)) != 0)
2717 >                        p = (dir < 0) ? pl : pr;
2718 >                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
2719 >                        return q;
2720 >                    else
2721 >                        p = pl;
2722 >                } while (p != null);
2723              }
2724 <            for (Map.Entry<?,?> e : m.entrySet()) {
2725 <                Object mk, mv, v;
2726 <                if ((mk = e.getKey()) == null ||
2727 <                    (mv = e.getValue()) == null ||
2728 <                    (v = internalGet(mk)) == null ||
2729 <                    (mv != v && !mv.equals(v)))
2730 <                    return false;
2724 >            return null;
2725 >        }
2726 >    }
2727 >
2728 >    /* ---------------- TreeBins -------------- */
2729 >
2730 >    /**
2731 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2732 >     * keys or values, but instead point to list of TreeNodes and
2733 >     * their root. They also maintain a parasitic read-write lock
2734 >     * forcing writers (who hold bin lock) to wait for readers (who do
2735 >     * not) to complete before tree restructuring operations.
2736 >     */
2737 >    static final class TreeBin<K,V> extends Node<K,V> {
2738 >        TreeNode<K,V> root;
2739 >        volatile TreeNode<K,V> first;
2740 >        volatile Thread waiter;
2741 >        volatile int lockState;
2742 >        // values for lockState
2743 >        static final int WRITER = 1; // set while holding write lock
2744 >        static final int WAITER = 2; // set when waiting for write lock
2745 >        static final int READER = 4; // increment value for setting read lock
2746 >
2747 >        /**
2748 >         * Tie-breaking utility for ordering insertions when equal
2749 >         * hashCodes and non-comparable. We don't require a total
2750 >         * order, just a consistent insertion rule to maintain
2751 >         * equivalence across rebalancings. Tie-breaking further than
2752 >         * necessary simplifies testing a bit.
2753 >         */
2754 >        static int tieBreakOrder(Object a, Object b) {
2755 >            int d;
2756 >            if (a == null || b == null ||
2757 >                (d = a.getClass().getName().
2758 >                 compareTo(b.getClass().getName())) == 0)
2759 >                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2760 >                     -1 : 1);
2761 >            return d;
2762 >        }
2763 >
2764 >        /**
2765 >         * Creates bin with initial set of nodes headed by b.
2766 >         */
2767 >        TreeBin(TreeNode<K,V> b) {
2768 >            super(TREEBIN, null, null, null);
2769 >            this.first = b;
2770 >            TreeNode<K,V> r = null;
2771 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2772 >                next = (TreeNode<K,V>)x.next;
2773 >                x.left = x.right = null;
2774 >                if (r == null) {
2775 >                    x.parent = null;
2776 >                    x.red = false;
2777 >                    r = x;
2778 >                }
2779 >                else {
2780 >                    K k = x.key;
2781 >                    int h = x.hash;
2782 >                    Class<?> kc = null;
2783 >                    for (TreeNode<K,V> p = r;;) {
2784 >                        int dir, ph;
2785 >                        K pk = p.key;
2786 >                        if ((ph = p.hash) > h)
2787 >                            dir = -1;
2788 >                        else if (ph < h)
2789 >                            dir = 1;
2790 >                        else if ((kc == null &&
2791 >                                  (kc = comparableClassFor(k)) == null) ||
2792 >                                 (dir = compareComparables(kc, k, pk)) == 0)
2793 >                            dir = tieBreakOrder(k, pk);
2794 >                        TreeNode<K,V> xp = p;
2795 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2796 >                            x.parent = xp;
2797 >                            if (dir <= 0)
2798 >                                xp.left = x;
2799 >                            else
2800 >                                xp.right = x;
2801 >                            r = balanceInsertion(r, x);
2802 >                            break;
2803 >                        }
2804 >                    }
2805 >                }
2806 >            }
2807 >            this.root = r;
2808 >            assert checkInvariants(root);
2809 >        }
2810 >
2811 >        /**
2812 >         * Acquires write lock for tree restructuring.
2813 >         */
2814 >        private final void lockRoot() {
2815 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2816 >                contendedLock(); // offload to separate method
2817 >        }
2818 >
2819 >        /**
2820 >         * Releases write lock for tree restructuring.
2821 >         */
2822 >        private final void unlockRoot() {
2823 >            lockState = 0;
2824 >        }
2825 >
2826 >        /**
2827 >         * Possibly blocks awaiting root lock.
2828 >         */
2829 >        private final void contendedLock() {
2830 >            boolean waiting = false;
2831 >            for (int s;;) {
2832 >                if (((s = lockState) & ~WAITER) == 0) {
2833 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2834 >                        if (waiting)
2835 >                            waiter = null;
2836 >                        return;
2837 >                    }
2838 >                }
2839 >                else if ((s & WAITER) == 0) {
2840 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2841 >                        waiting = true;
2842 >                        waiter = Thread.currentThread();
2843 >                    }
2844 >                }
2845 >                else if (waiting)
2846 >                    LockSupport.park(this);
2847 >            }
2848 >        }
2849 >
2850 >        /**
2851 >         * Returns matching node or null if none. Tries to search
2852 >         * using tree comparisons from root, but continues linear
2853 >         * search when lock not available.
2854 >         */
2855 >        final Node<K,V> find(int h, Object k) {
2856 >            if (k != null) {
2857 >                for (Node<K,V> e = first; e != null; ) {
2858 >                    int s; K ek;
2859 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2860 >                        if (e.hash == h &&
2861 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2862 >                            return e;
2863 >                        e = e.next;
2864 >                    }
2865 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2866 >                                                 s + READER)) {
2867 >                        TreeNode<K,V> r, p;
2868 >                        try {
2869 >                            p = ((r = root) == null ? null :
2870 >                                 r.findTreeNode(h, k, null));
2871 >                        } finally {
2872 >                            Thread w;
2873 >                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2874 >                                (READER|WAITER) && (w = waiter) != null)
2875 >                                LockSupport.unpark(w);
2876 >                        }
2877 >                        return p;
2878 >                    }
2879 >                }
2880 >            }
2881 >            return null;
2882 >        }
2883 >
2884 >        /**
2885 >         * Finds or adds a node.
2886 >         * @return null if added
2887 >         */
2888 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2889 >            Class<?> kc = null;
2890 >            boolean searched = false;
2891 >            for (TreeNode<K,V> p = root;;) {
2892 >                int dir, ph; K pk;
2893 >                if (p == null) {
2894 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2895 >                    break;
2896 >                }
2897 >                else if ((ph = p.hash) > h)
2898 >                    dir = -1;
2899 >                else if (ph < h)
2900 >                    dir = 1;
2901 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2902 >                    return p;
2903 >                else if ((kc == null &&
2904 >                          (kc = comparableClassFor(k)) == null) ||
2905 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2906 >                    if (!searched) {
2907 >                        TreeNode<K,V> q, ch;
2908 >                        searched = true;
2909 >                        if (((ch = p.left) != null &&
2910 >                             (q = ch.findTreeNode(h, k, kc)) != null) ||
2911 >                            ((ch = p.right) != null &&
2912 >                             (q = ch.findTreeNode(h, k, kc)) != null))
2913 >                            return q;
2914 >                    }
2915 >                    dir = tieBreakOrder(k, pk);
2916 >                }
2917 >
2918 >                TreeNode<K,V> xp = p;
2919 >                if ((p = (dir <= 0) ? p.left : p.right) == null) {
2920 >                    TreeNode<K,V> x, f = first;
2921 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2922 >                    if (f != null)
2923 >                        f.prev = x;
2924 >                    if (dir <= 0)
2925 >                        xp.left = x;
2926 >                    else
2927 >                        xp.right = x;
2928 >                    if (!xp.red)
2929 >                        x.red = true;
2930 >                    else {
2931 >                        lockRoot();
2932 >                        try {
2933 >                            root = balanceInsertion(root, x);
2934 >                        } finally {
2935 >                            unlockRoot();
2936 >                        }
2937 >                    }
2938 >                    break;
2939 >                }
2940 >            }
2941 >            assert checkInvariants(root);
2942 >            return null;
2943 >        }
2944 >
2945 >        /**
2946 >         * Removes the given node, that must be present before this
2947 >         * call.  This is messier than typical red-black deletion code
2948 >         * because we cannot swap the contents of an interior node
2949 >         * with a leaf successor that is pinned by "next" pointers
2950 >         * that are accessible independently of lock. So instead we
2951 >         * swap the tree linkages.
2952 >         *
2953 >         * @return true if now too small, so should be untreeified
2954 >         */
2955 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2956 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2957 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2958 >            TreeNode<K,V> r, rl;
2959 >            if (pred == null)
2960 >                first = next;
2961 >            else
2962 >                pred.next = next;
2963 >            if (next != null)
2964 >                next.prev = pred;
2965 >            if (first == null) {
2966 >                root = null;
2967 >                return true;
2968 >            }
2969 >            if ((r = root) == null || r.right == null || // too small
2970 >                (rl = r.left) == null || rl.left == null)
2971 >                return true;
2972 >            lockRoot();
2973 >            try {
2974 >                TreeNode<K,V> replacement;
2975 >                TreeNode<K,V> pl = p.left;
2976 >                TreeNode<K,V> pr = p.right;
2977 >                if (pl != null && pr != null) {
2978 >                    TreeNode<K,V> s = pr, sl;
2979 >                    while ((sl = s.left) != null) // find successor
2980 >                        s = sl;
2981 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2982 >                    TreeNode<K,V> sr = s.right;
2983 >                    TreeNode<K,V> pp = p.parent;
2984 >                    if (s == pr) { // p was s's direct parent
2985 >                        p.parent = s;
2986 >                        s.right = p;
2987 >                    }
2988 >                    else {
2989 >                        TreeNode<K,V> sp = s.parent;
2990 >                        if ((p.parent = sp) != null) {
2991 >                            if (s == sp.left)
2992 >                                sp.left = p;
2993 >                            else
2994 >                                sp.right = p;
2995 >                        }
2996 >                        if ((s.right = pr) != null)
2997 >                            pr.parent = s;
2998 >                    }
2999 >                    p.left = null;
3000 >                    if ((p.right = sr) != null)
3001 >                        sr.parent = p;
3002 >                    if ((s.left = pl) != null)
3003 >                        pl.parent = s;
3004 >                    if ((s.parent = pp) == null)
3005 >                        r = s;
3006 >                    else if (p == pp.left)
3007 >                        pp.left = s;
3008 >                    else
3009 >                        pp.right = s;
3010 >                    if (sr != null)
3011 >                        replacement = sr;
3012 >                    else
3013 >                        replacement = p;
3014 >                }
3015 >                else if (pl != null)
3016 >                    replacement = pl;
3017 >                else if (pr != null)
3018 >                    replacement = pr;
3019 >                else
3020 >                    replacement = p;
3021 >                if (replacement != p) {
3022 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
3023 >                    if (pp == null)
3024 >                        r = replacement;
3025 >                    else if (p == pp.left)
3026 >                        pp.left = replacement;
3027 >                    else
3028 >                        pp.right = replacement;
3029 >                    p.left = p.right = p.parent = null;
3030 >                }
3031 >
3032 >                root = (p.red) ? r : balanceDeletion(r, replacement);
3033 >
3034 >                if (p == replacement) {  // detach pointers
3035 >                    TreeNode<K,V> pp;
3036 >                    if ((pp = p.parent) != null) {
3037 >                        if (p == pp.left)
3038 >                            pp.left = null;
3039 >                        else if (p == pp.right)
3040 >                            pp.right = null;
3041 >                        p.parent = null;
3042 >                    }
3043 >                }
3044 >            } finally {
3045 >                unlockRoot();
3046 >            }
3047 >            assert checkInvariants(root);
3048 >            return false;
3049 >        }
3050 >
3051 >        /* ------------------------------------------------------------ */
3052 >        // Red-black tree methods, all adapted from CLR
3053 >
3054 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
3055 >                                              TreeNode<K,V> p) {
3056 >            TreeNode<K,V> r, pp, rl;
3057 >            if (p != null && (r = p.right) != null) {
3058 >                if ((rl = p.right = r.left) != null)
3059 >                    rl.parent = p;
3060 >                if ((pp = r.parent = p.parent) == null)
3061 >                    (root = r).red = false;
3062 >                else if (pp.left == p)
3063 >                    pp.left = r;
3064 >                else
3065 >                    pp.right = r;
3066 >                r.left = p;
3067 >                p.parent = r;
3068 >            }
3069 >            return root;
3070 >        }
3071 >
3072 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
3073 >                                               TreeNode<K,V> p) {
3074 >            TreeNode<K,V> l, pp, lr;
3075 >            if (p != null && (l = p.left) != null) {
3076 >                if ((lr = p.left = l.right) != null)
3077 >                    lr.parent = p;
3078 >                if ((pp = l.parent = p.parent) == null)
3079 >                    (root = l).red = false;
3080 >                else if (pp.right == p)
3081 >                    pp.right = l;
3082 >                else
3083 >                    pp.left = l;
3084 >                l.right = p;
3085 >                p.parent = l;
3086 >            }
3087 >            return root;
3088 >        }
3089 >
3090 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
3091 >                                                    TreeNode<K,V> x) {
3092 >            x.red = true;
3093 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
3094 >                if ((xp = x.parent) == null) {
3095 >                    x.red = false;
3096 >                    return x;
3097 >                }
3098 >                else if (!xp.red || (xpp = xp.parent) == null)
3099 >                    return root;
3100 >                if (xp == (xppl = xpp.left)) {
3101 >                    if ((xppr = xpp.right) != null && xppr.red) {
3102 >                        xppr.red = false;
3103 >                        xp.red = false;
3104 >                        xpp.red = true;
3105 >                        x = xpp;
3106 >                    }
3107 >                    else {
3108 >                        if (x == xp.right) {
3109 >                            root = rotateLeft(root, x = xp);
3110 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3111 >                        }
3112 >                        if (xp != null) {
3113 >                            xp.red = false;
3114 >                            if (xpp != null) {
3115 >                                xpp.red = true;
3116 >                                root = rotateRight(root, xpp);
3117 >                            }
3118 >                        }
3119 >                    }
3120 >                }
3121 >                else {
3122 >                    if (xppl != null && xppl.red) {
3123 >                        xppl.red = false;
3124 >                        xp.red = false;
3125 >                        xpp.red = true;
3126 >                        x = xpp;
3127 >                    }
3128 >                    else {
3129 >                        if (x == xp.left) {
3130 >                            root = rotateRight(root, x = xp);
3131 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3132 >                        }
3133 >                        if (xp != null) {
3134 >                            xp.red = false;
3135 >                            if (xpp != null) {
3136 >                                xpp.red = true;
3137 >                                root = rotateLeft(root, xpp);
3138 >                            }
3139 >                        }
3140 >                    }
3141 >                }
3142 >            }
3143 >        }
3144 >
3145 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3146 >                                                   TreeNode<K,V> x) {
3147 >            for (TreeNode<K,V> xp, xpl, xpr;;) {
3148 >                if (x == null || x == root)
3149 >                    return root;
3150 >                else if ((xp = x.parent) == null) {
3151 >                    x.red = false;
3152 >                    return x;
3153 >                }
3154 >                else if (x.red) {
3155 >                    x.red = false;
3156 >                    return root;
3157 >                }
3158 >                else if ((xpl = xp.left) == x) {
3159 >                    if ((xpr = xp.right) != null && xpr.red) {
3160 >                        xpr.red = false;
3161 >                        xp.red = true;
3162 >                        root = rotateLeft(root, xp);
3163 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3164 >                    }
3165 >                    if (xpr == null)
3166 >                        x = xp;
3167 >                    else {
3168 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3169 >                        if ((sr == null || !sr.red) &&
3170 >                            (sl == null || !sl.red)) {
3171 >                            xpr.red = true;
3172 >                            x = xp;
3173 >                        }
3174 >                        else {
3175 >                            if (sr == null || !sr.red) {
3176 >                                if (sl != null)
3177 >                                    sl.red = false;
3178 >                                xpr.red = true;
3179 >                                root = rotateRight(root, xpr);
3180 >                                xpr = (xp = x.parent) == null ?
3181 >                                    null : xp.right;
3182 >                            }
3183 >                            if (xpr != null) {
3184 >                                xpr.red = (xp == null) ? false : xp.red;
3185 >                                if ((sr = xpr.right) != null)
3186 >                                    sr.red = false;
3187 >                            }
3188 >                            if (xp != null) {
3189 >                                xp.red = false;
3190 >                                root = rotateLeft(root, xp);
3191 >                            }
3192 >                            x = root;
3193 >                        }
3194 >                    }
3195 >                }
3196 >                else { // symmetric
3197 >                    if (xpl != null && xpl.red) {
3198 >                        xpl.red = false;
3199 >                        xp.red = true;
3200 >                        root = rotateRight(root, xp);
3201 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3202 >                    }
3203 >                    if (xpl == null)
3204 >                        x = xp;
3205 >                    else {
3206 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3207 >                        if ((sl == null || !sl.red) &&
3208 >                            (sr == null || !sr.red)) {
3209 >                            xpl.red = true;
3210 >                            x = xp;
3211 >                        }
3212 >                        else {
3213 >                            if (sl == null || !sl.red) {
3214 >                                if (sr != null)
3215 >                                    sr.red = false;
3216 >                                xpl.red = true;
3217 >                                root = rotateLeft(root, xpl);
3218 >                                xpl = (xp = x.parent) == null ?
3219 >                                    null : xp.left;
3220 >                            }
3221 >                            if (xpl != null) {
3222 >                                xpl.red = (xp == null) ? false : xp.red;
3223 >                                if ((sl = xpl.left) != null)
3224 >                                    sl.red = false;
3225 >                            }
3226 >                            if (xp != null) {
3227 >                                xp.red = false;
3228 >                                root = rotateRight(root, xp);
3229 >                            }
3230 >                            x = root;
3231 >                        }
3232 >                    }
3233 >                }
3234 >            }
3235 >        }
3236 >
3237 >        /**
3238 >         * Recursive invariant check
3239 >         */
3240 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3241 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3242 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3243 >            if (tb != null && tb.next != t)
3244 >                return false;
3245 >            if (tn != null && tn.prev != t)
3246 >                return false;
3247 >            if (tp != null && t != tp.left && t != tp.right)
3248 >                return false;
3249 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3250 >                return false;
3251 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3252 >                return false;
3253 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3254 >                return false;
3255 >            if (tl != null && !checkInvariants(tl))
3256 >                return false;
3257 >            if (tr != null && !checkInvariants(tr))
3258 >                return false;
3259 >            return true;
3260 >        }
3261 >
3262 >        private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
3263 >        private static final long LOCKSTATE;
3264 >        static {
3265 >            try {
3266 >                LOCKSTATE = U.objectFieldOffset
3267 >                    (TreeBin.class.getDeclaredField("lockState"));
3268 >            } catch (ReflectiveOperationException e) {
3269 >                throw new Error(e);
3270              }
3271          }
3248        return true;
3272      }
3273  
3274 <    /* ----------------Iterators -------------- */
3274 >    /* ----------------Table Traversal -------------- */
3275 >
3276 >    /**
3277 >     * Records the table, its length, and current traversal index for a
3278 >     * traverser that must process a region of a forwarded table before
3279 >     * proceeding with current table.
3280 >     */
3281 >    static final class TableStack<K,V> {
3282 >        int length;
3283 >        int index;
3284 >        Node<K,V>[] tab;
3285 >        TableStack<K,V> next;
3286 >    }
3287  
3288 <    @SuppressWarnings("serial") static final class KeyIterator<K,V> extends Traverser<K,V,Object>
3289 <        implements Spliterator<K>, Enumeration<K> {
3290 <        KeyIterator(ConcurrentHashMap<K, V> map) { super(map); }
3291 <        KeyIterator(Traverser<K,V,Object> it) {
3292 <            super(it);
3288 >    /**
3289 >     * Encapsulates traversal for methods such as containsValue; also
3290 >     * serves as a base class for other iterators and spliterators.
3291 >     *
3292 >     * Method advance visits once each still-valid node that was
3293 >     * reachable upon iterator construction. It might miss some that
3294 >     * were added to a bin after the bin was visited, which is OK wrt
3295 >     * consistency guarantees. Maintaining this property in the face
3296 >     * of possible ongoing resizes requires a fair amount of
3297 >     * bookkeeping state that is difficult to optimize away amidst
3298 >     * volatile accesses.  Even so, traversal maintains reasonable
3299 >     * throughput.
3300 >     *
3301 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3302 >     * However, if the table has been resized, then all future steps
3303 >     * must traverse both the bin at the current index as well as at
3304 >     * (index + baseSize); and so on for further resizings. To
3305 >     * paranoically cope with potential sharing by users of iterators
3306 >     * across threads, iteration terminates if a bounds checks fails
3307 >     * for a table read.
3308 >     */
3309 >    static class Traverser<K,V> {
3310 >        Node<K,V>[] tab;        // current table; updated if resized
3311 >        Node<K,V> next;         // the next entry to use
3312 >        TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3313 >        int index;              // index of bin to use next
3314 >        int baseIndex;          // current index of initial table
3315 >        int baseLimit;          // index bound for initial table
3316 >        final int baseSize;     // initial table size
3317 >
3318 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3319 >            this.tab = tab;
3320 >            this.baseSize = size;
3321 >            this.baseIndex = this.index = index;
3322 >            this.baseLimit = limit;
3323 >            this.next = null;
3324          }
3325 <        public KeyIterator<K,V> split() {
3326 <            if (nextKey != null)
3325 >
3326 >        /**
3327 >         * Advances if possible, returning next valid node, or null if none.
3328 >         */
3329 >        final Node<K,V> advance() {
3330 >            Node<K,V> e;
3331 >            if ((e = next) != null)
3332 >                e = e.next;
3333 >            for (;;) {
3334 >                Node<K,V>[] t; int i, n;  // must use locals in checks
3335 >                if (e != null)
3336 >                    return next = e;
3337 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3338 >                    (n = t.length) <= (i = index) || i < 0)
3339 >                    return next = null;
3340 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
3341 >                    if (e instanceof ForwardingNode) {
3342 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3343 >                        e = null;
3344 >                        pushState(t, i, n);
3345 >                        continue;
3346 >                    }
3347 >                    else if (e instanceof TreeBin)
3348 >                        e = ((TreeBin<K,V>)e).first;
3349 >                    else
3350 >                        e = null;
3351 >                }
3352 >                if (stack != null)
3353 >                    recoverState(n);
3354 >                else if ((index = i + baseSize) >= n)
3355 >                    index = ++baseIndex; // visit upper slots if present
3356 >            }
3357 >        }
3358 >
3359 >        /**
3360 >         * Saves traversal state upon encountering a forwarding node.
3361 >         */
3362 >        private void pushState(Node<K,V>[] t, int i, int n) {
3363 >            TableStack<K,V> s = spare;  // reuse if possible
3364 >            if (s != null)
3365 >                spare = s.next;
3366 >            else
3367 >                s = new TableStack<K,V>();
3368 >            s.tab = t;
3369 >            s.length = n;
3370 >            s.index = i;
3371 >            s.next = stack;
3372 >            stack = s;
3373 >        }
3374 >
3375 >        /**
3376 >         * Possibly pops traversal state.
3377 >         *
3378 >         * @param n length of current table
3379 >         */
3380 >        private void recoverState(int n) {
3381 >            TableStack<K,V> s; int len;
3382 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
3383 >                n = len;
3384 >                index = s.index;
3385 >                tab = s.tab;
3386 >                s.tab = null;
3387 >                TableStack<K,V> next = s.next;
3388 >                s.next = spare; // save for reuse
3389 >                stack = next;
3390 >                spare = s;
3391 >            }
3392 >            if (s == null && (index += baseSize) >= n)
3393 >                index = ++baseIndex;
3394 >        }
3395 >    }
3396 >
3397 >    /**
3398 >     * Base of key, value, and entry Iterators. Adds fields to
3399 >     * Traverser to support iterator.remove.
3400 >     */
3401 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3402 >        final ConcurrentHashMap<K,V> map;
3403 >        Node<K,V> lastReturned;
3404 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3405 >                    ConcurrentHashMap<K,V> map) {
3406 >            super(tab, size, index, limit);
3407 >            this.map = map;
3408 >            advance();
3409 >        }
3410 >
3411 >        public final boolean hasNext() { return next != null; }
3412 >        public final boolean hasMoreElements() { return next != null; }
3413 >
3414 >        public final void remove() {
3415 >            Node<K,V> p;
3416 >            if ((p = lastReturned) == null)
3417                  throw new IllegalStateException();
3418 <            return new KeyIterator<K,V>(this);
3418 >            lastReturned = null;
3419 >            map.replaceNode(p.key, null, null);
3420          }
3421 <        @SuppressWarnings("unchecked") public final K next() {
3422 <            if (nextVal == null && advance() == null)
3421 >    }
3422 >
3423 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3424 >        implements Iterator<K>, Enumeration<K> {
3425 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3426 >                    ConcurrentHashMap<K,V> map) {
3427 >            super(tab, index, size, limit, map);
3428 >        }
3429 >
3430 >        public final K next() {
3431 >            Node<K,V> p;
3432 >            if ((p = next) == null)
3433                  throw new NoSuchElementException();
3434 <            Object k = nextKey;
3435 <            nextVal = null;
3436 <            return (K) k;
3434 >            K k = p.key;
3435 >            lastReturned = p;
3436 >            advance();
3437 >            return k;
3438          }
3439  
3440          public final K nextElement() { return next(); }
3441      }
3442  
3443 <    @SuppressWarnings("serial") static final class ValueIterator<K,V> extends Traverser<K,V,Object>
3444 <        implements Spliterator<V>, Enumeration<V> {
3445 <        ValueIterator(ConcurrentHashMap<K, V> map) { super(map); }
3446 <        ValueIterator(Traverser<K,V,Object> it) {
3447 <            super(it);
3280 <        }
3281 <        public ValueIterator<K,V> split() {
3282 <            if (nextKey != null)
3283 <                throw new IllegalStateException();
3284 <            return new ValueIterator<K,V>(this);
3443 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3444 >        implements Iterator<V>, Enumeration<V> {
3445 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3446 >                      ConcurrentHashMap<K,V> map) {
3447 >            super(tab, index, size, limit, map);
3448          }
3449  
3450 <        @SuppressWarnings("unchecked") public final V next() {
3451 <            Object v;
3452 <            if ((v = nextVal) == null && (v = advance()) == null)
3450 >        public final V next() {
3451 >            Node<K,V> p;
3452 >            if ((p = next) == null)
3453                  throw new NoSuchElementException();
3454 <            nextVal = null;
3455 <            return (V) v;
3454 >            V v = p.val;
3455 >            lastReturned = p;
3456 >            advance();
3457 >            return v;
3458          }
3459  
3460          public final V nextElement() { return next(); }
3461      }
3462  
3463 <    @SuppressWarnings("serial") static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3464 <        implements Spliterator<Map.Entry<K,V>> {
3465 <        EntryIterator(ConcurrentHashMap<K, V> map) { super(map); }
3466 <        EntryIterator(Traverser<K,V,Object> it) {
3467 <            super(it);
3303 <        }
3304 <        public EntryIterator<K,V> split() {
3305 <            if (nextKey != null)
3306 <                throw new IllegalStateException();
3307 <            return new EntryIterator<K,V>(this);
3463 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3464 >        implements Iterator<Map.Entry<K,V>> {
3465 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3466 >                      ConcurrentHashMap<K,V> map) {
3467 >            super(tab, index, size, limit, map);
3468          }
3469  
3470 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3471 <            Object v;
3472 <            if ((v = nextVal) == null && (v = advance()) == null)
3470 >        public final Map.Entry<K,V> next() {
3471 >            Node<K,V> p;
3472 >            if ((p = next) == null)
3473                  throw new NoSuchElementException();
3474 <            Object k = nextKey;
3475 <            nextVal = null;
3476 <            return new MapEntry<K,V>((K)k, (V)v, map);
3474 >            K k = p.key;
3475 >            V v = p.val;
3476 >            lastReturned = p;
3477 >            advance();
3478 >            return new MapEntry<K,V>(k, v, map);
3479          }
3480      }
3481  
3482      /**
3483 <     * Exported Entry for iterators
3483 >     * Exported Entry for EntryIterator
3484       */
3485 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3485 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3486          final K key; // non-null
3487          V val;       // non-null
3488 <        final ConcurrentHashMap<K, V> map;
3489 <        MapEntry(K key, V val, ConcurrentHashMap<K, V> map) {
3488 >        final ConcurrentHashMap<K,V> map;
3489 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3490              this.key = key;
3491              this.val = val;
3492              this.map = map;
3493          }
3494 <        public final K getKey()       { return key; }
3495 <        public final V getValue()     { return val; }
3496 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3497 <        public final String toString(){ return key + "=" + val; }
3494 >        public K getKey()        { return key; }
3495 >        public V getValue()      { return val; }
3496 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3497 >        public String toString() {
3498 >            return Helpers.mapEntryToString(key, val);
3499 >        }
3500  
3501 <        public final boolean equals(Object o) {
3501 >        public boolean equals(Object o) {
3502              Object k, v; Map.Entry<?,?> e;
3503              return ((o instanceof Map.Entry) &&
3504                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3348 | Line 3512 | public class ConcurrentHashMap<K, V>
3512           * value to return is somewhat arbitrary here. Since we do not
3513           * necessarily track asynchronous changes, the most recent
3514           * "previous" value could be different from what we return (or
3515 <         * could even have been removed in which case the put will
3515 >         * could even have been removed, in which case the put will
3516           * re-establish). We do not and cannot guarantee more.
3517           */
3518 <        public final V setValue(V value) {
3518 >        public V setValue(V value) {
3519              if (value == null) throw new NullPointerException();
3520              V v = val;
3521              val = value;
# Line 3360 | Line 3524 | public class ConcurrentHashMap<K, V>
3524          }
3525      }
3526  
3527 <    /* ----------------Views -------------- */
3527 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3528 >        implements Spliterator<K> {
3529 >        long est;               // size estimate
3530 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3531 >                       long est) {
3532 >            super(tab, size, index, limit);
3533 >            this.est = est;
3534 >        }
3535 >
3536 >        public Spliterator<K> trySplit() {
3537 >            int i, f, h;
3538 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3539 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3540 >                                        f, est >>>= 1);
3541 >        }
3542  
3543 <    /**
3544 <     * Base class for views.
3545 <     */
3546 <    static abstract class CHMView<K, V> {
3547 <        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(); }
3543 >        public void forEachRemaining(Consumer<? super K> action) {
3544 >            if (action == null) throw new NullPointerException();
3545 >            for (Node<K,V> p; (p = advance()) != null;)
3546 >                action.accept(p.key);
3547 >        }
3548  
3549 <        // implementations below rely on concrete classes supplying these
3550 <        abstract public Iterator<?> iterator();
3551 <        abstract public boolean contains(Object o);
3552 <        abstract public boolean remove(Object o);
3549 >        public boolean tryAdvance(Consumer<? super K> action) {
3550 >            if (action == null) throw new NullPointerException();
3551 >            Node<K,V> p;
3552 >            if ((p = advance()) == null)
3553 >                return false;
3554 >            action.accept(p.key);
3555 >            return true;
3556 >        }
3557  
3558 <        private static final String oomeMsg = "Required array size too large";
3558 >        public long estimateSize() { return est; }
3559  
3560 <        public final Object[] toArray() {
3561 <            long sz = map.mappingCount();
3562 <            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);
3560 >        public int characteristics() {
3561 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3562 >                Spliterator.NONNULL;
3563          }
3564 +    }
3565  
3566 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
3567 <            long sz = map.mappingCount();
3568 <            if (sz > (long)(MAX_ARRAY_SIZE))
3569 <                throw new OutOfMemoryError(oomeMsg);
3570 <            int m = (int)sz;
3571 <            T[] r = (a.length >= m) ? a :
3572 <                (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);
3566 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3567 >        implements Spliterator<V> {
3568 >        long est;               // size estimate
3569 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3570 >                         long est) {
3571 >            super(tab, size, index, limit);
3572 >            this.est = est;
3573          }
3574  
3575 <        public final int hashCode() {
3576 <            int h = 0;
3577 <            for (Iterator<?> it = iterator(); it.hasNext();)
3578 <                h += it.next().hashCode();
3579 <            return h;
3575 >        public Spliterator<V> trySplit() {
3576 >            int i, f, h;
3577 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3578 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3579 >                                          f, est >>>= 1);
3580          }
3581  
3582 <        public final String toString() {
3583 <            StringBuilder sb = new StringBuilder();
3584 <            sb.append('[');
3585 <            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();
3582 >        public void forEachRemaining(Consumer<? super V> action) {
3583 >            if (action == null) throw new NullPointerException();
3584 >            for (Node<K,V> p; (p = advance()) != null;)
3585 >                action.accept(p.val);
3586          }
3587  
3588 <        public final boolean containsAll(Collection<?> c) {
3589 <            if (c != this) {
3590 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
3591 <                    Object e = it.next();
3592 <                    if (e == null || !contains(e))
3593 <                        return false;
3464 <                }
3465 <            }
3588 >        public boolean tryAdvance(Consumer<? super V> action) {
3589 >            if (action == null) throw new NullPointerException();
3590 >            Node<K,V> p;
3591 >            if ((p = advance()) == null)
3592 >                return false;
3593 >            action.accept(p.val);
3594              return true;
3595          }
3596  
3597 <        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 <        }
3597 >        public long estimateSize() { return est; }
3598  
3599 <        public final boolean retainAll(Collection<?> c) {
3600 <            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;
3599 >        public int characteristics() {
3600 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3601          }
3490
3602      }
3603  
3604 <    static final class Values<K,V> extends CHMView<K,V>
3605 <        implements Collection<V> {
3606 <        Values(ConcurrentHashMap<K, V> map)   { super(map); }
3607 <        public final boolean contains(Object o) { return map.containsValue(o); }
3608 <        public final boolean remove(Object o) {
3609 <            if (o != null) {
3610 <                Iterator<V> it = new ValueIterator<K,V>(map);
3611 <                while (it.hasNext()) {
3612 <                    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();
3604 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3605 >        implements Spliterator<Map.Entry<K,V>> {
3606 >        final ConcurrentHashMap<K,V> map; // To export MapEntry
3607 >        long est;               // size estimate
3608 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3609 >                         long est, ConcurrentHashMap<K,V> map) {
3610 >            super(tab, size, index, limit);
3611 >            this.map = map;
3612 >            this.est = est;
3613          }
3614  
3615 <    }
3616 <
3617 <    static final class EntrySet<K,V> extends CHMView<K,V>
3618 <        implements Set<Map.Entry<K,V>> {
3619 <        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)));
3615 >        public Spliterator<Map.Entry<K,V>> trySplit() {
3616 >            int i, f, h;
3617 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3618 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3619 >                                          f, est >>>= 1, map);
3620          }
3621 <        public final boolean remove(Object o) {
3622 <            Object k, v; Map.Entry<?,?> e;
3623 <            return ((o instanceof Map.Entry) &&
3624 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3625 <                    (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();
3547 <        }
3548 <        public boolean equals(Object o) {
3549 <            Set<?> c;
3550 <            return ((o instanceof Set) &&
3551 <                    ((c = (Set<?>)o) == this ||
3552 <                     (containsAll(c) && c.containsAll(this))));
3621 >
3622 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3623 >            if (action == null) throw new NullPointerException();
3624 >            for (Node<K,V> p; (p = advance()) != null; )
3625 >                action.accept(new MapEntry<K,V>(p.key, p.val, map));
3626          }
3554    }
3627  
3628 <    /* ---------------- Serialization Support -------------- */
3628 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3629 >            if (action == null) throw new NullPointerException();
3630 >            Node<K,V> p;
3631 >            if ((p = advance()) == null)
3632 >                return false;
3633 >            action.accept(new MapEntry<K,V>(p.key, p.val, map));
3634 >            return true;
3635 >        }
3636  
3637 <    /**
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 <    }
3637 >        public long estimateSize() { return est; }
3638  
3639 <    /**
3640 <     * Saves the state of the {@code ConcurrentHashMap} instance to a
3641 <     * 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);
3639 >        public int characteristics() {
3640 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3641 >                Spliterator.NONNULL;
3642          }
3592        s.writeObject(null);
3593        s.writeObject(null);
3594        segments = null; // throw away
3643      }
3644  
3645 +    // Parallel bulk operations
3646 +
3647      /**
3648 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3649 <     * @param s the stream
3648 >     * Computes initial batch value for bulk tasks. The returned value
3649 >     * is approximately exp2 of the number of times (minus one) to
3650 >     * split task by two before executing leaf action. This value is
3651 >     * faster to compute and more convenient to use as a guide to
3652 >     * splitting than is the depth, since it is used while dividing by
3653 >     * two anyway.
3654       */
3655 <    @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
3656 <        throws java.io.IOException, ClassNotFoundException {
3657 <        s.defaultReadObject();
3658 <        this.segments = null; // unneeded
3659 <        // initialize transient final field
3660 <        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 <        }
3655 >    final int batchFor(long b) {
3656 >        long n;
3657 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3658 >            return 0;
3659 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3660 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3661      }
3662  
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
3663      /**
3664       * Performs the given action for each (key, value).
3665       *
3666 +     * @param parallelismThreshold the (estimated) number of elements
3667 +     * needed for this operation to be executed in parallel
3668       * @param action the action
3669 +     * @since 1.8
3670       */
3671 <    public void forEach(BiAction<K,V> action) {
3672 <        ForkJoinTasks.forEach
3673 <            (this, action).invoke();
3671 >    public void forEach(long parallelismThreshold,
3672 >                        BiConsumer<? super K,? super V> action) {
3673 >        if (action == null) throw new NullPointerException();
3674 >        new ForEachMappingTask<K,V>
3675 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3676 >             action).invoke();
3677      }
3678  
3679      /**
3680       * Performs the given action for each non-null transformation
3681       * of each (key, value).
3682       *
3683 +     * @param parallelismThreshold the (estimated) number of elements
3684 +     * needed for this operation to be executed in parallel
3685       * @param transformer a function returning the transformation
3686 <     * for an element, or null of there is no transformation (in
3687 <     * which case the action is not applied).
3686 >     * for an element, or null if there is no transformation (in
3687 >     * which case the action is not applied)
3688       * @param action the action
3689 +     * @param <U> the return type of the transformer
3690 +     * @since 1.8
3691       */
3692 <    public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3693 <                            Action<U> action) {
3694 <        ForkJoinTasks.forEach
3695 <            (this, transformer, action).invoke();
3692 >    public <U> void forEach(long parallelismThreshold,
3693 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3694 >                            Consumer<? super U> action) {
3695 >        if (transformer == null || action == null)
3696 >            throw new NullPointerException();
3697 >        new ForEachTransformedMappingTask<K,V,U>
3698 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3699 >             transformer, action).invoke();
3700      }
3701  
3702      /**
# Line 3750 | Line 3706 | public class ConcurrentHashMap<K, V>
3706       * results of any other parallel invocations of the search
3707       * function are ignored.
3708       *
3709 +     * @param parallelismThreshold the (estimated) number of elements
3710 +     * needed for this operation to be executed in parallel
3711       * @param searchFunction a function returning a non-null
3712       * result on success, else null
3713 +     * @param <U> the return type of the search function
3714       * @return a non-null result from applying the given search
3715       * function on each (key, value), or null if none
3716 +     * @since 1.8
3717       */
3718 <    public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3719 <        return ForkJoinTasks.search
3720 <            (this, searchFunction).invoke();
3718 >    public <U> U search(long parallelismThreshold,
3719 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3720 >        if (searchFunction == null) throw new NullPointerException();
3721 >        return new SearchMappingsTask<K,V,U>
3722 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3723 >             searchFunction, new AtomicReference<U>()).invoke();
3724      }
3725  
3726      /**
# Line 3765 | Line 3728 | public class ConcurrentHashMap<K, V>
3728       * of all (key, value) pairs using the given reducer to
3729       * combine values, or null if none.
3730       *
3731 +     * @param parallelismThreshold the (estimated) number of elements
3732 +     * needed for this operation to be executed in parallel
3733       * @param transformer a function returning the transformation
3734 <     * for an element, or null of there is no transformation (in
3735 <     * which case it is not combined).
3734 >     * for an element, or null if there is no transformation (in
3735 >     * which case it is not combined)
3736       * @param reducer a commutative associative combining function
3737 +     * @param <U> the return type of the transformer
3738       * @return the result of accumulating the given transformation
3739       * of all (key, value) pairs
3740 +     * @since 1.8
3741       */
3742 <    public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3743 <                        BiFun<? super U, ? super U, ? extends U> reducer) {
3744 <        return ForkJoinTasks.reduce
3745 <            (this, transformer, reducer).invoke();
3742 >    public <U> U reduce(long parallelismThreshold,
3743 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3744 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3745 >        if (transformer == null || reducer == null)
3746 >            throw new NullPointerException();
3747 >        return new MapReduceMappingsTask<K,V,U>
3748 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3749 >             null, transformer, reducer).invoke();
3750      }
3751  
3752      /**
# Line 3783 | Line 3754 | public class ConcurrentHashMap<K, V>
3754       * of all (key, value) pairs using the given reducer to
3755       * combine values, and the given basis as an identity value.
3756       *
3757 +     * @param parallelismThreshold the (estimated) number of elements
3758 +     * needed for this operation to be executed in parallel
3759       * @param transformer a function returning the transformation
3760       * for an element
3761       * @param basis the identity (initial default value) for the reduction
3762       * @param reducer a commutative associative combining function
3763       * @return the result of accumulating the given transformation
3764       * of all (key, value) pairs
3765 +     * @since 1.8
3766       */
3767 <    public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
3767 >    public double reduceToDouble(long parallelismThreshold,
3768 >                                 ToDoubleBiFunction<? super K, ? super V> transformer,
3769                                   double basis,
3770 <                                 DoubleByDoubleToDouble reducer) {
3771 <        return ForkJoinTasks.reduceToDouble
3772 <            (this, transformer, basis, reducer).invoke();
3770 >                                 DoubleBinaryOperator reducer) {
3771 >        if (transformer == null || reducer == null)
3772 >            throw new NullPointerException();
3773 >        return new MapReduceMappingsToDoubleTask<K,V>
3774 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3775 >             null, transformer, basis, reducer).invoke();
3776      }
3777  
3778      /**
# Line 3802 | Line 3780 | public class ConcurrentHashMap<K, V>
3780       * of all (key, value) pairs using the given reducer to
3781       * combine values, and the given basis as an identity value.
3782       *
3783 +     * @param parallelismThreshold the (estimated) number of elements
3784 +     * needed for this operation to be executed in parallel
3785       * @param transformer a function returning the transformation
3786       * for an element
3787       * @param basis the identity (initial default value) for the reduction
3788       * @param reducer a commutative associative combining function
3789       * @return the result of accumulating the given transformation
3790       * of all (key, value) pairs
3791 +     * @since 1.8
3792       */
3793 <    public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
3793 >    public long reduceToLong(long parallelismThreshold,
3794 >                             ToLongBiFunction<? super K, ? super V> transformer,
3795                               long basis,
3796 <                             LongByLongToLong reducer) {
3797 <        return ForkJoinTasks.reduceToLong
3798 <            (this, transformer, basis, reducer).invoke();
3796 >                             LongBinaryOperator reducer) {
3797 >        if (transformer == null || reducer == null)
3798 >            throw new NullPointerException();
3799 >        return new MapReduceMappingsToLongTask<K,V>
3800 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3801 >             null, transformer, basis, reducer).invoke();
3802      }
3803  
3804      /**
# Line 3821 | Line 3806 | public class ConcurrentHashMap<K, V>
3806       * of all (key, value) pairs using the given reducer to
3807       * combine values, and the given basis as an identity value.
3808       *
3809 +     * @param parallelismThreshold the (estimated) number of elements
3810 +     * needed for this operation to be executed in parallel
3811       * @param transformer a function returning the transformation
3812       * for an element
3813       * @param basis the identity (initial default value) for the reduction
3814       * @param reducer a commutative associative combining function
3815       * @return the result of accumulating the given transformation
3816       * of all (key, value) pairs
3817 +     * @since 1.8
3818       */
3819 <    public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
3819 >    public int reduceToInt(long parallelismThreshold,
3820 >                           ToIntBiFunction<? super K, ? super V> transformer,
3821                             int basis,
3822 <                           IntByIntToInt reducer) {
3823 <        return ForkJoinTasks.reduceToInt
3824 <            (this, transformer, basis, reducer).invoke();
3822 >                           IntBinaryOperator reducer) {
3823 >        if (transformer == null || reducer == null)
3824 >            throw new NullPointerException();
3825 >        return new MapReduceMappingsToIntTask<K,V>
3826 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3827 >             null, transformer, basis, reducer).invoke();
3828      }
3829  
3830      /**
3831       * Performs the given action for each key.
3832       *
3833 +     * @param parallelismThreshold the (estimated) number of elements
3834 +     * needed for this operation to be executed in parallel
3835       * @param action the action
3836 +     * @since 1.8
3837       */
3838 <    public void forEachKey(Action<K> action) {
3839 <        ForkJoinTasks.forEachKey
3840 <            (this, action).invoke();
3838 >    public void forEachKey(long parallelismThreshold,
3839 >                           Consumer<? super K> action) {
3840 >        if (action == null) throw new NullPointerException();
3841 >        new ForEachKeyTask<K,V>
3842 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3843 >             action).invoke();
3844      }
3845  
3846      /**
3847       * Performs the given action for each non-null transformation
3848       * of each key.
3849       *
3850 +     * @param parallelismThreshold the (estimated) number of elements
3851 +     * needed for this operation to be executed in parallel
3852       * @param transformer a function returning the transformation
3853 <     * for an element, or null of there is no transformation (in
3854 <     * which case the action is not applied).
3853 >     * for an element, or null if there is no transformation (in
3854 >     * which case the action is not applied)
3855       * @param action the action
3856 +     * @param <U> the return type of the transformer
3857 +     * @since 1.8
3858       */
3859 <    public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
3860 <                               Action<U> action) {
3861 <        ForkJoinTasks.forEachKey
3862 <            (this, transformer, action).invoke();
3859 >    public <U> void forEachKey(long parallelismThreshold,
3860 >                               Function<? super K, ? extends U> transformer,
3861 >                               Consumer<? super U> action) {
3862 >        if (transformer == null || action == null)
3863 >            throw new NullPointerException();
3864 >        new ForEachTransformedKeyTask<K,V,U>
3865 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3866 >             transformer, action).invoke();
3867      }
3868  
3869      /**
# Line 3867 | Line 3873 | public class ConcurrentHashMap<K, V>
3873       * any other parallel invocations of the search function are
3874       * ignored.
3875       *
3876 +     * @param parallelismThreshold the (estimated) number of elements
3877 +     * needed for this operation to be executed in parallel
3878       * @param searchFunction a function returning a non-null
3879       * result on success, else null
3880 +     * @param <U> the return type of the search function
3881       * @return a non-null result from applying the given search
3882       * function on each key, or null if none
3883 +     * @since 1.8
3884       */
3885 <    public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
3886 <        return ForkJoinTasks.searchKeys
3887 <            (this, searchFunction).invoke();
3885 >    public <U> U searchKeys(long parallelismThreshold,
3886 >                            Function<? super K, ? extends U> searchFunction) {
3887 >        if (searchFunction == null) throw new NullPointerException();
3888 >        return new SearchKeysTask<K,V,U>
3889 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3890 >             searchFunction, new AtomicReference<U>()).invoke();
3891      }
3892  
3893      /**
3894       * Returns the result of accumulating all keys using the given
3895       * reducer to combine values, or null if none.
3896       *
3897 +     * @param parallelismThreshold the (estimated) number of elements
3898 +     * needed for this operation to be executed in parallel
3899       * @param reducer a commutative associative combining function
3900       * @return the result of accumulating all keys using the given
3901       * reducer to combine values, or null if none
3902 +     * @since 1.8
3903       */
3904 <    public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
3905 <        return ForkJoinTasks.reduceKeys
3906 <            (this, reducer).invoke();
3904 >    public K reduceKeys(long parallelismThreshold,
3905 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3906 >        if (reducer == null) throw new NullPointerException();
3907 >        return new ReduceKeysTask<K,V>
3908 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3909 >             null, reducer).invoke();
3910      }
3911  
3912      /**
# Line 3895 | Line 3914 | public class ConcurrentHashMap<K, V>
3914       * of all keys using the given reducer to combine values, or
3915       * null if none.
3916       *
3917 +     * @param parallelismThreshold the (estimated) number of elements
3918 +     * needed for this operation to be executed in parallel
3919       * @param transformer a function returning the transformation
3920 <     * for an element, or null of there is no transformation (in
3921 <     * which case it is not combined).
3920 >     * for an element, or null if there is no transformation (in
3921 >     * which case it is not combined)
3922       * @param reducer a commutative associative combining function
3923 +     * @param <U> the return type of the transformer
3924       * @return the result of accumulating the given transformation
3925       * of all keys
3926 +     * @since 1.8
3927       */
3928 <    public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
3929 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
3930 <        return ForkJoinTasks.reduceKeys
3931 <            (this, transformer, reducer).invoke();
3928 >    public <U> U reduceKeys(long parallelismThreshold,
3929 >                            Function<? super K, ? extends U> transformer,
3930 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3931 >        if (transformer == null || reducer == null)
3932 >            throw new NullPointerException();
3933 >        return new MapReduceKeysTask<K,V,U>
3934 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3935 >             null, transformer, reducer).invoke();
3936      }
3937  
3938      /**
# Line 3913 | Line 3940 | public class ConcurrentHashMap<K, V>
3940       * of all keys using the given reducer to combine values, and
3941       * the given basis as an identity value.
3942       *
3943 +     * @param parallelismThreshold the (estimated) number of elements
3944 +     * needed for this operation to be executed in parallel
3945       * @param transformer a function returning the transformation
3946       * for an element
3947       * @param basis the identity (initial default value) for the reduction
3948       * @param reducer a commutative associative combining function
3949 <     * @return  the result of accumulating the given transformation
3949 >     * @return the result of accumulating the given transformation
3950       * of all keys
3951 +     * @since 1.8
3952       */
3953 <    public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
3953 >    public double reduceKeysToDouble(long parallelismThreshold,
3954 >                                     ToDoubleFunction<? super K> transformer,
3955                                       double basis,
3956 <                                     DoubleByDoubleToDouble reducer) {
3957 <        return ForkJoinTasks.reduceKeysToDouble
3958 <            (this, transformer, basis, reducer).invoke();
3956 >                                     DoubleBinaryOperator reducer) {
3957 >        if (transformer == null || reducer == null)
3958 >            throw new NullPointerException();
3959 >        return new MapReduceKeysToDoubleTask<K,V>
3960 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3961 >             null, transformer, basis, reducer).invoke();
3962      }
3963  
3964      /**
# Line 3932 | Line 3966 | public class ConcurrentHashMap<K, V>
3966       * of all keys using the given reducer to combine values, and
3967       * the given basis as an identity value.
3968       *
3969 +     * @param parallelismThreshold the (estimated) number of elements
3970 +     * needed for this operation to be executed in parallel
3971       * @param transformer a function returning the transformation
3972       * for an element
3973       * @param basis the identity (initial default value) for the reduction
3974       * @param reducer a commutative associative combining function
3975       * @return the result of accumulating the given transformation
3976       * of all keys
3977 +     * @since 1.8
3978       */
3979 <    public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3979 >    public long reduceKeysToLong(long parallelismThreshold,
3980 >                                 ToLongFunction<? super K> transformer,
3981                                   long basis,
3982 <                                 LongByLongToLong reducer) {
3983 <        return ForkJoinTasks.reduceKeysToLong
3984 <            (this, transformer, basis, reducer).invoke();
3982 >                                 LongBinaryOperator reducer) {
3983 >        if (transformer == null || reducer == null)
3984 >            throw new NullPointerException();
3985 >        return new MapReduceKeysToLongTask<K,V>
3986 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3987 >             null, transformer, basis, reducer).invoke();
3988      }
3989  
3990      /**
# Line 3951 | Line 3992 | public class ConcurrentHashMap<K, V>
3992       * of all keys using the given reducer to combine values, and
3993       * the given basis as an identity value.
3994       *
3995 +     * @param parallelismThreshold the (estimated) number of elements
3996 +     * needed for this operation to be executed in parallel
3997       * @param transformer a function returning the transformation
3998       * for an element
3999       * @param basis the identity (initial default value) for the reduction
4000       * @param reducer a commutative associative combining function
4001       * @return the result of accumulating the given transformation
4002       * of all keys
4003 +     * @since 1.8
4004       */
4005 <    public int reduceKeysToInt(ObjectToInt<? super K> transformer,
4005 >    public int reduceKeysToInt(long parallelismThreshold,
4006 >                               ToIntFunction<? super K> transformer,
4007                                 int basis,
4008 <                               IntByIntToInt reducer) {
4009 <        return ForkJoinTasks.reduceKeysToInt
4010 <            (this, transformer, basis, reducer).invoke();
4008 >                               IntBinaryOperator reducer) {
4009 >        if (transformer == null || reducer == null)
4010 >            throw new NullPointerException();
4011 >        return new MapReduceKeysToIntTask<K,V>
4012 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4013 >             null, transformer, basis, reducer).invoke();
4014      }
4015  
4016      /**
4017       * Performs the given action for each value.
4018       *
4019 +     * @param parallelismThreshold the (estimated) number of elements
4020 +     * needed for this operation to be executed in parallel
4021       * @param action the action
4022 +     * @since 1.8
4023       */
4024 <    public void forEachValue(Action<V> action) {
4025 <        ForkJoinTasks.forEachValue
4026 <            (this, action).invoke();
4024 >    public void forEachValue(long parallelismThreshold,
4025 >                             Consumer<? super V> action) {
4026 >        if (action == null)
4027 >            throw new NullPointerException();
4028 >        new ForEachValueTask<K,V>
4029 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4030 >             action).invoke();
4031      }
4032  
4033      /**
4034       * Performs the given action for each non-null transformation
4035       * of each value.
4036       *
4037 +     * @param parallelismThreshold the (estimated) number of elements
4038 +     * needed for this operation to be executed in parallel
4039       * @param transformer a function returning the transformation
4040 <     * for an element, or null of there is no transformation (in
4041 <     * which case the action is not applied).
4040 >     * for an element, or null if there is no transformation (in
4041 >     * which case the action is not applied)
4042 >     * @param action the action
4043 >     * @param <U> the return type of the transformer
4044 >     * @since 1.8
4045       */
4046 <    public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
4047 <                                 Action<U> action) {
4048 <        ForkJoinTasks.forEachValue
4049 <            (this, transformer, action).invoke();
4046 >    public <U> void forEachValue(long parallelismThreshold,
4047 >                                 Function<? super V, ? extends U> transformer,
4048 >                                 Consumer<? super U> action) {
4049 >        if (transformer == null || action == null)
4050 >            throw new NullPointerException();
4051 >        new ForEachTransformedValueTask<K,V,U>
4052 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4053 >             transformer, action).invoke();
4054      }
4055  
4056      /**
# Line 3996 | Line 4060 | public class ConcurrentHashMap<K, V>
4060       * any other parallel invocations of the search function are
4061       * ignored.
4062       *
4063 +     * @param parallelismThreshold the (estimated) number of elements
4064 +     * needed for this operation to be executed in parallel
4065       * @param searchFunction a function returning a non-null
4066       * result on success, else null
4067 +     * @param <U> the return type of the search function
4068       * @return a non-null result from applying the given search
4069       * function on each value, or null if none
4070 <     *
4070 >     * @since 1.8
4071       */
4072 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
4073 <        return ForkJoinTasks.searchValues
4074 <            (this, searchFunction).invoke();
4072 >    public <U> U searchValues(long parallelismThreshold,
4073 >                              Function<? super V, ? extends U> searchFunction) {
4074 >        if (searchFunction == null) throw new NullPointerException();
4075 >        return new SearchValuesTask<K,V,U>
4076 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4077 >             searchFunction, new AtomicReference<U>()).invoke();
4078      }
4079  
4080      /**
4081       * Returns the result of accumulating all values using the
4082       * given reducer to combine values, or null if none.
4083       *
4084 +     * @param parallelismThreshold the (estimated) number of elements
4085 +     * needed for this operation to be executed in parallel
4086       * @param reducer a commutative associative combining function
4087 <     * @return  the result of accumulating all values
4087 >     * @return the result of accumulating all values
4088 >     * @since 1.8
4089       */
4090 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
4091 <        return ForkJoinTasks.reduceValues
4092 <            (this, reducer).invoke();
4090 >    public V reduceValues(long parallelismThreshold,
4091 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
4092 >        if (reducer == null) throw new NullPointerException();
4093 >        return new ReduceValuesTask<K,V>
4094 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4095 >             null, reducer).invoke();
4096      }
4097  
4098      /**
# Line 4024 | Line 4100 | public class ConcurrentHashMap<K, V>
4100       * of all values using the given reducer to combine values, or
4101       * null if none.
4102       *
4103 +     * @param parallelismThreshold the (estimated) number of elements
4104 +     * needed for this operation to be executed in parallel
4105       * @param transformer a function returning the transformation
4106 <     * for an element, or null of there is no transformation (in
4107 <     * which case it is not combined).
4106 >     * for an element, or null if there is no transformation (in
4107 >     * which case it is not combined)
4108       * @param reducer a commutative associative combining function
4109 +     * @param <U> the return type of the transformer
4110       * @return the result of accumulating the given transformation
4111       * of all values
4112 +     * @since 1.8
4113       */
4114 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
4115 <                              BiFun<? super U, ? super U, ? extends U> reducer) {
4116 <        return ForkJoinTasks.reduceValues
4117 <            (this, transformer, reducer).invoke();
4114 >    public <U> U reduceValues(long parallelismThreshold,
4115 >                              Function<? super V, ? extends U> transformer,
4116 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
4117 >        if (transformer == null || reducer == null)
4118 >            throw new NullPointerException();
4119 >        return new MapReduceValuesTask<K,V,U>
4120 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4121 >             null, transformer, reducer).invoke();
4122      }
4123  
4124      /**
# Line 4042 | Line 4126 | public class ConcurrentHashMap<K, V>
4126       * of all values using the given reducer to combine values,
4127       * and the given basis as an identity value.
4128       *
4129 +     * @param parallelismThreshold the (estimated) number of elements
4130 +     * needed for this operation to be executed in parallel
4131       * @param transformer a function returning the transformation
4132       * for an element
4133       * @param basis the identity (initial default value) for the reduction
4134       * @param reducer a commutative associative combining function
4135       * @return the result of accumulating the given transformation
4136       * of all values
4137 +     * @since 1.8
4138       */
4139 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
4139 >    public double reduceValuesToDouble(long parallelismThreshold,
4140 >                                       ToDoubleFunction<? super V> transformer,
4141                                         double basis,
4142 <                                       DoubleByDoubleToDouble reducer) {
4143 <        return ForkJoinTasks.reduceValuesToDouble
4144 <            (this, transformer, basis, reducer).invoke();
4142 >                                       DoubleBinaryOperator reducer) {
4143 >        if (transformer == null || reducer == null)
4144 >            throw new NullPointerException();
4145 >        return new MapReduceValuesToDoubleTask<K,V>
4146 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4147 >             null, transformer, basis, reducer).invoke();
4148      }
4149  
4150      /**
# Line 4061 | Line 4152 | public class ConcurrentHashMap<K, V>
4152       * of all values using the given reducer to combine values,
4153       * and the given basis as an identity value.
4154       *
4155 +     * @param parallelismThreshold the (estimated) number of elements
4156 +     * needed for this operation to be executed in parallel
4157       * @param transformer a function returning the transformation
4158       * for an element
4159       * @param basis the identity (initial default value) for the reduction
4160       * @param reducer a commutative associative combining function
4161       * @return the result of accumulating the given transformation
4162       * of all values
4163 +     * @since 1.8
4164       */
4165 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
4165 >    public long reduceValuesToLong(long parallelismThreshold,
4166 >                                   ToLongFunction<? super V> transformer,
4167                                     long basis,
4168 <                                   LongByLongToLong reducer) {
4169 <        return ForkJoinTasks.reduceValuesToLong
4170 <            (this, transformer, basis, reducer).invoke();
4168 >                                   LongBinaryOperator reducer) {
4169 >        if (transformer == null || reducer == null)
4170 >            throw new NullPointerException();
4171 >        return new MapReduceValuesToLongTask<K,V>
4172 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4173 >             null, transformer, basis, reducer).invoke();
4174      }
4175  
4176      /**
# Line 4080 | Line 4178 | public class ConcurrentHashMap<K, V>
4178       * of all values using the given reducer to combine values,
4179       * and the given basis as an identity value.
4180       *
4181 +     * @param parallelismThreshold the (estimated) number of elements
4182 +     * needed for this operation to be executed in parallel
4183       * @param transformer a function returning the transformation
4184       * for an element
4185       * @param basis the identity (initial default value) for the reduction
4186       * @param reducer a commutative associative combining function
4187       * @return the result of accumulating the given transformation
4188       * of all values
4189 +     * @since 1.8
4190       */
4191 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4191 >    public int reduceValuesToInt(long parallelismThreshold,
4192 >                                 ToIntFunction<? super V> transformer,
4193                                   int basis,
4194 <                                 IntByIntToInt reducer) {
4195 <        return ForkJoinTasks.reduceValuesToInt
4196 <            (this, transformer, basis, reducer).invoke();
4194 >                                 IntBinaryOperator reducer) {
4195 >        if (transformer == null || reducer == null)
4196 >            throw new NullPointerException();
4197 >        return new MapReduceValuesToIntTask<K,V>
4198 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4199 >             null, transformer, basis, reducer).invoke();
4200      }
4201  
4202      /**
4203       * Performs the given action for each entry.
4204       *
4205 +     * @param parallelismThreshold the (estimated) number of elements
4206 +     * needed for this operation to be executed in parallel
4207       * @param action the action
4208 +     * @since 1.8
4209       */
4210 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
4211 <        ForkJoinTasks.forEachEntry
4212 <            (this, action).invoke();
4210 >    public void forEachEntry(long parallelismThreshold,
4211 >                             Consumer<? super Map.Entry<K,V>> action) {
4212 >        if (action == null) throw new NullPointerException();
4213 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4214 >                                  action).invoke();
4215      }
4216  
4217      /**
4218       * Performs the given action for each non-null transformation
4219       * of each entry.
4220       *
4221 +     * @param parallelismThreshold the (estimated) number of elements
4222 +     * needed for this operation to be executed in parallel
4223       * @param transformer a function returning the transformation
4224 <     * for an element, or null of there is no transformation (in
4225 <     * which case the action is not applied).
4224 >     * for an element, or null if there is no transformation (in
4225 >     * which case the action is not applied)
4226       * @param action the action
4227 +     * @param <U> the return type of the transformer
4228 +     * @since 1.8
4229       */
4230 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4231 <                                 Action<U> action) {
4232 <        ForkJoinTasks.forEachEntry
4233 <            (this, transformer, action).invoke();
4230 >    public <U> void forEachEntry(long parallelismThreshold,
4231 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
4232 >                                 Consumer<? super U> action) {
4233 >        if (transformer == null || action == null)
4234 >            throw new NullPointerException();
4235 >        new ForEachTransformedEntryTask<K,V,U>
4236 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4237 >             transformer, action).invoke();
4238      }
4239  
4240      /**
# Line 4126 | Line 4244 | public class ConcurrentHashMap<K, V>
4244       * any other parallel invocations of the search function are
4245       * ignored.
4246       *
4247 +     * @param parallelismThreshold the (estimated) number of elements
4248 +     * needed for this operation to be executed in parallel
4249       * @param searchFunction a function returning a non-null
4250       * result on success, else null
4251 +     * @param <U> the return type of the search function
4252       * @return a non-null result from applying the given search
4253       * function on each entry, or null if none
4254 +     * @since 1.8
4255       */
4256 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4257 <        return ForkJoinTasks.searchEntries
4258 <            (this, searchFunction).invoke();
4256 >    public <U> U searchEntries(long parallelismThreshold,
4257 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4258 >        if (searchFunction == null) throw new NullPointerException();
4259 >        return new SearchEntriesTask<K,V,U>
4260 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4261 >             searchFunction, new AtomicReference<U>()).invoke();
4262      }
4263  
4264      /**
4265       * Returns the result of accumulating all entries using the
4266       * given reducer to combine values, or null if none.
4267       *
4268 +     * @param parallelismThreshold the (estimated) number of elements
4269 +     * needed for this operation to be executed in parallel
4270       * @param reducer a commutative associative combining function
4271       * @return the result of accumulating all entries
4272 +     * @since 1.8
4273       */
4274 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4275 <        return ForkJoinTasks.reduceEntries
4276 <            (this, reducer).invoke();
4274 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4275 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4276 >        if (reducer == null) throw new NullPointerException();
4277 >        return new ReduceEntriesTask<K,V>
4278 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4279 >             null, reducer).invoke();
4280      }
4281  
4282      /**
# Line 4153 | Line 4284 | public class ConcurrentHashMap<K, V>
4284       * of all entries using the given reducer to combine values,
4285       * or null if none.
4286       *
4287 +     * @param parallelismThreshold the (estimated) number of elements
4288 +     * needed for this operation to be executed in parallel
4289       * @param transformer a function returning the transformation
4290 <     * for an element, or null of there is no transformation (in
4291 <     * which case it is not combined).
4290 >     * for an element, or null if there is no transformation (in
4291 >     * which case it is not combined)
4292       * @param reducer a commutative associative combining function
4293 +     * @param <U> the return type of the transformer
4294       * @return the result of accumulating the given transformation
4295       * of all entries
4296 +     * @since 1.8
4297       */
4298 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4299 <                               BiFun<? super U, ? super U, ? extends U> reducer) {
4300 <        return ForkJoinTasks.reduceEntries
4301 <            (this, transformer, reducer).invoke();
4298 >    public <U> U reduceEntries(long parallelismThreshold,
4299 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
4300 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
4301 >        if (transformer == null || reducer == null)
4302 >            throw new NullPointerException();
4303 >        return new MapReduceEntriesTask<K,V,U>
4304 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4305 >             null, transformer, reducer).invoke();
4306      }
4307  
4308      /**
# Line 4171 | Line 4310 | public class ConcurrentHashMap<K, V>
4310       * of all entries using the given reducer to combine values,
4311       * and the given basis as an identity value.
4312       *
4313 +     * @param parallelismThreshold the (estimated) number of elements
4314 +     * needed for this operation to be executed in parallel
4315       * @param transformer a function returning the transformation
4316       * for an element
4317       * @param basis the identity (initial default value) for the reduction
4318       * @param reducer a commutative associative combining function
4319       * @return the result of accumulating the given transformation
4320       * of all entries
4321 +     * @since 1.8
4322       */
4323 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4323 >    public double reduceEntriesToDouble(long parallelismThreshold,
4324 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
4325                                          double basis,
4326 <                                        DoubleByDoubleToDouble reducer) {
4327 <        return ForkJoinTasks.reduceEntriesToDouble
4328 <            (this, transformer, basis, reducer).invoke();
4326 >                                        DoubleBinaryOperator reducer) {
4327 >        if (transformer == null || reducer == null)
4328 >            throw new NullPointerException();
4329 >        return new MapReduceEntriesToDoubleTask<K,V>
4330 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4331 >             null, transformer, basis, reducer).invoke();
4332      }
4333  
4334      /**
# Line 4190 | Line 4336 | public class ConcurrentHashMap<K, V>
4336       * of all entries using the given reducer to combine values,
4337       * and the given basis as an identity value.
4338       *
4339 +     * @param parallelismThreshold the (estimated) number of elements
4340 +     * needed for this operation to be executed in parallel
4341       * @param transformer a function returning the transformation
4342       * for an element
4343       * @param basis the identity (initial default value) for the reduction
4344       * @param reducer a commutative associative combining function
4345 <     * @return  the result of accumulating the given transformation
4345 >     * @return the result of accumulating the given transformation
4346       * of all entries
4347 +     * @since 1.8
4348       */
4349 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4349 >    public long reduceEntriesToLong(long parallelismThreshold,
4350 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
4351                                      long basis,
4352 <                                    LongByLongToLong reducer) {
4353 <        return ForkJoinTasks.reduceEntriesToLong
4354 <            (this, transformer, basis, reducer).invoke();
4352 >                                    LongBinaryOperator reducer) {
4353 >        if (transformer == null || reducer == null)
4354 >            throw new NullPointerException();
4355 >        return new MapReduceEntriesToLongTask<K,V>
4356 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4357 >             null, transformer, basis, reducer).invoke();
4358      }
4359  
4360      /**
# Line 4209 | Line 4362 | public class ConcurrentHashMap<K, V>
4362       * of all entries using the given reducer to combine values,
4363       * and the given basis as an identity value.
4364       *
4365 +     * @param parallelismThreshold the (estimated) number of elements
4366 +     * needed for this operation to be executed in parallel
4367       * @param transformer a function returning the transformation
4368       * for an element
4369       * @param basis the identity (initial default value) for the reduction
4370       * @param reducer a commutative associative combining function
4371       * @return the result of accumulating the given transformation
4372       * of all entries
4373 +     * @since 1.8
4374       */
4375 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4375 >    public int reduceEntriesToInt(long parallelismThreshold,
4376 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
4377                                    int basis,
4378 <                                  IntByIntToInt reducer) {
4379 <        return ForkJoinTasks.reduceEntriesToInt
4380 <            (this, transformer, basis, reducer).invoke();
4378 >                                  IntBinaryOperator reducer) {
4379 >        if (transformer == null || reducer == null)
4380 >            throw new NullPointerException();
4381 >        return new MapReduceEntriesToIntTask<K,V>
4382 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4383 >             null, transformer, basis, reducer).invoke();
4384      }
4385  
4386 <    // ---------------------------------------------------------------------
4386 >
4387 >    /* ----------------Views -------------- */
4388  
4389      /**
4390 <     * 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.
4390 >     * Base class for views.
4391       */
4392 <    public static class ForkJoinTasks {
4393 <        private ForkJoinTasks() {}
4394 <
4395 <        /**
4396 <         * 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 <        }
4392 >    abstract static class CollectionView<K,V,E>
4393 >        implements Collection<E>, java.io.Serializable {
4394 >        private static final long serialVersionUID = 7249069246763182397L;
4395 >        final ConcurrentHashMap<K,V> map;
4396 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4397  
4398          /**
4399 <         * Returns a task that when invoked, performs the given
4257 <         * action for each non-null transformation of each (key, value)
4399 >         * Returns the map backing this view.
4400           *
4401 <         * @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
4401 >         * @return the map backing this view
4402           */
4403 <        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 <        }
4403 >        public ConcurrentHashMap<K,V> getMap() { return map; }
4404  
4405          /**
4406 <         * Returns a task that when invoked, returns a non-null result
4407 <         * 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
4406 >         * Removes all of the elements from this view, by removing all
4407 >         * the mappings from the map backing this view.
4408           */
4409 <        public static <K,V,U> ForkJoinTask<U> search
4410 <            (ConcurrentHashMap<K,V> map,
4411 <             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 <        }
4409 >        public final void clear()      { map.clear(); }
4410 >        public final int size()        { return map.size(); }
4411 >        public final boolean isEmpty() { return map.isEmpty(); }
4412  
4413 +        // implementations below rely on concrete classes supplying these
4414 +        // abstract methods
4415          /**
4416 <         * 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.
4416 >         * Returns an iterator over the elements in this collection.
4417           *
4418 <         * @param map the map
4419 <         * @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.
4418 >         * <p>The returned iterator is
4419 >         * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
4420           *
4421 <         * @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
4421 >         * @return an iterator over the elements in this collection
4422           */
4423 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4424 <            (ConcurrentHashMap<K,V> map,
4425 <             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 <        }
4423 >        public abstract Iterator<E> iterator();
4424 >        public abstract boolean contains(Object o);
4425 >        public abstract boolean remove(Object o);
4426  
4427 <        /**
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 <        }
4427 >        private static final String oomeMsg = "Required array size too large";
4428  
4429 <        /**
4430 <         * Returns a task that when invoked, returns the result of
4431 <         * accumulating the given transformation of all (key, value) pairs
4432 <         * using the given reducer to combine values, and the given
4433 <         * basis as an identity value.
4434 <         *
4435 <         * @param transformer a function returning the transformation
4436 <         * for an element
4437 <         * @param basis the identity (initial default value) for the reduction
4438 <         * @param reducer a commutative associative combining function
4439 <         * @return the task
4440 <         */
4441 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
4442 <            (ConcurrentHashMap<K,V> map,
4443 <             ObjectByObjectToInt<? super K, ? super V> transformer,
4444 <             int basis,
4445 <             IntByIntToInt reducer) {
4446 <            if (transformer == null || reducer == null)
4447 <                throw new NullPointerException();
4448 <            return new MapReduceMappingsToIntTask<K,V>
4387 <                (map, null, -1, null, transformer, basis, reducer);
4429 >        public final Object[] toArray() {
4430 >            long sz = map.mappingCount();
4431 >            if (sz > MAX_ARRAY_SIZE)
4432 >                throw new OutOfMemoryError(oomeMsg);
4433 >            int n = (int)sz;
4434 >            Object[] r = new Object[n];
4435 >            int i = 0;
4436 >            for (E e : this) {
4437 >                if (i == n) {
4438 >                    if (n >= MAX_ARRAY_SIZE)
4439 >                        throw new OutOfMemoryError(oomeMsg);
4440 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4441 >                        n = MAX_ARRAY_SIZE;
4442 >                    else
4443 >                        n += (n >>> 1) + 1;
4444 >                    r = Arrays.copyOf(r, n);
4445 >                }
4446 >                r[i++] = e;
4447 >            }
4448 >            return (i == n) ? r : Arrays.copyOf(r, i);
4449          }
4450  
4451 <        /**
4452 <         * Returns a task that when invoked, performs the given action
4453 <         * for each key.
4454 <         *
4455 <         * @param map the map
4456 <         * @param action the action
4457 <         * @return the task
4458 <         */
4459 <        public static <K,V> ForkJoinTask<Void> forEachKey
4460 <            (ConcurrentHashMap<K,V> map,
4461 <             Action<K> action) {
4462 <            if (action == null) throw new NullPointerException();
4463 <            return new ForEachKeyTask<K,V>(map, null, -1, null, action);
4451 >        @SuppressWarnings("unchecked")
4452 >        public final <T> T[] toArray(T[] a) {
4453 >            long sz = map.mappingCount();
4454 >            if (sz > MAX_ARRAY_SIZE)
4455 >                throw new OutOfMemoryError(oomeMsg);
4456 >            int m = (int)sz;
4457 >            T[] r = (a.length >= m) ? a :
4458 >                (T[])java.lang.reflect.Array
4459 >                .newInstance(a.getClass().getComponentType(), m);
4460 >            int n = r.length;
4461 >            int i = 0;
4462 >            for (E e : this) {
4463 >                if (i == n) {
4464 >                    if (n >= MAX_ARRAY_SIZE)
4465 >                        throw new OutOfMemoryError(oomeMsg);
4466 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4467 >                        n = MAX_ARRAY_SIZE;
4468 >                    else
4469 >                        n += (n >>> 1) + 1;
4470 >                    r = Arrays.copyOf(r, n);
4471 >                }
4472 >                r[i++] = (T)e;
4473 >            }
4474 >            if (a == r && i < n) {
4475 >                r[i] = null; // null-terminate
4476 >                return r;
4477 >            }
4478 >            return (i == n) ? r : Arrays.copyOf(r, i);
4479          }
4480  
4481          /**
4482 <         * Returns a task that when invoked, performs the given action
4483 <         * for each non-null transformation of each key.
4482 >         * Returns a string representation of this collection.
4483 >         * The string representation consists of the string representations
4484 >         * of the collection's elements in the order they are returned by
4485 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4486 >         * Adjacent elements are separated by the characters {@code ", "}
4487 >         * (comma and space).  Elements are converted to strings as by
4488 >         * {@link String#valueOf(Object)}.
4489           *
4490 <         * @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
4490 >         * @return a string representation of this collection
4491           */
4492 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
4493 <            (ConcurrentHashMap<K,V> map,
4494 <             Fun<? super K, ? extends U> transformer,
4495 <             Action<U> action) {
4496 <            if (transformer == null || action == null)
4497 <                throw new NullPointerException();
4498 <            return new ForEachTransformedKeyTask<K,V,U>
4499 <                (map, null, -1, null, transformer, action);
4492 >        public final String toString() {
4493 >            StringBuilder sb = new StringBuilder();
4494 >            sb.append('[');
4495 >            Iterator<E> it = iterator();
4496 >            if (it.hasNext()) {
4497 >                for (;;) {
4498 >                    Object e = it.next();
4499 >                    sb.append(e == this ? "(this Collection)" : e);
4500 >                    if (!it.hasNext())
4501 >                        break;
4502 >                    sb.append(',').append(' ');
4503 >                }
4504 >            }
4505 >            return sb.append(']').toString();
4506          }
4507  
4508 <        /**
4509 <         * Returns a task that when invoked, returns a non-null result
4510 <         * from applying the given search function on each key, or
4511 <         * null if none.  Upon success, further element processing is
4512 <         * suppressed and the results of any other parallel
4513 <         * invocations of the search function are ignored.
4514 <         *
4515 <         * @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>());
4508 >        public final boolean containsAll(Collection<?> c) {
4509 >            if (c != this) {
4510 >                for (Object e : c) {
4511 >                    if (e == null || !contains(e))
4512 >                        return false;
4513 >                }
4514 >            }
4515 >            return true;
4516          }
4517  
4518 <        /**
4519 <         * Returns a task that when invoked, returns the result of
4520 <         * accumulating all keys using the given reducer to combine
4521 <         * values, or null if none.
4522 <         *
4523 <         * @param map the map
4524 <         * @param reducer a commutative associative combining function
4525 <         * @return the task
4526 <         */
4527 <        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);
4518 >        public final boolean removeAll(Collection<?> c) {
4519 >            if (c == null) throw new NullPointerException();
4520 >            boolean modified = false;
4521 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4522 >                if (c.contains(it.next())) {
4523 >                    it.remove();
4524 >                    modified = true;
4525 >                }
4526 >            }
4527 >            return modified;
4528          }
4529  
4530 <        /**
4531 <         * Returns a task that when invoked, returns the result of
4532 <         * accumulating the given transformation of all keys using the given
4533 <         * reducer to combine values, or null if none.
4534 <         *
4535 <         * @param map the map
4536 <         * @param transformer a function returning the transformation
4537 <         * for an element, or null if there is no transformation (in
4538 <         * which case it is not combined).
4539 <         * @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);
4530 >        public final boolean retainAll(Collection<?> c) {
4531 >            if (c == null) throw new NullPointerException();
4532 >            boolean modified = false;
4533 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4534 >                if (!c.contains(it.next())) {
4535 >                    it.remove();
4536 >                    modified = true;
4537 >                }
4538 >            }
4539 >            return modified;
4540          }
4541  
4542 <        /**
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 <        }
4542 >    }
4543  
4544 <        /**
4545 <         * Returns a task that when invoked, returns the result of
4546 <         * accumulating the given transformation of all keys using the given
4547 <         * reducer to combine values, and the given basis as an
4548 <         * identity value.
4549 <         *
4550 <         * @param map the map
4551 <         * @param transformer a function returning the transformation
4552 <         * for an element
4553 <         * @param basis the identity (initial default value) for the reduction
4554 <         * @param reducer a commutative associative combining function
4555 <         * @return the task
4556 <         */
4557 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
4558 <            (ConcurrentHashMap<K,V> map,
4559 <             ObjectToLong<? super K> transformer,
4560 <             long basis,
4561 <             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);
4544 >    /**
4545 >     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4546 >     * which additions may optionally be enabled by mapping to a
4547 >     * common value.  This class cannot be directly instantiated.
4548 >     * See {@link #keySet() keySet()},
4549 >     * {@link #keySet(Object) keySet(V)},
4550 >     * {@link #newKeySet() newKeySet()},
4551 >     * {@link #newKeySet(int) newKeySet(int)}.
4552 >     *
4553 >     * @since 1.8
4554 >     */
4555 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4556 >        implements Set<K>, java.io.Serializable {
4557 >        private static final long serialVersionUID = 7249069246763182397L;
4558 >        private final V value;
4559 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4560 >            super(map);
4561 >            this.value = value;
4562          }
4563  
4564          /**
4565 <         * Returns a task that when invoked, returns the result of
4566 <         * accumulating the given transformation of all keys using the given
4537 <         * reducer to combine values, and the given basis as an
4538 <         * identity value.
4565 >         * Returns the default mapped value for additions,
4566 >         * or {@code null} if additions are not supported.
4567           *
4568 <         * @param map the map
4569 <         * @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
4568 >         * @return the default mapped value for additions, or {@code null}
4569 >         * if not supported
4570           */
4571 <        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 <        }
4571 >        public V getMappedValue() { return value; }
4572  
4573          /**
4574 <         * Returns a task that when invoked, performs the given action
4575 <         * for each value.
4561 <         *
4562 <         * @param map the map
4563 <         * @param action the action
4574 >         * {@inheritDoc}
4575 >         * @throws NullPointerException if the specified key is null
4576           */
4577 <        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 <        }
4577 >        public boolean contains(Object o) { return map.containsKey(o); }
4578  
4579          /**
4580 <         * Returns a task that when invoked, performs the given action
4581 <         * for each non-null transformation of each value.
4580 >         * Removes the key from this map view, by removing the key (and its
4581 >         * corresponding value) from the backing map.  This method does
4582 >         * nothing if the key is not in the map.
4583           *
4584 <         * @param map the map
4585 <         * @param transformer a function returning the transformation
4586 <         * for an element, or null if there is no transformation (in
4579 <         * which case the action is not applied)
4580 <         * @param action the action
4584 >         * @param  o the key to be removed from the backing map
4585 >         * @return {@code true} if the backing map contained the specified key
4586 >         * @throws NullPointerException if the specified key is null
4587           */
4588 <        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 <        }
4588 >        public boolean remove(Object o) { return map.remove(o) != null; }
4589  
4590          /**
4591 <         * 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
4591 >         * @return an iterator over the keys of the backing map
4592           */
4593 <        public static <K,V,U> ForkJoinTask<U> searchValues
4594 <            (ConcurrentHashMap<K,V> map,
4595 <             Fun<? super V, ? extends U> searchFunction) {
4596 <            if (searchFunction == null) throw new NullPointerException();
4597 <            return new SearchValuesTask<K,V,U>
4609 <                (map, null, -1, null, searchFunction,
4610 <                 new AtomicReference<U>());
4593 >        public Iterator<K> iterator() {
4594 >            Node<K,V>[] t;
4595 >            ConcurrentHashMap<K,V> m = map;
4596 >            int f = (t = m.table) == null ? 0 : t.length;
4597 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4598          }
4599  
4600          /**
4601 <         * Returns a task that when invoked, returns the result of
4602 <         * accumulating all values using the given reducer to combine
4616 <         * values, or null if none.
4601 >         * Adds the specified key to this set view by mapping the key to
4602 >         * the default mapped value in the backing map, if defined.
4603           *
4604 <         * @param map the map
4605 <         * @param reducer a commutative associative combining function
4606 <         * @return the task
4604 >         * @param e key to be added
4605 >         * @return {@code true} if this set changed as a result of the call
4606 >         * @throws NullPointerException if the specified key is null
4607 >         * @throws UnsupportedOperationException if no default mapped value
4608 >         * for additions was provided
4609           */
4610 <        public static <K,V> ForkJoinTask<V> reduceValues
4611 <            (ConcurrentHashMap<K,V> map,
4612 <             BiFun<? super V, ? super V, ? extends V> reducer) {
4613 <            if (reducer == null) throw new NullPointerException();
4614 <            return new ReduceValuesTask<K,V>
4627 <                (map, null, -1, null, reducer);
4610 >        public boolean add(K e) {
4611 >            V v;
4612 >            if ((v = value) == null)
4613 >                throw new UnsupportedOperationException();
4614 >            return map.putVal(e, v, true) == null;
4615          }
4616  
4617          /**
4618 <         * Returns a task that when invoked, returns the result of
4619 <         * accumulating the given transformation of all values using the
4633 <         * given reducer to combine values, or null if none.
4618 >         * Adds all of the elements in the specified collection to this set,
4619 >         * as if by calling {@link #add} on each one.
4620           *
4621 <         * @param map the map
4622 <         * @param transformer a function returning the transformation
4623 <         * for an element, or null if there is no transformation (in
4624 <         * which case it is not combined).
4625 <         * @param reducer a commutative associative combining function
4626 <         * @return the task
4621 >         * @param c the elements to be inserted into this set
4622 >         * @return {@code true} if this set changed as a result of the call
4623 >         * @throws NullPointerException if the collection or any of its
4624 >         * elements are {@code null}
4625 >         * @throws UnsupportedOperationException if no default mapped value
4626 >         * for additions was provided
4627           */
4628 <        public static <K,V,U> ForkJoinTask<U> reduceValues
4629 <            (ConcurrentHashMap<K,V> map,
4630 <             Fun<? super V, ? extends U> transformer,
4631 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4632 <            if (transformer == null || reducer == null)
4633 <                throw new NullPointerException();
4634 <            return new MapReduceValuesTask<K,V,U>
4635 <                (map, null, -1, null, transformer, reducer);
4628 >        public boolean addAll(Collection<? extends K> c) {
4629 >            boolean added = false;
4630 >            V v;
4631 >            if ((v = value) == null)
4632 >                throw new UnsupportedOperationException();
4633 >            for (K e : c) {
4634 >                if (map.putVal(e, v, true) == null)
4635 >                    added = true;
4636 >            }
4637 >            return added;
4638          }
4639  
4640 <        /**
4641 <         * Returns a task that when invoked, returns the result of
4642 <         * accumulating the given transformation of all values using the
4643 <         * given reducer to combine values, and the given basis as an
4644 <         * 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);
4640 >        public int hashCode() {
4641 >            int h = 0;
4642 >            for (K e : this)
4643 >                h += e.hashCode();
4644 >            return h;
4645          }
4646  
4647 <        /**
4648 <         * Returns a task that when invoked, returns the result of
4649 <         * accumulating the given transformation of all values using the
4650 <         * given reducer to combine values, and the given basis as an
4651 <         * 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);
4647 >        public boolean equals(Object o) {
4648 >            Set<?> c;
4649 >            return ((o instanceof Set) &&
4650 >                    ((c = (Set<?>)o) == this ||
4651 >                     (containsAll(c) && c.containsAll(this))));
4652          }
4653  
4654 <        /**
4655 <         * Returns a task that when invoked, returns the result of
4656 <         * accumulating the given transformation of all values using the
4657 <         * given reducer to combine values, and the given basis as an
4658 <         * identity value.
4659 <         *
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);
4654 >        public Spliterator<K> spliterator() {
4655 >            Node<K,V>[] t;
4656 >            ConcurrentHashMap<K,V> m = map;
4657 >            long n = m.sumCount();
4658 >            int f = (t = m.table) == null ? 0 : t.length;
4659 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4660          }
4661  
4662 <        /**
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) {
4662 >        public void forEach(Consumer<? super K> action) {
4663              if (action == null) throw new NullPointerException();
4664 <            return new ForEachEntryTask<K,V>(map, null, -1, null, action);
4664 >            Node<K,V>[] t;
4665 >            if ((t = map.table) != null) {
4666 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4667 >                for (Node<K,V> p; (p = it.advance()) != null; )
4668 >                    action.accept(p.key);
4669 >            }
4670          }
4671 +    }
4672  
4673 <        /**
4674 <         * Returns a task that when invoked, perform the given action
4675 <         * for each non-null transformation of each entry.
4676 <         *
4677 <         * @param map the map
4678 <         * @param transformer a function returning the transformation
4679 <         * for an element, or null if there is no transformation (in
4680 <         * which case the action is not applied)
4681 <         * @param action the action
4682 <         */
4683 <        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);
4673 >    /**
4674 >     * A view of a ConcurrentHashMap as a {@link Collection} of
4675 >     * values, in which additions are disabled. This class cannot be
4676 >     * directly instantiated. See {@link #values()}.
4677 >     */
4678 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4679 >        implements Collection<V>, java.io.Serializable {
4680 >        private static final long serialVersionUID = 2249069246763182397L;
4681 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4682 >        public final boolean contains(Object o) {
4683 >            return map.containsValue(o);
4684          }
4685  
4686 <        /**
4687 <         * Returns a task that when invoked, returns a non-null result
4688 <         * from applying the given search function on each entry, or
4689 <         * null if none.  Upon success, further element processing is
4690 <         * suppressed and the results of any other parallel
4691 <         * invocations of the search function are ignored.
4692 <         *
4693 <         * @param map the map
4694 <         * @param searchFunction a function returning a non-null
4695 <         * 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>());
4686 >        public final boolean remove(Object o) {
4687 >            if (o != null) {
4688 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4689 >                    if (o.equals(it.next())) {
4690 >                        it.remove();
4691 >                        return true;
4692 >                    }
4693 >                }
4694 >            }
4695 >            return false;
4696          }
4697  
4698 <        /**
4699 <         * Returns a task that when invoked, returns the result of
4700 <         * accumulating all entries using the given reducer to combine
4701 <         * values, or null if none.
4702 <         *
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);
4698 >        public final Iterator<V> iterator() {
4699 >            ConcurrentHashMap<K,V> m = map;
4700 >            Node<K,V>[] t;
4701 >            int f = (t = m.table) == null ? 0 : t.length;
4702 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4703          }
4704  
4705 <        /**
4706 <         * Returns a task that when invoked, returns the result of
4707 <         * accumulating the given transformation of all entries using the
4708 <         * given reducer to combine values, or null if none.
4709 <         *
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);
4705 >        public final boolean add(V e) {
4706 >            throw new UnsupportedOperationException();
4707 >        }
4708 >        public final boolean addAll(Collection<? extends V> c) {
4709 >            throw new UnsupportedOperationException();
4710          }
4711  
4712 <        /**
4713 <         * 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);
4712 >        public boolean removeIf(Predicate<? super V> filter) {
4713 >            return map.removeValueIf(filter);
4714          }
4715  
4716 <        /**
4717 <         * Returns a task that when invoked, returns the result of
4718 <         * accumulating the given transformation of all entries using the
4719 <         * given reducer to combine values, and the given basis as an
4720 <         * identity value.
4721 <         *
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);
4716 >        public Spliterator<V> spliterator() {
4717 >            Node<K,V>[] t;
4718 >            ConcurrentHashMap<K,V> m = map;
4719 >            long n = m.sumCount();
4720 >            int f = (t = m.table) == null ? 0 : t.length;
4721 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4722          }
4723  
4724 <        /**
4725 <         * Returns a task that when invoked, returns the result of
4726 <         * accumulating the given transformation of all entries using the
4727 <         * given reducer to combine values, and the given basis as an
4728 <         * identity value.
4729 <         *
4730 <         * @param map the map
4731 <         * @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);
4724 >        public void forEach(Consumer<? super V> action) {
4725 >            if (action == null) throw new NullPointerException();
4726 >            Node<K,V>[] t;
4727 >            if ((t = map.table) != null) {
4728 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4729 >                for (Node<K,V> p; (p = it.advance()) != null; )
4730 >                    action.accept(p.val);
4731 >            }
4732          }
4733      }
4734  
4891    // -------------------------------------------------------
4892
4735      /**
4736 <     * Base for FJ tasks for bulk operations. This adds a variant of
4737 <     * CountedCompleters and some split and merge bookkeeping to
4738 <     * iterator functionality. The forEach and reduce methods are
4739 <     * similar to those illustrated in CountedCompleter documentation,
4740 <     * except that bottom-up reduction completions perform them within
4741 <     * their compute methods. The search methods are like forEach
4742 <     * except they continually poll for success and exit early.  Also,
4743 <     * 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
4736 >     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4737 >     * entries.  This class cannot be directly instantiated. See
4738 >     * {@link #entrySet()}.
4739 >     */
4740 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4741 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4742 >        private static final long serialVersionUID = 2249069246763182397L;
4743 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4744  
4745 <        BulkTask(ConcurrentHashMap<K,V> map, BulkTask<K,V,?> parent,
4746 <                 int batch) {
4747 <            super(map);
4748 <            this.parent = parent;
4749 <            this.batch = batch;
4750 <            if (parent != null && map != null) { // split parent
4751 <                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 <            }
4745 >        public boolean contains(Object o) {
4746 >            Object k, v, r; Map.Entry<?,?> e;
4747 >            return ((o instanceof Map.Entry) &&
4748 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4749 >                    (r = map.get(k)) != null &&
4750 >                    (v = e.getValue()) != null &&
4751 >                    (v == r || v.equals(r)));
4752          }
4753  
4754 <        /**
4755 <         * Forces root task to complete.
4756 <         * @param ex if null, complete normally, else exceptionally
4757 <         * @return false to simplify use
4758 <         */
4759 <        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 <            }
4754 >        public boolean remove(Object o) {
4755 >            Object k, v; Map.Entry<?,?> e;
4756 >            return ((o instanceof Map.Entry) &&
4757 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4758 >                    (v = e.getValue()) != null &&
4759 >                    map.remove(k, v));
4760          }
4761  
4762          /**
4763 <         * Version of tryCompleteComputation for function screening checks
4763 >         * @return an iterator over the entries of the backing map
4764           */
4765 <        final boolean abortOnNullFunction() {
4766 <            return tryCompleteComputation(new Error("Unexpected null function"));
4765 >        public Iterator<Map.Entry<K,V>> iterator() {
4766 >            ConcurrentHashMap<K,V> m = map;
4767 >            Node<K,V>[] t;
4768 >            int f = (t = m.table) == null ? 0 : t.length;
4769 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4770          }
4771  
4772 <        // utilities
4772 >        public boolean add(Entry<K,V> e) {
4773 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4774 >        }
4775  
4776 <        /** CompareAndSet pending count */
4777 <        final boolean casPending(int cmp, int val) {
4778 <            return U.compareAndSwapInt(this, PENDING, cmp, val);
4776 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4777 >            boolean added = false;
4778 >            for (Entry<K,V> e : c) {
4779 >                if (add(e))
4780 >                    added = true;
4781 >            }
4782 >            return added;
4783          }
4784  
4785 <        /**
4786 <         * Returns approx exp2 of the number of times (minus one) to
4787 <         * split task by two before executing leaf action. This value
4788 <         * is faster to compute and more convenient to use as a guide
4789 <         * to splitting than is the depth, since it is used while
4790 <         * dividing by two anyway.
4791 <         */
4792 <        final int batch() {
4793 <            ConcurrentHashMap<K, V> m; int b; Node[] t;  ForkJoinPool pool;
4794 <            if ((b = batch) < 0 && (m = map) != null) { // force initialization
4795 <                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;
4785 >        public boolean removeIf(Predicate<? super Entry<K,V>> filter) {
4786 >            return map.removeEntryIf(filter);
4787 >        }
4788 >
4789 >        public final int hashCode() {
4790 >            int h = 0;
4791 >            Node<K,V>[] t;
4792 >            if ((t = map.table) != null) {
4793 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4794 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4795 >                    h += p.hashCode();
4796                  }
4797              }
4798 <            return b;
4798 >            return h;
4799          }
4800  
4801 <        /**
4802 <         * Returns exportable snapshot entry.
4803 <         */
4804 <        static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
4805 <            return new AbstractMap.SimpleEntry<K,V>(k, v);
4801 >        public final boolean equals(Object o) {
4802 >            Set<?> c;
4803 >            return ((o instanceof Set) &&
4804 >                    ((c = (Set<?>)o) == this ||
4805 >                     (containsAll(c) && c.containsAll(this))));
4806          }
4807  
4808 <        // Unsafe mechanics
4809 <        private static final sun.misc.Unsafe U;
4810 <        private static final long PENDING;
4811 <        static {
4812 <            try {
4813 <                U = sun.misc.Unsafe.getUnsafe();
4814 <                PENDING = U.objectFieldOffset
4815 <                    (BulkTask.class.getDeclaredField("pending"));
4816 <            } catch (Exception e) {
4817 <                throw new Error(e);
4808 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4809 >            Node<K,V>[] t;
4810 >            ConcurrentHashMap<K,V> m = map;
4811 >            long n = m.sumCount();
4812 >            int f = (t = m.table) == null ? 0 : t.length;
4813 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4814 >        }
4815 >
4816 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4817 >            if (action == null) throw new NullPointerException();
4818 >            Node<K,V>[] t;
4819 >            if ((t = map.table) != null) {
4820 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4821 >                for (Node<K,V> p; (p = it.advance()) != null; )
4822 >                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
4823              }
4824          }
4825 +
4826      }
4827  
4828 +    // -------------------------------------------------------
4829 +
4830      /**
4831 <     * Base class for non-reductive actions
4831 >     * Base class for bulk tasks. Repeats some fields and code from
4832 >     * class Traverser, because we need to subclass CountedCompleter.
4833       */
4834 <    @SuppressWarnings("serial") static abstract class BulkAction<K,V,R> extends BulkTask<K,V,R> {
4835 <        BulkAction<K,V,?> nextTask;
4836 <        BulkAction(ConcurrentHashMap<K,V> map, BulkTask<K,V,?> parent,
4837 <                   int batch, BulkAction<K,V,?> nextTask) {
4838 <            super(map, parent, batch);
4839 <            this.nextTask = nextTask;
4834 >    @SuppressWarnings("serial")
4835 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4836 >        Node<K,V>[] tab;        // same as Traverser
4837 >        Node<K,V> next;
4838 >        TableStack<K,V> stack, spare;
4839 >        int index;
4840 >        int baseIndex;
4841 >        int baseLimit;
4842 >        final int baseSize;
4843 >        int batch;              // split control
4844 >
4845 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4846 >            super(par);
4847 >            this.batch = b;
4848 >            this.index = this.baseIndex = i;
4849 >            if ((this.tab = t) == null)
4850 >                this.baseSize = this.baseLimit = 0;
4851 >            else if (par == null)
4852 >                this.baseSize = this.baseLimit = t.length;
4853 >            else {
4854 >                this.baseLimit = f;
4855 >                this.baseSize = par.baseSize;
4856 >            }
4857          }
4858  
4859          /**
4860 <         * 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.
4860 >         * Same as Traverser version
4861           */
4862 <        final void tryComplete(BulkAction<K,V,?> subtasks) {
4863 <            BulkTask<K,V,?> a = this, s = a;
4864 <            for (int c;;) {
4865 <                if ((c = a.pending) == 0) {
4866 <                    if ((a = (s = a).parent) == null) {
4867 <                        s.quietlyComplete();
4868 <                        break;
4869 <                    }
4870 <                }
4871 <                else if (a.casPending(c, c - 1)) {
4872 <                    if (subtasks != null && !inForkJoinPool()) {
4873 <                        while ((s = a.parent) != null)
4874 <                            a = s;
4875 <                        while (!a.isDone()) {
4876 <                            BulkAction<K,V,?> next = subtasks.nextTask;
4877 <                            if (subtasks.tryUnfork())
4878 <                                subtasks.exec();
5038 <                            if ((subtasks = next) == null)
5039 <                                break;
5040 <                        }
4862 >        final Node<K,V> advance() {
4863 >            Node<K,V> e;
4864 >            if ((e = next) != null)
4865 >                e = e.next;
4866 >            for (;;) {
4867 >                Node<K,V>[] t; int i, n;
4868 >                if (e != null)
4869 >                    return next = e;
4870 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4871 >                    (n = t.length) <= (i = index) || i < 0)
4872 >                    return next = null;
4873 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
4874 >                    if (e instanceof ForwardingNode) {
4875 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4876 >                        e = null;
4877 >                        pushState(t, i, n);
4878 >                        continue;
4879                      }
4880 <                    break;
4880 >                    else if (e instanceof TreeBin)
4881 >                        e = ((TreeBin<K,V>)e).first;
4882 >                    else
4883 >                        e = null;
4884                  }
4885 +                if (stack != null)
4886 +                    recoverState(n);
4887 +                else if ((index = i + baseSize) >= n)
4888 +                    index = ++baseIndex;
4889              }
4890          }
4891  
4892 +        private void pushState(Node<K,V>[] t, int i, int n) {
4893 +            TableStack<K,V> s = spare;
4894 +            if (s != null)
4895 +                spare = s.next;
4896 +            else
4897 +                s = new TableStack<K,V>();
4898 +            s.tab = t;
4899 +            s.length = n;
4900 +            s.index = i;
4901 +            s.next = stack;
4902 +            stack = s;
4903 +        }
4904 +
4905 +        private void recoverState(int n) {
4906 +            TableStack<K,V> s; int len;
4907 +            while ((s = stack) != null && (index += (len = s.length)) >= n) {
4908 +                n = len;
4909 +                index = s.index;
4910 +                tab = s.tab;
4911 +                s.tab = null;
4912 +                TableStack<K,V> next = s.next;
4913 +                s.next = spare; // save for reuse
4914 +                stack = next;
4915 +                spare = s;
4916 +            }
4917 +            if (s == null && (index += baseSize) >= n)
4918 +                index = ++baseIndex;
4919 +        }
4920      }
4921  
4922      /*
4923       * Task classes. Coded in a regular but ugly format/style to
4924       * simplify checks that each variant differs in the right way from
4925 <     * others.
4926 <     */
4927 <
4928 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4929 <        extends BulkAction<K,V,Void> {
4930 <        final Action<K> action;
4925 >     * others. The null screenings exist because compilers cannot tell
4926 >     * that we've already null-checked task arguments, so we force
4927 >     * simplest hoisted bypass to help avoid convoluted traps.
4928 >     */
4929 >    @SuppressWarnings("serial")
4930 >    static final class ForEachKeyTask<K,V>
4931 >        extends BulkTask<K,V,Void> {
4932 >        final Consumer<? super K> action;
4933          ForEachKeyTask
4934 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4935 <             ForEachKeyTask<K,V> nextTask,
4936 <             Action<K> action) {
5062 <            super(m, p, b, nextTask);
4934 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4935 >             Consumer<? super K> action) {
4936 >            super(p, b, i, f, t);
4937              this.action = action;
4938          }
4939 <        @SuppressWarnings("unchecked") public final boolean exec() {
4940 <            final Action<K> action = this.action;
4941 <            if (action == null)
4942 <                return abortOnNullFunction();
4943 <            ForEachKeyTask<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 ForEachKeyTask<K,V>
4949 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4950 <                }
4951 <                while (advance() != null)
5078 <                    action.apply((K)nextKey);
5079 <            } catch (Throwable ex) {
5080 <                return tryCompleteComputation(ex);
4939 >        public final void compute() {
4940 >            final Consumer<? super K> 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 ForEachKeyTask<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.key);
4951 >                propagateCompletion();
4952              }
5082            tryComplete(subtasks);
5083            return false;
4953          }
4954      }
4955  
4956 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4957 <        extends BulkAction<K,V,Void> {
4958 <        final Action<V> action;
4956 >    @SuppressWarnings("serial")
4957 >    static final class ForEachValueTask<K,V>
4958 >        extends BulkTask<K,V,Void> {
4959 >        final Consumer<? super V> action;
4960          ForEachValueTask
4961 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4962 <             ForEachValueTask<K,V> nextTask,
4963 <             Action<V> action) {
5094 <            super(m, p, b, nextTask);
4961 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4962 >             Consumer<? super V> action) {
4963 >            super(p, b, i, f, t);
4964              this.action = action;
4965          }
4966 <        @SuppressWarnings("unchecked") public final boolean exec() {
4967 <            final Action<V> action = this.action;
4968 <            if (action == null)
4969 <                return abortOnNullFunction();
4970 <            ForEachValueTask<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 ForEachValueTask<K,V>
4976 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4977 <                }
4978 <                Object v;
5110 <                while ((v = advance()) != null)
5111 <                    action.apply((V)v);
5112 <            } catch (Throwable ex) {
5113 <                return tryCompleteComputation(ex);
4966 >        public final void compute() {
4967 >            final Consumer<? 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 ForEachValueTask<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.val);
4978 >                propagateCompletion();
4979              }
5115            tryComplete(subtasks);
5116            return false;
4980          }
4981      }
4982  
4983 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4984 <        extends BulkAction<K,V,Void> {
4985 <        final Action<Entry<K,V>> action;
4983 >    @SuppressWarnings("serial")
4984 >    static final class ForEachEntryTask<K,V>
4985 >        extends BulkTask<K,V,Void> {
4986 >        final Consumer<? super Entry<K,V>> action;
4987          ForEachEntryTask
4988 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4989 <             ForEachEntryTask<K,V> nextTask,
4990 <             Action<Entry<K,V>> action) {
5127 <            super(m, p, b, nextTask);
4988 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4989 >             Consumer<? super Entry<K,V>> action) {
4990 >            super(p, b, i, f, t);
4991              this.action = action;
4992          }
4993 <        @SuppressWarnings("unchecked") public final boolean exec() {
4994 <            final Action<Entry<K,V>> action = this.action;
4995 <            if (action == null)
4996 <                return abortOnNullFunction();
4997 <            ForEachEntryTask<K,V> subtasks = null;
4998 <            try {
4999 <                int b = batch(), c;
5000 <                while (b > 1 && baseIndex != baseLimit) {
5001 <                    do {} while (!casPending(c = pending, c+1));
5002 <                    (subtasks = new ForEachEntryTask<K,V>
5003 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5004 <                }
5005 <                Object v;
5143 <                while ((v = advance()) != null)
5144 <                    action.apply(entryFor((K)nextKey, (V)v));
5145 <            } catch (Throwable ex) {
5146 <                return tryCompleteComputation(ex);
4993 >        public final void compute() {
4994 >            final Consumer<? super Entry<K,V>> action;
4995 >            if ((action = this.action) != null) {
4996 >                for (int i = baseIndex, f, h; batch > 0 &&
4997 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4998 >                    addToPendingCount(1);
4999 >                    new ForEachEntryTask<K,V>
5000 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5001 >                         action).fork();
5002 >                }
5003 >                for (Node<K,V> p; (p = advance()) != null; )
5004 >                    action.accept(p);
5005 >                propagateCompletion();
5006              }
5148            tryComplete(subtasks);
5149            return false;
5007          }
5008      }
5009  
5010 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5011 <        extends BulkAction<K,V,Void> {
5012 <        final BiAction<K,V> action;
5010 >    @SuppressWarnings("serial")
5011 >    static final class ForEachMappingTask<K,V>
5012 >        extends BulkTask<K,V,Void> {
5013 >        final BiConsumer<? super K, ? super V> action;
5014          ForEachMappingTask
5015 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5016 <             ForEachMappingTask<K,V> nextTask,
5017 <             BiAction<K,V> action) {
5160 <            super(m, p, b, nextTask);
5015 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5016 >             BiConsumer<? super K,? super V> action) {
5017 >            super(p, b, i, f, t);
5018              this.action = action;
5019          }
5020 <        @SuppressWarnings("unchecked") public final boolean exec() {
5021 <            final BiAction<K,V> action = this.action;
5022 <            if (action == null)
5023 <                return abortOnNullFunction();
5024 <            ForEachMappingTask<K,V> subtasks = null;
5025 <            try {
5026 <                int b = batch(), c;
5027 <                while (b > 1 && baseIndex != baseLimit) {
5028 <                    do {} while (!casPending(c = pending, c+1));
5029 <                    (subtasks = new ForEachMappingTask<K,V>
5030 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5031 <                }
5032 <                Object v;
5176 <                while ((v = advance()) != null)
5177 <                    action.apply((K)nextKey, (V)v);
5178 <            } catch (Throwable ex) {
5179 <                return tryCompleteComputation(ex);
5020 >        public final void compute() {
5021 >            final BiConsumer<? super K, ? super V> action;
5022 >            if ((action = this.action) != null) {
5023 >                for (int i = baseIndex, f, h; batch > 0 &&
5024 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5025 >                    addToPendingCount(1);
5026 >                    new ForEachMappingTask<K,V>
5027 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5028 >                         action).fork();
5029 >                }
5030 >                for (Node<K,V> p; (p = advance()) != null; )
5031 >                    action.accept(p.key, p.val);
5032 >                propagateCompletion();
5033              }
5181            tryComplete(subtasks);
5182            return false;
5034          }
5035      }
5036  
5037 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5038 <        extends BulkAction<K,V,Void> {
5039 <        final Fun<? super K, ? extends U> transformer;
5040 <        final Action<U> action;
5037 >    @SuppressWarnings("serial")
5038 >    static final class ForEachTransformedKeyTask<K,V,U>
5039 >        extends BulkTask<K,V,Void> {
5040 >        final Function<? super K, ? extends U> transformer;
5041 >        final Consumer<? super U> action;
5042          ForEachTransformedKeyTask
5043 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5044 <             ForEachTransformedKeyTask<K,V,U> nextTask,
5045 <             Fun<? super K, ? extends U> transformer,
5046 <             Action<U> action) {
5047 <            super(m, p, b, nextTask);
5048 <            this.transformer = transformer;
5049 <            this.action = action;
5050 <
5051 <        }
5052 <        @SuppressWarnings("unchecked") public final boolean exec() {
5053 <            final Fun<? super K, ? extends U> transformer =
5054 <                this.transformer;
5055 <            final Action<U> action = this.action;
5056 <            if (transformer == null || action == null)
5057 <                return abortOnNullFunction();
5058 <            ForEachTransformedKeyTask<K,V,U> subtasks = null;
5059 <            try {
5060 <                int b = batch(), c;
5061 <                while (b > 1 && baseIndex != baseLimit) {
5062 <                    do {} while (!casPending(c = pending, c+1));
5063 <                    (subtasks = new ForEachTransformedKeyTask<K,V,U>
5064 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5065 <                }
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);
5043 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5044 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5045 >            super(p, b, i, f, t);
5046 >            this.transformer = transformer; this.action = action;
5047 >        }
5048 >        public final void compute() {
5049 >            final Function<? super K, ? extends U> transformer;
5050 >            final Consumer<? super U> action;
5051 >            if ((transformer = this.transformer) != null &&
5052 >                (action = this.action) != null) {
5053 >                for (int i = baseIndex, f, h; batch > 0 &&
5054 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5055 >                    addToPendingCount(1);
5056 >                    new ForEachTransformedKeyTask<K,V,U>
5057 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5058 >                         transformer, action).fork();
5059 >                }
5060 >                for (Node<K,V> p; (p = advance()) != null; ) {
5061 >                    U u;
5062 >                    if ((u = transformer.apply(p.key)) != null)
5063 >                        action.accept(u);
5064 >                }
5065 >                propagateCompletion();
5066              }
5222            tryComplete(subtasks);
5223            return false;
5067          }
5068      }
5069  
5070 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5071 <        extends BulkAction<K,V,Void> {
5072 <        final Fun<? super V, ? extends U> transformer;
5073 <        final Action<U> action;
5070 >    @SuppressWarnings("serial")
5071 >    static final class ForEachTransformedValueTask<K,V,U>
5072 >        extends BulkTask<K,V,Void> {
5073 >        final Function<? super V, ? extends U> transformer;
5074 >        final Consumer<? super U> action;
5075          ForEachTransformedValueTask
5076 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5077 <             ForEachTransformedValueTask<K,V,U> nextTask,
5078 <             Fun<? super V, ? extends U> transformer,
5079 <             Action<U> action) {
5080 <            super(m, p, b, nextTask);
5081 <            this.transformer = transformer;
5082 <            this.action = action;
5083 <
5084 <        }
5085 <        @SuppressWarnings("unchecked") public final boolean exec() {
5086 <            final Fun<? super V, ? extends U> transformer =
5087 <                this.transformer;
5088 <            final Action<U> action = this.action;
5089 <            if (transformer == null || action == null)
5090 <                return abortOnNullFunction();
5091 <            ForEachTransformedValueTask<K,V,U> subtasks = null;
5092 <            try {
5093 <                int b = batch(), c;
5094 <                while (b > 1 && baseIndex != baseLimit) {
5095 <                    do {} while (!casPending(c = pending, c+1));
5096 <                    (subtasks = new ForEachTransformedValueTask<K,V,U>
5097 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5098 <                }
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);
5076 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5077 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5078 >            super(p, b, i, f, t);
5079 >            this.transformer = transformer; this.action = action;
5080 >        }
5081 >        public final void compute() {
5082 >            final Function<? super V, ? extends U> transformer;
5083 >            final Consumer<? super U> action;
5084 >            if ((transformer = this.transformer) != null &&
5085 >                (action = this.action) != null) {
5086 >                for (int i = baseIndex, f, h; batch > 0 &&
5087 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5088 >                    addToPendingCount(1);
5089 >                    new ForEachTransformedValueTask<K,V,U>
5090 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5091 >                         transformer, action).fork();
5092 >                }
5093 >                for (Node<K,V> p; (p = advance()) != null; ) {
5094 >                    U u;
5095 >                    if ((u = transformer.apply(p.val)) != null)
5096 >                        action.accept(u);
5097 >                }
5098 >                propagateCompletion();
5099              }
5263            tryComplete(subtasks);
5264            return false;
5100          }
5101      }
5102  
5103 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5104 <        extends BulkAction<K,V,Void> {
5105 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5106 <        final Action<U> action;
5103 >    @SuppressWarnings("serial")
5104 >    static final class ForEachTransformedEntryTask<K,V,U>
5105 >        extends BulkTask<K,V,Void> {
5106 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5107 >        final Consumer<? super U> action;
5108          ForEachTransformedEntryTask
5109 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5110 <             ForEachTransformedEntryTask<K,V,U> nextTask,
5111 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5112 <             Action<U> action) {
5113 <            super(m, p, b, nextTask);
5114 <            this.transformer = transformer;
5115 <            this.action = action;
5116 <
5117 <        }
5118 <        @SuppressWarnings("unchecked") public final boolean exec() {
5119 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5120 <                this.transformer;
5121 <            final Action<U> action = this.action;
5122 <            if (transformer == null || action == null)
5123 <                return abortOnNullFunction();
5124 <            ForEachTransformedEntryTask<K,V,U> subtasks = null;
5125 <            try {
5126 <                int b = batch(), c;
5127 <                while (b > 1 && baseIndex != baseLimit) {
5128 <                    do {} while (!casPending(c = pending, c+1));
5129 <                    (subtasks = new ForEachTransformedEntryTask<K,V,U>
5130 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5131 <                }
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);
5109 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5110 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5111 >            super(p, b, i, f, t);
5112 >            this.transformer = transformer; this.action = action;
5113 >        }
5114 >        public final void compute() {
5115 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5116 >            final Consumer<? super U> action;
5117 >            if ((transformer = this.transformer) != null &&
5118 >                (action = this.action) != null) {
5119 >                for (int i = baseIndex, f, h; batch > 0 &&
5120 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5121 >                    addToPendingCount(1);
5122 >                    new ForEachTransformedEntryTask<K,V,U>
5123 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5124 >                         transformer, action).fork();
5125 >                }
5126 >                for (Node<K,V> p; (p = advance()) != null; ) {
5127 >                    U u;
5128 >                    if ((u = transformer.apply(p)) != null)
5129 >                        action.accept(u);
5130 >                }
5131 >                propagateCompletion();
5132              }
5304            tryComplete(subtasks);
5305            return false;
5133          }
5134      }
5135  
5136 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5137 <        extends BulkAction<K,V,Void> {
5138 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5139 <        final Action<U> action;
5136 >    @SuppressWarnings("serial")
5137 >    static final class ForEachTransformedMappingTask<K,V,U>
5138 >        extends BulkTask<K,V,Void> {
5139 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5140 >        final Consumer<? super U> action;
5141          ForEachTransformedMappingTask
5142 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5143 <             ForEachTransformedMappingTask<K,V,U> nextTask,
5144 <             BiFun<? super K, ? super V, ? extends U> transformer,
5145 <             Action<U> action) {
5146 <            super(m, p, b, nextTask);
5147 <            this.transformer = transformer;
5148 <            this.action = action;
5149 <
5150 <        }
5151 <        @SuppressWarnings("unchecked") public final boolean exec() {
5152 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5153 <                this.transformer;
5154 <            final Action<U> action = this.action;
5155 <            if (transformer == null || action == null)
5156 <                return abortOnNullFunction();
5157 <            ForEachTransformedMappingTask<K,V,U> subtasks = null;
5158 <            try {
5159 <                int b = batch(), c;
5160 <                while (b > 1 && baseIndex != baseLimit) {
5161 <                    do {} while (!casPending(c = pending, c+1));
5162 <                    (subtasks = new ForEachTransformedMappingTask<K,V,U>
5163 <                     (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);
5142 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5143 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5144 >             Consumer<? super U> action) {
5145 >            super(p, b, i, f, t);
5146 >            this.transformer = transformer; this.action = action;
5147 >        }
5148 >        public final void compute() {
5149 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5150 >            final Consumer<? super U> action;
5151 >            if ((transformer = this.transformer) != null &&
5152 >                (action = this.action) != null) {
5153 >                for (int i = baseIndex, f, h; batch > 0 &&
5154 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5155 >                    addToPendingCount(1);
5156 >                    new ForEachTransformedMappingTask<K,V,U>
5157 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5158 >                         transformer, action).fork();
5159 >                }
5160 >                for (Node<K,V> p; (p = advance()) != null; ) {
5161 >                    U u;
5162 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5163 >                        action.accept(u);
5164                  }
5165 <            } catch (Throwable ex) {
5343 <                return tryCompleteComputation(ex);
5165 >                propagateCompletion();
5166              }
5345            tryComplete(subtasks);
5346            return false;
5167          }
5168      }
5169  
5170 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5171 <        extends BulkAction<K,V,U> {
5172 <        final Fun<? super K, ? extends U> searchFunction;
5170 >    @SuppressWarnings("serial")
5171 >    static final class SearchKeysTask<K,V,U>
5172 >        extends BulkTask<K,V,U> {
5173 >        final Function<? super K, ? extends U> searchFunction;
5174          final AtomicReference<U> result;
5175          SearchKeysTask
5176 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5177 <             SearchKeysTask<K,V,U> nextTask,
5357 <             Fun<? super K, ? extends U> searchFunction,
5176 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5177 >             Function<? super K, ? extends U> searchFunction,
5178               AtomicReference<U> result) {
5179 <            super(m, p, b, nextTask);
5179 >            super(p, b, i, f, t);
5180              this.searchFunction = searchFunction; this.result = result;
5181          }
5182 <        @SuppressWarnings("unchecked") public final boolean exec() {
5183 <            AtomicReference<U> result = this.result;
5184 <            final Fun<? super K, ? extends U> searchFunction =
5185 <                this.searchFunction;
5186 <            if (searchFunction == null || result == null)
5187 <                return abortOnNullFunction();
5188 <            SearchKeysTask<K,V,U> subtasks = null;
5189 <            try {
5190 <                int b = batch(), c;
5191 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5192 <                    do {} while (!casPending(c = pending, c+1));
5193 <                    (subtasks = new SearchKeysTask<K,V,U>
5194 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5195 <                }
5196 <                U u;
5197 <                while (result.get() == null && advance() != null) {
5198 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
5182 >        public final U getRawResult() { return result.get(); }
5183 >        public final void compute() {
5184 >            final Function<? super K, ? extends U> searchFunction;
5185 >            final AtomicReference<U> result;
5186 >            if ((searchFunction = this.searchFunction) != null &&
5187 >                (result = this.result) != null) {
5188 >                for (int i = baseIndex, f, h; batch > 0 &&
5189 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5190 >                    if (result.get() != null)
5191 >                        return;
5192 >                    addToPendingCount(1);
5193 >                    new SearchKeysTask<K,V,U>
5194 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5195 >                         searchFunction, result).fork();
5196 >                }
5197 >                while (result.get() == null) {
5198 >                    U u;
5199 >                    Node<K,V> p;
5200 >                    if ((p = advance()) == null) {
5201 >                        propagateCompletion();
5202 >                        break;
5203 >                    }
5204 >                    if ((u = searchFunction.apply(p.key)) != null) {
5205                          if (result.compareAndSet(null, u))
5206 <                            tryCompleteComputation(null);
5206 >                            quietlyCompleteRoot();
5207                          break;
5208                      }
5209                  }
5384            } catch (Throwable ex) {
5385                return tryCompleteComputation(ex);
5210              }
5387            tryComplete(subtasks);
5388            return false;
5211          }
5390        public final U getRawResult() { return result.get(); }
5212      }
5213  
5214 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5215 <        extends BulkAction<K,V,U> {
5216 <        final Fun<? super V, ? extends U> searchFunction;
5214 >    @SuppressWarnings("serial")
5215 >    static final class SearchValuesTask<K,V,U>
5216 >        extends BulkTask<K,V,U> {
5217 >        final Function<? super V, ? extends U> searchFunction;
5218          final AtomicReference<U> result;
5219          SearchValuesTask
5220 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5221 <             SearchValuesTask<K,V,U> nextTask,
5400 <             Fun<? super V, ? extends U> searchFunction,
5220 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5221 >             Function<? super V, ? extends U> searchFunction,
5222               AtomicReference<U> result) {
5223 <            super(m, p, b, nextTask);
5223 >            super(p, b, i, f, t);
5224              this.searchFunction = searchFunction; this.result = result;
5225          }
5226 <        @SuppressWarnings("unchecked") public final boolean exec() {
5227 <            AtomicReference<U> result = this.result;
5228 <            final Fun<? super V, ? extends U> searchFunction =
5229 <                this.searchFunction;
5230 <            if (searchFunction == null || result == null)
5231 <                return abortOnNullFunction();
5232 <            SearchValuesTask<K,V,U> subtasks = null;
5233 <            try {
5234 <                int b = batch(), c;
5235 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5236 <                    do {} while (!casPending(c = pending, c+1));
5237 <                    (subtasks = new SearchValuesTask<K,V,U>
5238 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5239 <                }
5240 <                Object v; U u;
5241 <                while (result.get() == null && (v = advance()) != null) {
5242 <                    if ((u = searchFunction.apply((V)v)) != null) {
5226 >        public final U getRawResult() { return result.get(); }
5227 >        public final void compute() {
5228 >            final Function<? super V, ? extends U> searchFunction;
5229 >            final AtomicReference<U> result;
5230 >            if ((searchFunction = this.searchFunction) != null &&
5231 >                (result = this.result) != null) {
5232 >                for (int i = baseIndex, f, h; batch > 0 &&
5233 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5234 >                    if (result.get() != null)
5235 >                        return;
5236 >                    addToPendingCount(1);
5237 >                    new SearchValuesTask<K,V,U>
5238 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5239 >                         searchFunction, result).fork();
5240 >                }
5241 >                while (result.get() == null) {
5242 >                    U u;
5243 >                    Node<K,V> p;
5244 >                    if ((p = advance()) == null) {
5245 >                        propagateCompletion();
5246 >                        break;
5247 >                    }
5248 >                    if ((u = searchFunction.apply(p.val)) != null) {
5249                          if (result.compareAndSet(null, u))
5250 <                            tryCompleteComputation(null);
5250 >                            quietlyCompleteRoot();
5251                          break;
5252                      }
5253                  }
5427            } catch (Throwable ex) {
5428                return tryCompleteComputation(ex);
5254              }
5430            tryComplete(subtasks);
5431            return false;
5255          }
5433        public final U getRawResult() { return result.get(); }
5256      }
5257  
5258 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5259 <        extends BulkAction<K,V,U> {
5260 <        final Fun<Entry<K,V>, ? extends U> searchFunction;
5258 >    @SuppressWarnings("serial")
5259 >    static final class SearchEntriesTask<K,V,U>
5260 >        extends BulkTask<K,V,U> {
5261 >        final Function<Entry<K,V>, ? extends U> searchFunction;
5262          final AtomicReference<U> result;
5263          SearchEntriesTask
5264 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5265 <             SearchEntriesTask<K,V,U> nextTask,
5443 <             Fun<Entry<K,V>, ? extends U> searchFunction,
5264 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5265 >             Function<Entry<K,V>, ? extends U> searchFunction,
5266               AtomicReference<U> result) {
5267 <            super(m, p, b, nextTask);
5267 >            super(p, b, i, f, t);
5268              this.searchFunction = searchFunction; this.result = result;
5269          }
5270 <        @SuppressWarnings("unchecked") public final boolean exec() {
5271 <            AtomicReference<U> result = this.result;
5272 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
5273 <                this.searchFunction;
5274 <            if (searchFunction == null || result == null)
5275 <                return abortOnNullFunction();
5276 <            SearchEntriesTask<K,V,U> subtasks = null;
5277 <            try {
5278 <                int b = batch(), c;
5279 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5280 <                    do {} while (!casPending(c = pending, c+1));
5281 <                    (subtasks = new SearchEntriesTask<K,V,U>
5282 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5283 <                }
5284 <                Object v; U u;
5285 <                while (result.get() == null && (v = advance()) != null) {
5286 <                    if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
5287 <                        if (result.compareAndSet(null, u))
5288 <                            tryCompleteComputation(null);
5270 >        public final U getRawResult() { return result.get(); }
5271 >        public final void compute() {
5272 >            final Function<Entry<K,V>, ? extends U> searchFunction;
5273 >            final AtomicReference<U> result;
5274 >            if ((searchFunction = this.searchFunction) != null &&
5275 >                (result = this.result) != null) {
5276 >                for (int i = baseIndex, f, h; batch > 0 &&
5277 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5278 >                    if (result.get() != null)
5279 >                        return;
5280 >                    addToPendingCount(1);
5281 >                    new SearchEntriesTask<K,V,U>
5282 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5283 >                         searchFunction, result).fork();
5284 >                }
5285 >                while (result.get() == null) {
5286 >                    U u;
5287 >                    Node<K,V> p;
5288 >                    if ((p = advance()) == null) {
5289 >                        propagateCompletion();
5290                          break;
5291                      }
5292 +                    if ((u = searchFunction.apply(p)) != null) {
5293 +                        if (result.compareAndSet(null, u))
5294 +                            quietlyCompleteRoot();
5295 +                        return;
5296 +                    }
5297                  }
5470            } catch (Throwable ex) {
5471                return tryCompleteComputation(ex);
5298              }
5473            tryComplete(subtasks);
5474            return false;
5299          }
5476        public final U getRawResult() { return result.get(); }
5300      }
5301  
5302 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5303 <        extends BulkAction<K,V,U> {
5304 <        final BiFun<? super K, ? super V, ? extends U> searchFunction;
5302 >    @SuppressWarnings("serial")
5303 >    static final class SearchMappingsTask<K,V,U>
5304 >        extends BulkTask<K,V,U> {
5305 >        final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5306          final AtomicReference<U> result;
5307          SearchMappingsTask
5308 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5309 <             SearchMappingsTask<K,V,U> nextTask,
5486 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
5308 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5309 >             BiFunction<? super K, ? super V, ? extends U> searchFunction,
5310               AtomicReference<U> result) {
5311 <            super(m, p, b, nextTask);
5311 >            super(p, b, i, f, t);
5312              this.searchFunction = searchFunction; this.result = result;
5313          }
5314 <        @SuppressWarnings("unchecked") public final boolean exec() {
5315 <            AtomicReference<U> result = this.result;
5316 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
5317 <                this.searchFunction;
5318 <            if (searchFunction == null || result == null)
5319 <                return abortOnNullFunction();
5320 <            SearchMappingsTask<K,V,U> subtasks = null;
5321 <            try {
5322 <                int b = batch(), c;
5323 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5324 <                    do {} while (!casPending(c = pending, c+1));
5325 <                    (subtasks = new SearchMappingsTask<K,V,U>
5326 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5327 <                }
5328 <                Object v; U u;
5329 <                while (result.get() == null && (v = advance()) != null) {
5330 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5314 >        public final U getRawResult() { return result.get(); }
5315 >        public final void compute() {
5316 >            final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5317 >            final AtomicReference<U> result;
5318 >            if ((searchFunction = this.searchFunction) != null &&
5319 >                (result = this.result) != null) {
5320 >                for (int i = baseIndex, f, h; batch > 0 &&
5321 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5322 >                    if (result.get() != null)
5323 >                        return;
5324 >                    addToPendingCount(1);
5325 >                    new SearchMappingsTask<K,V,U>
5326 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5327 >                         searchFunction, result).fork();
5328 >                }
5329 >                while (result.get() == null) {
5330 >                    U u;
5331 >                    Node<K,V> p;
5332 >                    if ((p = advance()) == null) {
5333 >                        propagateCompletion();
5334 >                        break;
5335 >                    }
5336 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5337                          if (result.compareAndSet(null, u))
5338 <                            tryCompleteComputation(null);
5338 >                            quietlyCompleteRoot();
5339                          break;
5340                      }
5341                  }
5513            } catch (Throwable ex) {
5514                return tryCompleteComputation(ex);
5342              }
5516            tryComplete(subtasks);
5517            return false;
5343          }
5519        public final U getRawResult() { return result.get(); }
5344      }
5345  
5346 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5346 >    @SuppressWarnings("serial")
5347 >    static final class ReduceKeysTask<K,V>
5348          extends BulkTask<K,V,K> {
5349 <        final BiFun<? super K, ? super K, ? extends K> reducer;
5349 >        final BiFunction<? super K, ? super K, ? extends K> reducer;
5350          K result;
5351          ReduceKeysTask<K,V> rights, nextRight;
5352          ReduceKeysTask
5353 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5353 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5354               ReduceKeysTask<K,V> nextRight,
5355 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5356 <            super(m, p, b); this.nextRight = nextRight;
5355 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
5356 >            super(p, b, i, f, t); this.nextRight = nextRight;
5357              this.reducer = reducer;
5358          }
5359 <        @SuppressWarnings("unchecked") public final boolean exec() {
5360 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5361 <                this.reducer;
5362 <            if (reducer == null)
5363 <                return abortOnNullFunction();
5364 <            try {
5365 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5541 <                    do {} while (!casPending(c = pending, c+1));
5359 >        public final K getRawResult() { return result; }
5360 >        public final void compute() {
5361 >            final BiFunction<? super K, ? super K, ? extends K> reducer;
5362 >            if ((reducer = this.reducer) != null) {
5363 >                for (int i = baseIndex, f, h; batch > 0 &&
5364 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5365 >                    addToPendingCount(1);
5366                      (rights = new ReduceKeysTask<K,V>
5367 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5367 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5368 >                      rights, reducer)).fork();
5369                  }
5370                  K r = null;
5371 <                while (advance() != null) {
5372 <                    K u = (K)nextKey;
5373 <                    r = (r == null) ? u : reducer.apply(r, u);
5371 >                for (Node<K,V> p; (p = advance()) != null; ) {
5372 >                    K u = p.key;
5373 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5374                  }
5375                  result = r;
5376 <                for (ReduceKeysTask<K,V> t = this, s;;) {
5377 <                    int c; BulkTask<K,V,?> par; K tr, sr;
5378 <                    if ((c = t.pending) == 0) {
5379 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5380 <                            if ((sr = s.result) != null)
5381 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5382 <                        }
5383 <                        if ((par = t.parent) == null ||
5384 <                            !(par instanceof ReduceKeysTask)) {
5385 <                            t.quietlyComplete();
5386 <                            break;
5387 <                        }
5563 <                        t = (ReduceKeysTask<K,V>)par;
5376 >                CountedCompleter<?> c;
5377 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5378 >                    @SuppressWarnings("unchecked")
5379 >                    ReduceKeysTask<K,V>
5380 >                        t = (ReduceKeysTask<K,V>)c,
5381 >                        s = t.rights;
5382 >                    while (s != null) {
5383 >                        K tr, sr;
5384 >                        if ((sr = s.result) != null)
5385 >                            t.result = (((tr = t.result) == null) ? sr :
5386 >                                        reducer.apply(tr, sr));
5387 >                        s = t.rights = s.nextRight;
5388                      }
5565                    else if (t.casPending(c, c - 1))
5566                        break;
5389                  }
5568            } catch (Throwable ex) {
5569                return tryCompleteComputation(ex);
5570            }
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);
5390              }
5578            return false;
5391          }
5580        public final K getRawResult() { return result; }
5392      }
5393  
5394 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5394 >    @SuppressWarnings("serial")
5395 >    static final class ReduceValuesTask<K,V>
5396          extends BulkTask<K,V,V> {
5397 <        final BiFun<? super V, ? super V, ? extends V> reducer;
5397 >        final BiFunction<? super V, ? super V, ? extends V> reducer;
5398          V result;
5399          ReduceValuesTask<K,V> rights, nextRight;
5400          ReduceValuesTask
5401 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5401 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5402               ReduceValuesTask<K,V> nextRight,
5403 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5404 <            super(m, p, b); this.nextRight = nextRight;
5403 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
5404 >            super(p, b, i, f, t); this.nextRight = nextRight;
5405              this.reducer = reducer;
5406          }
5407 <        @SuppressWarnings("unchecked") public final boolean exec() {
5408 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5409 <                this.reducer;
5410 <            if (reducer == null)
5411 <                return abortOnNullFunction();
5412 <            try {
5413 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5602 <                    do {} while (!casPending(c = pending, c+1));
5407 >        public final V getRawResult() { return result; }
5408 >        public final void compute() {
5409 >            final BiFunction<? super V, ? super V, ? extends V> reducer;
5410 >            if ((reducer = this.reducer) != null) {
5411 >                for (int i = baseIndex, f, h; batch > 0 &&
5412 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5413 >                    addToPendingCount(1);
5414                      (rights = new ReduceValuesTask<K,V>
5415 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5415 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5416 >                      rights, reducer)).fork();
5417                  }
5418                  V r = null;
5419 <                Object v;
5420 <                while ((v = advance()) != null) {
5421 <                    V u = (V)v;
5610 <                    r = (r == null) ? u : reducer.apply(r, u);
5419 >                for (Node<K,V> p; (p = advance()) != null; ) {
5420 >                    V v = p.val;
5421 >                    r = (r == null) ? v : reducer.apply(r, v);
5422                  }
5423                  result = r;
5424 <                for (ReduceValuesTask<K,V> t = this, s;;) {
5425 <                    int c; BulkTask<K,V,?> par; V tr, sr;
5426 <                    if ((c = t.pending) == 0) {
5427 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5428 <                            if ((sr = s.result) != null)
5429 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5430 <                        }
5431 <                        if ((par = t.parent) == null ||
5432 <                            !(par instanceof ReduceValuesTask)) {
5433 <                            t.quietlyComplete();
5434 <                            break;
5435 <                        }
5625 <                        t = (ReduceValuesTask<K,V>)par;
5424 >                CountedCompleter<?> c;
5425 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5426 >                    @SuppressWarnings("unchecked")
5427 >                    ReduceValuesTask<K,V>
5428 >                        t = (ReduceValuesTask<K,V>)c,
5429 >                        s = t.rights;
5430 >                    while (s != null) {
5431 >                        V tr, sr;
5432 >                        if ((sr = s.result) != null)
5433 >                            t.result = (((tr = t.result) == null) ? sr :
5434 >                                        reducer.apply(tr, sr));
5435 >                        s = t.rights = s.nextRight;
5436                      }
5627                    else if (t.casPending(c, c - 1))
5628                        break;
5437                  }
5630            } catch (Throwable ex) {
5631                return tryCompleteComputation(ex);
5438              }
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;
5439          }
5642        public final V getRawResult() { return result; }
5440      }
5441  
5442 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5442 >    @SuppressWarnings("serial")
5443 >    static final class ReduceEntriesTask<K,V>
5444          extends BulkTask<K,V,Map.Entry<K,V>> {
5445 <        final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5445 >        final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5446          Map.Entry<K,V> result;
5447          ReduceEntriesTask<K,V> rights, nextRight;
5448          ReduceEntriesTask
5449 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5449 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5450               ReduceEntriesTask<K,V> nextRight,
5451 <             BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5452 <            super(m, p, b); this.nextRight = nextRight;
5451 >             BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5452 >            super(p, b, i, f, t); this.nextRight = nextRight;
5453              this.reducer = reducer;
5454          }
5455 <        @SuppressWarnings("unchecked") public final boolean exec() {
5456 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
5457 <                this.reducer;
5458 <            if (reducer == null)
5459 <                return abortOnNullFunction();
5460 <            try {
5461 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5664 <                    do {} while (!casPending(c = pending, c+1));
5455 >        public final Map.Entry<K,V> getRawResult() { return result; }
5456 >        public final void compute() {
5457 >            final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5458 >            if ((reducer = this.reducer) != null) {
5459 >                for (int i = baseIndex, f, h; batch > 0 &&
5460 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5461 >                    addToPendingCount(1);
5462                      (rights = new ReduceEntriesTask<K,V>
5463 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5463 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5464 >                      rights, reducer)).fork();
5465                  }
5466                  Map.Entry<K,V> r = null;
5467 <                Object v;
5468 <                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 <                }
5467 >                for (Node<K,V> p; (p = advance()) != null; )
5468 >                    r = (r == null) ? p : reducer.apply(r, p);
5469                  result = r;
5470 <                for (ReduceEntriesTask<K,V> t = this, s;;) {
5471 <                    int c; BulkTask<K,V,?> par; Map.Entry<K,V> 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 ReduceEntriesTask)) {
5479 <                            t.quietlyComplete();
5480 <                            break;
5481 <                        }
5687 <                        t = (ReduceEntriesTask<K,V>)par;
5470 >                CountedCompleter<?> c;
5471 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5472 >                    @SuppressWarnings("unchecked")
5473 >                    ReduceEntriesTask<K,V>
5474 >                        t = (ReduceEntriesTask<K,V>)c,
5475 >                        s = t.rights;
5476 >                    while (s != null) {
5477 >                        Map.Entry<K,V> 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                      }
5689                    else if (t.casPending(c, c - 1))
5690                        break;
5483                  }
5692            } catch (Throwable ex) {
5693                return tryCompleteComputation(ex);
5694            }
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);
5484              }
5702            return false;
5485          }
5704        public final Map.Entry<K,V> getRawResult() { return result; }
5486      }
5487  
5488 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5488 >    @SuppressWarnings("serial")
5489 >    static final class MapReduceKeysTask<K,V,U>
5490          extends BulkTask<K,V,U> {
5491 <        final Fun<? super K, ? extends U> transformer;
5492 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5491 >        final Function<? super K, ? extends U> transformer;
5492 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5493          U result;
5494          MapReduceKeysTask<K,V,U> rights, nextRight;
5495          MapReduceKeysTask
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               MapReduceKeysTask<K,V,U> nextRight,
5498 <             Fun<? super K, ? extends U> transformer,
5499 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5500 <            super(m, p, b); this.nextRight = nextRight;
5498 >             Function<? super K, ? 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 K, ? 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;) {
5731 <                    do {} while (!casPending(c = pending, c+1));
5504 >        public final U getRawResult() { return result; }
5505 >        public final void compute() {
5506 >            final Function<? super K, ? 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 MapReduceKeysTask<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 <                while (advance() != null) {
5519 <                    if ((u = transformer.apply((K)nextKey)) != null)
5517 >                U r = null;
5518 >                for (Node<K,V> p; (p = advance()) != null; ) {
5519 >                    U u;
5520 >                    if ((u = transformer.apply(p.key)) != null)
5521                          r = (r == null) ? u : reducer.apply(r, u);
5522                  }
5523                  result = r;
5524 <                for (MapReduceKeysTask<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 MapReduceKeysTask)) {
5533 <                            t.quietlyComplete();
5534 <                            break;
5535 <                        }
5753 <                        t = (MapReduceKeysTask<K,V,U>)par;
5524 >                CountedCompleter<?> c;
5525 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5526 >                    @SuppressWarnings("unchecked")
5527 >                    MapReduceKeysTask<K,V,U>
5528 >                        t = (MapReduceKeysTask<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                      }
5755                    else if (t.casPending(c, c - 1))
5756                        break;
5537                  }
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);
5538              }
5768            return false;
5539          }
5770        public final U getRawResult() { return result; }
5540      }
5541  
5542 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5542 >    @SuppressWarnings("serial")
5543 >    static final class MapReduceValuesTask<K,V,U>
5544          extends BulkTask<K,V,U> {
5545 <        final Fun<? super V, ? extends U> transformer;
5546 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5545 >        final Function<? super V, ? extends U> transformer;
5546 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5547          U result;
5548          MapReduceValuesTask<K,V,U> rights, nextRight;
5549          MapReduceValuesTask
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               MapReduceValuesTask<K,V,U> nextRight,
5552 <             Fun<? super V, ? extends U> transformer,
5553 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5554 <            super(m, p, b); this.nextRight = nextRight;
5552 >             Function<? super 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<? super 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;) {
5797 <                    do {} while (!casPending(c = pending, c+1));
5558 >        public final U getRawResult() { return result; }
5559 >        public final void compute() {
5560 >            final Function<? super 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 MapReduceValuesTask<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((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.val)) != null)
5575                          r = (r == null) ? u : reducer.apply(r, u);
5576                  }
5577                  result = r;
5578 <                for (MapReduceValuesTask<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 MapReduceValuesTask)) {
5587 <                            t.quietlyComplete();
5588 <                            break;
5589 <                        }
5820 <                        t = (MapReduceValuesTask<K,V,U>)par;
5578 >                CountedCompleter<?> c;
5579 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5580 >                    @SuppressWarnings("unchecked")
5581 >                    MapReduceValuesTask<K,V,U>
5582 >                        t = (MapReduceValuesTask<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                      }
5822                    else if (t.casPending(c, c - 1))
5823                        break;
5591                  }
5825            } catch (Throwable ex) {
5826                return tryCompleteComputation(ex);
5827            }
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);
5592              }
5835            return false;
5593          }
5837        public final U getRawResult() { return result; }
5594      }
5595  
5596 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5596 >    @SuppressWarnings("serial")
5597 >    static final class MapReduceEntriesTask<K,V,U>
5598          extends BulkTask<K,V,U> {
5599 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5600 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5599 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5600 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5601          U result;
5602          MapReduceEntriesTask<K,V,U> rights, nextRight;
5603          MapReduceEntriesTask
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               MapReduceEntriesTask<K,V,U> nextRight,
5606 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5607 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5608 <            super(m, p, b); this.nextRight = nextRight;
5606 >             Function<Map.Entry<K,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 Fun<Map.Entry<K,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;) {
5864 <                    do {} while (!casPending(c = pending, c+1));
5612 >        public final U getRawResult() { return result; }
5613 >        public final void compute() {
5614 >            final Function<Map.Entry<K,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 MapReduceEntriesTask<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(entryFor((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)) != null)
5629                          r = (r == null) ? u : reducer.apply(r, u);
5630                  }
5631                  result = r;
5632 <                for (MapReduceEntriesTask<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 MapReduceEntriesTask)) {
5641 <                            t.quietlyComplete();
5642 <                            break;
5643 <                        }
5887 <                        t = (MapReduceEntriesTask<K,V,U>)par;
5632 >                CountedCompleter<?> c;
5633 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5634 >                    @SuppressWarnings("unchecked")
5635 >                    MapReduceEntriesTask<K,V,U>
5636 >                        t = (MapReduceEntriesTask<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                      }
5889                    else if (t.casPending(c, c - 1))
5890                        break;
5645                  }
5892            } catch (Throwable ex) {
5893                return tryCompleteComputation(ex);
5894            }
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);
5646              }
5902            return false;
5647          }
5904        public final U getRawResult() { return result; }
5648      }
5649  
5650 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5650 >    @SuppressWarnings("serial")
5651 >    static final class MapReduceMappingsTask<K,V,U>
5652          extends BulkTask<K,V,U> {
5653 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5654 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5653 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5654 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5655          U result;
5656          MapReduceMappingsTask<K,V,U> rights, nextRight;
5657          MapReduceMappingsTask
5658 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5658 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5659               MapReduceMappingsTask<K,V,U> nextRight,
5660 <             BiFun<? super K, ? super V, ? extends U> transformer,
5661 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5662 <            super(m, p, b); this.nextRight = nextRight;
5660 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5661 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5662 >            super(p, b, i, f, t); this.nextRight = nextRight;
5663              this.transformer = transformer;
5664              this.reducer = reducer;
5665          }
5666 <        @SuppressWarnings("unchecked") public final boolean exec() {
5667 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5668 <                this.transformer;
5669 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5670 <                this.reducer;
5671 <            if (transformer == null || reducer == null)
5672 <                return abortOnNullFunction();
5673 <            try {
5674 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5931 <                    do {} while (!casPending(c = pending, c+1));
5666 >        public final U getRawResult() { return result; }
5667 >        public final void compute() {
5668 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5669 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5670 >            if ((transformer = this.transformer) != null &&
5671 >                (reducer = this.reducer) != null) {
5672 >                for (int i = baseIndex, f, h; batch > 0 &&
5673 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5674 >                    addToPendingCount(1);
5675                      (rights = new MapReduceMappingsTask<K,V,U>
5676 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5676 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5677 >                      rights, transformer, reducer)).fork();
5678                  }
5679 <                U r = null, u;
5680 <                Object v;
5681 <                while ((v = advance()) != null) {
5682 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5679 >                U r = null;
5680 >                for (Node<K,V> p; (p = advance()) != null; ) {
5681 >                    U u;
5682 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5683                          r = (r == null) ? u : reducer.apply(r, u);
5684                  }
5685                  result = r;
5686 <                for (MapReduceMappingsTask<K,V,U> t = this, s;;) {
5687 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5688 <                    if ((c = t.pending) == 0) {
5689 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5690 <                            if ((sr = s.result) != null)
5691 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5692 <                        }
5693 <                        if ((par = t.parent) == null ||
5694 <                            !(par instanceof MapReduceMappingsTask)) {
5695 <                            t.quietlyComplete();
5696 <                            break;
5697 <                        }
5954 <                        t = (MapReduceMappingsTask<K,V,U>)par;
5686 >                CountedCompleter<?> c;
5687 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5688 >                    @SuppressWarnings("unchecked")
5689 >                    MapReduceMappingsTask<K,V,U>
5690 >                        t = (MapReduceMappingsTask<K,V,U>)c,
5691 >                        s = t.rights;
5692 >                    while (s != null) {
5693 >                        U tr, sr;
5694 >                        if ((sr = s.result) != null)
5695 >                            t.result = (((tr = t.result) == null) ? sr :
5696 >                                        reducer.apply(tr, sr));
5697 >                        s = t.rights = s.nextRight;
5698                      }
5956                    else if (t.casPending(c, c - 1))
5957                        break;
5699                  }
5959            } catch (Throwable ex) {
5960                return tryCompleteComputation(ex);
5700              }
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;
5701          }
5971        public final U getRawResult() { return result; }
5702      }
5703  
5704 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5704 >    @SuppressWarnings("serial")
5705 >    static final class MapReduceKeysToDoubleTask<K,V>
5706          extends BulkTask<K,V,Double> {
5707 <        final ObjectToDouble<? super K> transformer;
5708 <        final DoubleByDoubleToDouble reducer;
5707 >        final ToDoubleFunction<? super K> transformer;
5708 >        final DoubleBinaryOperator reducer;
5709          final double basis;
5710          double result;
5711          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5712          MapReduceKeysToDoubleTask
5713 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5713 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5714               MapReduceKeysToDoubleTask<K,V> nextRight,
5715 <             ObjectToDouble<? super K> transformer,
5715 >             ToDoubleFunction<? super K> transformer,
5716               double basis,
5717 <             DoubleByDoubleToDouble reducer) {
5718 <            super(m, p, b); this.nextRight = nextRight;
5717 >             DoubleBinaryOperator reducer) {
5718 >            super(p, b, i, f, t); this.nextRight = nextRight;
5719              this.transformer = transformer;
5720              this.basis = basis; this.reducer = reducer;
5721          }
5722 <        @SuppressWarnings("unchecked") public final boolean exec() {
5723 <            final ObjectToDouble<? super K> transformer =
5724 <                this.transformer;
5725 <            final DoubleByDoubleToDouble reducer = this.reducer;
5726 <            if (transformer == null || reducer == null)
5727 <                return abortOnNullFunction();
5728 <            try {
5729 <                final double id = this.basis;
5730 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5731 <                    do {} while (!casPending(c = pending, c+1));
5722 >        public final Double getRawResult() { return result; }
5723 >        public final void compute() {
5724 >            final ToDoubleFunction<? super K> transformer;
5725 >            final DoubleBinaryOperator reducer;
5726 >            if ((transformer = this.transformer) != null &&
5727 >                (reducer = this.reducer) != null) {
5728 >                double r = this.basis;
5729 >                for (int i = baseIndex, f, h; batch > 0 &&
5730 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5731 >                    addToPendingCount(1);
5732                      (rights = new MapReduceKeysToDoubleTask<K,V>
5733 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5733 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5734 >                      rights, transformer, r, reducer)).fork();
5735                  }
5736 <                double r = id;
5737 <                while (advance() != null)
6006 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5736 >                for (Node<K,V> p; (p = advance()) != null; )
5737 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5738                  result = r;
5739 <                for (MapReduceKeysToDoubleTask<K,V> t = this, s;;) {
5740 <                    int c; BulkTask<K,V,?> par;
5741 <                    if ((c = t.pending) == 0) {
5742 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5743 <                            t.result = reducer.apply(t.result, s.result);
5744 <                        }
5745 <                        if ((par = t.parent) == null ||
5746 <                            !(par instanceof MapReduceKeysToDoubleTask)) {
5747 <                            t.quietlyComplete();
6017 <                            break;
6018 <                        }
6019 <                        t = (MapReduceKeysToDoubleTask<K,V>)par;
5739 >                CountedCompleter<?> c;
5740 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5741 >                    @SuppressWarnings("unchecked")
5742 >                    MapReduceKeysToDoubleTask<K,V>
5743 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
5744 >                        s = t.rights;
5745 >                    while (s != null) {
5746 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5747 >                        s = t.rights = s.nextRight;
5748                      }
6021                    else if (t.casPending(c, c - 1))
6022                        break;
5749                  }
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);
5750              }
6034            return false;
5751          }
6036        public final Double getRawResult() { return result; }
5752      }
5753  
5754 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5754 >    @SuppressWarnings("serial")
5755 >    static final class MapReduceValuesToDoubleTask<K,V>
5756          extends BulkTask<K,V,Double> {
5757 <        final ObjectToDouble<? super V> transformer;
5758 <        final DoubleByDoubleToDouble reducer;
5757 >        final ToDoubleFunction<? super V> transformer;
5758 >        final DoubleBinaryOperator reducer;
5759          final double basis;
5760          double result;
5761          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5762          MapReduceValuesToDoubleTask
5763 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5763 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5764               MapReduceValuesToDoubleTask<K,V> nextRight,
5765 <             ObjectToDouble<? super V> transformer,
5765 >             ToDoubleFunction<? super V> transformer,
5766               double basis,
5767 <             DoubleByDoubleToDouble reducer) {
5768 <            super(m, p, b); this.nextRight = nextRight;
5767 >             DoubleBinaryOperator reducer) {
5768 >            super(p, b, i, f, t); this.nextRight = nextRight;
5769              this.transformer = transformer;
5770              this.basis = basis; this.reducer = reducer;
5771          }
5772 <        @SuppressWarnings("unchecked") public final boolean exec() {
5773 <            final ObjectToDouble<? super V> transformer =
5774 <                this.transformer;
5775 <            final DoubleByDoubleToDouble reducer = this.reducer;
5776 <            if (transformer == null || reducer == null)
5777 <                return abortOnNullFunction();
5778 <            try {
5779 <                final double id = this.basis;
5780 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5781 <                    do {} while (!casPending(c = pending, c+1));
5772 >        public final Double getRawResult() { return result; }
5773 >        public final void compute() {
5774 >            final ToDoubleFunction<? super V> transformer;
5775 >            final DoubleBinaryOperator reducer;
5776 >            if ((transformer = this.transformer) != null &&
5777 >                (reducer = this.reducer) != null) {
5778 >                double r = this.basis;
5779 >                for (int i = baseIndex, f, h; batch > 0 &&
5780 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5781 >                    addToPendingCount(1);
5782                      (rights = new MapReduceValuesToDoubleTask<K,V>
5783 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5783 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5784 >                      rights, transformer, r, reducer)).fork();
5785                  }
5786 <                double r = id;
5787 <                Object v;
6071 <                while ((v = advance()) != null)
6072 <                    r = reducer.apply(r, transformer.apply((V)v));
5786 >                for (Node<K,V> p; (p = advance()) != null; )
5787 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5788                  result = r;
5789 <                for (MapReduceValuesToDoubleTask<K,V> t = this, s;;) {
5790 <                    int c; BulkTask<K,V,?> par;
5791 <                    if ((c = t.pending) == 0) {
5792 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5793 <                            t.result = reducer.apply(t.result, s.result);
5794 <                        }
5795 <                        if ((par = t.parent) == null ||
5796 <                            !(par instanceof MapReduceValuesToDoubleTask)) {
5797 <                            t.quietlyComplete();
6083 <                            break;
6084 <                        }
6085 <                        t = (MapReduceValuesToDoubleTask<K,V>)par;
5789 >                CountedCompleter<?> c;
5790 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5791 >                    @SuppressWarnings("unchecked")
5792 >                    MapReduceValuesToDoubleTask<K,V>
5793 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
5794 >                        s = t.rights;
5795 >                    while (s != null) {
5796 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5797 >                        s = t.rights = s.nextRight;
5798                      }
6087                    else if (t.casPending(c, c - 1))
6088                        break;
5799                  }
6090            } catch (Throwable ex) {
6091                return tryCompleteComputation(ex);
5800              }
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;
5801          }
6102        public final Double getRawResult() { return result; }
5802      }
5803  
5804 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5804 >    @SuppressWarnings("serial")
5805 >    static final class MapReduceEntriesToDoubleTask<K,V>
5806          extends BulkTask<K,V,Double> {
5807 <        final ObjectToDouble<Map.Entry<K,V>> transformer;
5808 <        final DoubleByDoubleToDouble reducer;
5807 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
5808 >        final DoubleBinaryOperator reducer;
5809          final double basis;
5810          double result;
5811          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5812          MapReduceEntriesToDoubleTask
5813 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5813 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5814               MapReduceEntriesToDoubleTask<K,V> nextRight,
5815 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5815 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5816               double basis,
5817 <             DoubleByDoubleToDouble reducer) {
5818 <            super(m, p, b); this.nextRight = nextRight;
5817 >             DoubleBinaryOperator reducer) {
5818 >            super(p, b, i, f, t); this.nextRight = nextRight;
5819              this.transformer = transformer;
5820              this.basis = basis; this.reducer = reducer;
5821          }
5822 <        @SuppressWarnings("unchecked") public final boolean exec() {
5823 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
5824 <                this.transformer;
5825 <            final DoubleByDoubleToDouble reducer = this.reducer;
5826 <            if (transformer == null || reducer == null)
5827 <                return abortOnNullFunction();
5828 <            try {
5829 <                final double id = this.basis;
5830 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5831 <                    do {} while (!casPending(c = pending, c+1));
5822 >        public final Double getRawResult() { return result; }
5823 >        public final void compute() {
5824 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
5825 >            final DoubleBinaryOperator reducer;
5826 >            if ((transformer = this.transformer) != null &&
5827 >                (reducer = this.reducer) != null) {
5828 >                double r = this.basis;
5829 >                for (int i = baseIndex, f, h; batch > 0 &&
5830 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5831 >                    addToPendingCount(1);
5832                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5833 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5833 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5834 >                      rights, transformer, r, reducer)).fork();
5835                  }
5836 <                double r = id;
5837 <                Object v;
6137 <                while ((v = advance()) != null)
6138 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5836 >                for (Node<K,V> p; (p = advance()) != null; )
5837 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5838                  result = r;
5839 <                for (MapReduceEntriesToDoubleTask<K,V> t = this, s;;) {
5840 <                    int c; BulkTask<K,V,?> par;
5841 <                    if ((c = t.pending) == 0) {
5842 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5843 <                            t.result = reducer.apply(t.result, s.result);
5844 <                        }
5845 <                        if ((par = t.parent) == null ||
5846 <                            !(par instanceof MapReduceEntriesToDoubleTask)) {
5847 <                            t.quietlyComplete();
6149 <                            break;
6150 <                        }
6151 <                        t = (MapReduceEntriesToDoubleTask<K,V>)par;
5839 >                CountedCompleter<?> c;
5840 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5841 >                    @SuppressWarnings("unchecked")
5842 >                    MapReduceEntriesToDoubleTask<K,V>
5843 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
5844 >                        s = t.rights;
5845 >                    while (s != null) {
5846 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5847 >                        s = t.rights = s.nextRight;
5848                      }
6153                    else if (t.casPending(c, c - 1))
6154                        break;
5849                  }
6156            } catch (Throwable ex) {
6157                return tryCompleteComputation(ex);
6158            }
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);
5850              }
6166            return false;
5851          }
6168        public final Double getRawResult() { return result; }
5852      }
5853  
5854 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5854 >    @SuppressWarnings("serial")
5855 >    static final class MapReduceMappingsToDoubleTask<K,V>
5856          extends BulkTask<K,V,Double> {
5857 <        final ObjectByObjectToDouble<? super K, ? super V> transformer;
5858 <        final DoubleByDoubleToDouble reducer;
5857 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
5858 >        final DoubleBinaryOperator reducer;
5859          final double basis;
5860          double result;
5861          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5862          MapReduceMappingsToDoubleTask
5863 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5863 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5864               MapReduceMappingsToDoubleTask<K,V> nextRight,
5865 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
5865 >             ToDoubleBiFunction<? super K, ? super V> transformer,
5866               double basis,
5867 <             DoubleByDoubleToDouble reducer) {
5868 <            super(m, p, b); this.nextRight = nextRight;
5867 >             DoubleBinaryOperator reducer) {
5868 >            super(p, b, i, f, t); this.nextRight = nextRight;
5869              this.transformer = transformer;
5870              this.basis = basis; this.reducer = reducer;
5871          }
5872 <        @SuppressWarnings("unchecked") public final boolean exec() {
5873 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
5874 <                this.transformer;
5875 <            final DoubleByDoubleToDouble reducer = this.reducer;
5876 <            if (transformer == null || reducer == null)
5877 <                return abortOnNullFunction();
5878 <            try {
5879 <                final double id = this.basis;
5880 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5881 <                    do {} while (!casPending(c = pending, c+1));
5872 >        public final Double getRawResult() { return result; }
5873 >        public final void compute() {
5874 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
5875 >            final DoubleBinaryOperator reducer;
5876 >            if ((transformer = this.transformer) != null &&
5877 >                (reducer = this.reducer) != null) {
5878 >                double r = this.basis;
5879 >                for (int i = baseIndex, f, h; batch > 0 &&
5880 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5881 >                    addToPendingCount(1);
5882                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5883 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5883 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5884 >                      rights, transformer, r, reducer)).fork();
5885                  }
5886 <                double r = id;
5887 <                Object v;
6203 <                while ((v = advance()) != null)
6204 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5886 >                for (Node<K,V> p; (p = advance()) != null; )
5887 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5888                  result = r;
5889 <                for (MapReduceMappingsToDoubleTask<K,V> t = this, s;;) {
5890 <                    int c; BulkTask<K,V,?> par;
5891 <                    if ((c = t.pending) == 0) {
5892 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5893 <                            t.result = reducer.apply(t.result, s.result);
5894 <                        }
5895 <                        if ((par = t.parent) == null ||
5896 <                            !(par instanceof MapReduceMappingsToDoubleTask)) {
5897 <                            t.quietlyComplete();
6215 <                            break;
6216 <                        }
6217 <                        t = (MapReduceMappingsToDoubleTask<K,V>)par;
5889 >                CountedCompleter<?> c;
5890 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5891 >                    @SuppressWarnings("unchecked")
5892 >                    MapReduceMappingsToDoubleTask<K,V>
5893 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
5894 >                        s = t.rights;
5895 >                    while (s != null) {
5896 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5897 >                        s = t.rights = s.nextRight;
5898                      }
6219                    else if (t.casPending(c, c - 1))
6220                        break;
5899                  }
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);
5900              }
6232            return false;
5901          }
6234        public final Double getRawResult() { return result; }
5902      }
5903  
5904 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5904 >    @SuppressWarnings("serial")
5905 >    static final class MapReduceKeysToLongTask<K,V>
5906          extends BulkTask<K,V,Long> {
5907 <        final ObjectToLong<? super K> transformer;
5908 <        final LongByLongToLong reducer;
5907 >        final ToLongFunction<? super K> transformer;
5908 >        final LongBinaryOperator reducer;
5909          final long basis;
5910          long result;
5911          MapReduceKeysToLongTask<K,V> rights, nextRight;
5912          MapReduceKeysToLongTask
5913 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5913 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5914               MapReduceKeysToLongTask<K,V> nextRight,
5915 <             ObjectToLong<? super K> transformer,
5915 >             ToLongFunction<? super K> transformer,
5916               long basis,
5917 <             LongByLongToLong reducer) {
5918 <            super(m, p, b); this.nextRight = nextRight;
5917 >             LongBinaryOperator reducer) {
5918 >            super(p, b, i, f, t); this.nextRight = nextRight;
5919              this.transformer = transformer;
5920              this.basis = basis; this.reducer = reducer;
5921          }
5922 <        @SuppressWarnings("unchecked") public final boolean exec() {
5923 <            final ObjectToLong<? super K> transformer =
5924 <                this.transformer;
5925 <            final LongByLongToLong reducer = this.reducer;
5926 <            if (transformer == null || reducer == null)
5927 <                return abortOnNullFunction();
5928 <            try {
5929 <                final long id = this.basis;
5930 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5931 <                    do {} while (!casPending(c = pending, c+1));
5922 >        public final Long getRawResult() { return result; }
5923 >        public final void compute() {
5924 >            final ToLongFunction<? super K> transformer;
5925 >            final LongBinaryOperator reducer;
5926 >            if ((transformer = this.transformer) != null &&
5927 >                (reducer = this.reducer) != null) {
5928 >                long r = this.basis;
5929 >                for (int i = baseIndex, f, h; batch > 0 &&
5930 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5931 >                    addToPendingCount(1);
5932                      (rights = new MapReduceKeysToLongTask<K,V>
5933 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5933 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5934 >                      rights, transformer, r, reducer)).fork();
5935                  }
5936 <                long r = id;
5937 <                while (advance() != null)
6269 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5936 >                for (Node<K,V> p; (p = advance()) != null; )
5937 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5938                  result = r;
5939 <                for (MapReduceKeysToLongTask<K,V> t = this, s;;) {
5940 <                    int c; BulkTask<K,V,?> par;
5941 <                    if ((c = t.pending) == 0) {
5942 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5943 <                            t.result = reducer.apply(t.result, s.result);
5944 <                        }
5945 <                        if ((par = t.parent) == null ||
5946 <                            !(par instanceof MapReduceKeysToLongTask)) {
5947 <                            t.quietlyComplete();
6280 <                            break;
6281 <                        }
6282 <                        t = (MapReduceKeysToLongTask<K,V>)par;
5939 >                CountedCompleter<?> c;
5940 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5941 >                    @SuppressWarnings("unchecked")
5942 >                    MapReduceKeysToLongTask<K,V>
5943 >                        t = (MapReduceKeysToLongTask<K,V>)c,
5944 >                        s = t.rights;
5945 >                    while (s != null) {
5946 >                        t.result = reducer.applyAsLong(t.result, s.result);
5947 >                        s = t.rights = s.nextRight;
5948                      }
6284                    else if (t.casPending(c, c - 1))
6285                        break;
5949                  }
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);
5950              }
6297            return false;
5951          }
6299        public final Long getRawResult() { return result; }
5952      }
5953  
5954 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5954 >    @SuppressWarnings("serial")
5955 >    static final class MapReduceValuesToLongTask<K,V>
5956          extends BulkTask<K,V,Long> {
5957 <        final ObjectToLong<? super V> transformer;
5958 <        final LongByLongToLong reducer;
5957 >        final ToLongFunction<? super V> transformer;
5958 >        final LongBinaryOperator reducer;
5959          final long basis;
5960          long result;
5961          MapReduceValuesToLongTask<K,V> rights, nextRight;
5962          MapReduceValuesToLongTask
5963 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5963 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5964               MapReduceValuesToLongTask<K,V> nextRight,
5965 <             ObjectToLong<? super V> transformer,
5965 >             ToLongFunction<? super V> transformer,
5966               long basis,
5967 <             LongByLongToLong reducer) {
5968 <            super(m, p, b); this.nextRight = nextRight;
5967 >             LongBinaryOperator reducer) {
5968 >            super(p, b, i, f, t); this.nextRight = nextRight;
5969              this.transformer = transformer;
5970              this.basis = basis; this.reducer = reducer;
5971          }
5972 <        @SuppressWarnings("unchecked") public final boolean exec() {
5973 <            final ObjectToLong<? super V> transformer =
5974 <                this.transformer;
5975 <            final LongByLongToLong reducer = this.reducer;
5976 <            if (transformer == null || reducer == null)
5977 <                return abortOnNullFunction();
5978 <            try {
5979 <                final long id = this.basis;
5980 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5981 <                    do {} while (!casPending(c = pending, c+1));
5972 >        public final Long getRawResult() { return result; }
5973 >        public final void compute() {
5974 >            final ToLongFunction<? super V> transformer;
5975 >            final LongBinaryOperator reducer;
5976 >            if ((transformer = this.transformer) != null &&
5977 >                (reducer = this.reducer) != null) {
5978 >                long r = this.basis;
5979 >                for (int i = baseIndex, f, h; batch > 0 &&
5980 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5981 >                    addToPendingCount(1);
5982                      (rights = new MapReduceValuesToLongTask<K,V>
5983 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5983 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5984 >                      rights, transformer, r, reducer)).fork();
5985                  }
5986 <                long r = id;
5987 <                Object v;
6334 <                while ((v = advance()) != null)
6335 <                    r = reducer.apply(r, transformer.apply((V)v));
5986 >                for (Node<K,V> p; (p = advance()) != null; )
5987 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5988                  result = r;
5989 <                for (MapReduceValuesToLongTask<K,V> t = this, s;;) {
5990 <                    int c; BulkTask<K,V,?> par;
5991 <                    if ((c = t.pending) == 0) {
5992 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5993 <                            t.result = reducer.apply(t.result, s.result);
5994 <                        }
5995 <                        if ((par = t.parent) == null ||
5996 <                            !(par instanceof MapReduceValuesToLongTask)) {
5997 <                            t.quietlyComplete();
6346 <                            break;
6347 <                        }
6348 <                        t = (MapReduceValuesToLongTask<K,V>)par;
5989 >                CountedCompleter<?> c;
5990 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5991 >                    @SuppressWarnings("unchecked")
5992 >                    MapReduceValuesToLongTask<K,V>
5993 >                        t = (MapReduceValuesToLongTask<K,V>)c,
5994 >                        s = t.rights;
5995 >                    while (s != null) {
5996 >                        t.result = reducer.applyAsLong(t.result, s.result);
5997 >                        s = t.rights = s.nextRight;
5998                      }
6350                    else if (t.casPending(c, c - 1))
6351                        break;
5999                  }
6353            } catch (Throwable ex) {
6354                return tryCompleteComputation(ex);
6355            }
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);
6000              }
6363            return false;
6001          }
6365        public final Long getRawResult() { return result; }
6002      }
6003  
6004 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6004 >    @SuppressWarnings("serial")
6005 >    static final class MapReduceEntriesToLongTask<K,V>
6006          extends BulkTask<K,V,Long> {
6007 <        final ObjectToLong<Map.Entry<K,V>> transformer;
6008 <        final LongByLongToLong reducer;
6007 >        final ToLongFunction<Map.Entry<K,V>> transformer;
6008 >        final LongBinaryOperator reducer;
6009          final long basis;
6010          long result;
6011          MapReduceEntriesToLongTask<K,V> rights, nextRight;
6012          MapReduceEntriesToLongTask
6013 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6013 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6014               MapReduceEntriesToLongTask<K,V> nextRight,
6015 <             ObjectToLong<Map.Entry<K,V>> transformer,
6015 >             ToLongFunction<Map.Entry<K,V>> transformer,
6016               long basis,
6017 <             LongByLongToLong reducer) {
6018 <            super(m, p, b); this.nextRight = nextRight;
6017 >             LongBinaryOperator reducer) {
6018 >            super(p, b, i, f, t); this.nextRight = nextRight;
6019              this.transformer = transformer;
6020              this.basis = basis; this.reducer = reducer;
6021          }
6022 <        @SuppressWarnings("unchecked") public final boolean exec() {
6023 <            final ObjectToLong<Map.Entry<K,V>> transformer =
6024 <                this.transformer;
6025 <            final LongByLongToLong reducer = this.reducer;
6026 <            if (transformer == null || reducer == null)
6027 <                return abortOnNullFunction();
6028 <            try {
6029 <                final long id = this.basis;
6030 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6031 <                    do {} while (!casPending(c = pending, c+1));
6022 >        public final Long getRawResult() { return result; }
6023 >        public final void compute() {
6024 >            final ToLongFunction<Map.Entry<K,V>> transformer;
6025 >            final LongBinaryOperator reducer;
6026 >            if ((transformer = this.transformer) != null &&
6027 >                (reducer = this.reducer) != null) {
6028 >                long r = this.basis;
6029 >                for (int i = baseIndex, f, h; batch > 0 &&
6030 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6031 >                    addToPendingCount(1);
6032                      (rights = new MapReduceEntriesToLongTask<K,V>
6033 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6033 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6034 >                      rights, transformer, r, reducer)).fork();
6035                  }
6036 <                long r = id;
6037 <                Object v;
6400 <                while ((v = advance()) != null)
6401 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6036 >                for (Node<K,V> p; (p = advance()) != null; )
6037 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
6038                  result = r;
6039 <                for (MapReduceEntriesToLongTask<K,V> t = this, s;;) {
6040 <                    int c; BulkTask<K,V,?> par;
6041 <                    if ((c = t.pending) == 0) {
6042 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6043 <                            t.result = reducer.apply(t.result, s.result);
6044 <                        }
6045 <                        if ((par = t.parent) == null ||
6046 <                            !(par instanceof MapReduceEntriesToLongTask)) {
6047 <                            t.quietlyComplete();
6412 <                            break;
6413 <                        }
6414 <                        t = (MapReduceEntriesToLongTask<K,V>)par;
6039 >                CountedCompleter<?> c;
6040 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6041 >                    @SuppressWarnings("unchecked")
6042 >                    MapReduceEntriesToLongTask<K,V>
6043 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
6044 >                        s = t.rights;
6045 >                    while (s != null) {
6046 >                        t.result = reducer.applyAsLong(t.result, s.result);
6047 >                        s = t.rights = s.nextRight;
6048                      }
6416                    else if (t.casPending(c, c - 1))
6417                        break;
6049                  }
6419            } catch (Throwable ex) {
6420                return tryCompleteComputation(ex);
6050              }
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;
6051          }
6431        public final Long getRawResult() { return result; }
6052      }
6053  
6054 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6054 >    @SuppressWarnings("serial")
6055 >    static final class MapReduceMappingsToLongTask<K,V>
6056          extends BulkTask<K,V,Long> {
6057 <        final ObjectByObjectToLong<? super K, ? super V> transformer;
6058 <        final LongByLongToLong reducer;
6057 >        final ToLongBiFunction<? super K, ? super V> transformer;
6058 >        final LongBinaryOperator reducer;
6059          final long basis;
6060          long result;
6061          MapReduceMappingsToLongTask<K,V> rights, nextRight;
6062          MapReduceMappingsToLongTask
6063 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6063 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6064               MapReduceMappingsToLongTask<K,V> nextRight,
6065 <             ObjectByObjectToLong<? super K, ? super V> transformer,
6065 >             ToLongBiFunction<? super K, ? super V> transformer,
6066               long basis,
6067 <             LongByLongToLong reducer) {
6068 <            super(m, p, b); this.nextRight = nextRight;
6067 >             LongBinaryOperator reducer) {
6068 >            super(p, b, i, f, t); this.nextRight = nextRight;
6069              this.transformer = transformer;
6070              this.basis = basis; this.reducer = reducer;
6071          }
6072 <        @SuppressWarnings("unchecked") public final boolean exec() {
6073 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
6074 <                this.transformer;
6075 <            final LongByLongToLong reducer = this.reducer;
6076 <            if (transformer == null || reducer == null)
6077 <                return abortOnNullFunction();
6078 <            try {
6079 <                final long id = this.basis;
6080 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6081 <                    do {} while (!casPending(c = pending, c+1));
6072 >        public final Long getRawResult() { return result; }
6073 >        public final void compute() {
6074 >            final ToLongBiFunction<? super K, ? super V> transformer;
6075 >            final LongBinaryOperator reducer;
6076 >            if ((transformer = this.transformer) != null &&
6077 >                (reducer = this.reducer) != null) {
6078 >                long r = this.basis;
6079 >                for (int i = baseIndex, f, h; batch > 0 &&
6080 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6081 >                    addToPendingCount(1);
6082                      (rights = new MapReduceMappingsToLongTask<K,V>
6083 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6083 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6084 >                      rights, transformer, r, reducer)).fork();
6085                  }
6086 <                long r = id;
6087 <                Object v;
6466 <                while ((v = advance()) != null)
6467 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6086 >                for (Node<K,V> p; (p = advance()) != null; )
6087 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
6088                  result = r;
6089 <                for (MapReduceMappingsToLongTask<K,V> t = this, s;;) {
6090 <                    int c; BulkTask<K,V,?> par;
6091 <                    if ((c = t.pending) == 0) {
6092 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6093 <                            t.result = reducer.apply(t.result, s.result);
6094 <                        }
6095 <                        if ((par = t.parent) == null ||
6096 <                            !(par instanceof MapReduceMappingsToLongTask)) {
6097 <                            t.quietlyComplete();
6478 <                            break;
6479 <                        }
6480 <                        t = (MapReduceMappingsToLongTask<K,V>)par;
6089 >                CountedCompleter<?> c;
6090 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6091 >                    @SuppressWarnings("unchecked")
6092 >                    MapReduceMappingsToLongTask<K,V>
6093 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
6094 >                        s = t.rights;
6095 >                    while (s != null) {
6096 >                        t.result = reducer.applyAsLong(t.result, s.result);
6097 >                        s = t.rights = s.nextRight;
6098                      }
6482                    else if (t.casPending(c, c - 1))
6483                        break;
6099                  }
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);
6100              }
6495            return false;
6101          }
6497        public final Long getRawResult() { return result; }
6102      }
6103  
6104 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6104 >    @SuppressWarnings("serial")
6105 >    static final class MapReduceKeysToIntTask<K,V>
6106          extends BulkTask<K,V,Integer> {
6107 <        final ObjectToInt<? super K> transformer;
6108 <        final IntByIntToInt reducer;
6107 >        final ToIntFunction<? super K> transformer;
6108 >        final IntBinaryOperator reducer;
6109          final int basis;
6110          int result;
6111          MapReduceKeysToIntTask<K,V> rights, nextRight;
6112          MapReduceKeysToIntTask
6113 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6113 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6114               MapReduceKeysToIntTask<K,V> nextRight,
6115 <             ObjectToInt<? super K> transformer,
6115 >             ToIntFunction<? super K> transformer,
6116               int basis,
6117 <             IntByIntToInt reducer) {
6118 <            super(m, p, b); this.nextRight = nextRight;
6117 >             IntBinaryOperator reducer) {
6118 >            super(p, b, i, f, t); this.nextRight = nextRight;
6119              this.transformer = transformer;
6120              this.basis = basis; this.reducer = reducer;
6121          }
6122 <        @SuppressWarnings("unchecked") public final boolean exec() {
6123 <            final ObjectToInt<? super K> transformer =
6124 <                this.transformer;
6125 <            final IntByIntToInt reducer = this.reducer;
6126 <            if (transformer == null || reducer == null)
6127 <                return abortOnNullFunction();
6128 <            try {
6129 <                final int id = this.basis;
6130 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6131 <                    do {} while (!casPending(c = pending, c+1));
6122 >        public final Integer getRawResult() { return result; }
6123 >        public final void compute() {
6124 >            final ToIntFunction<? super K> transformer;
6125 >            final IntBinaryOperator reducer;
6126 >            if ((transformer = this.transformer) != null &&
6127 >                (reducer = this.reducer) != null) {
6128 >                int r = this.basis;
6129 >                for (int i = baseIndex, f, h; batch > 0 &&
6130 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6131 >                    addToPendingCount(1);
6132                      (rights = new MapReduceKeysToIntTask<K,V>
6133 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6133 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6134 >                      rights, transformer, r, reducer)).fork();
6135                  }
6136 <                int r = id;
6137 <                while (advance() != null)
6532 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
6136 >                for (Node<K,V> p; (p = advance()) != null; )
6137 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
6138                  result = r;
6139 <                for (MapReduceKeysToIntTask<K,V> t = this, s;;) {
6140 <                    int c; BulkTask<K,V,?> par;
6141 <                    if ((c = t.pending) == 0) {
6142 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6143 <                            t.result = reducer.apply(t.result, s.result);
6144 <                        }
6145 <                        if ((par = t.parent) == null ||
6146 <                            !(par instanceof MapReduceKeysToIntTask)) {
6147 <                            t.quietlyComplete();
6543 <                            break;
6544 <                        }
6545 <                        t = (MapReduceKeysToIntTask<K,V>)par;
6139 >                CountedCompleter<?> c;
6140 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6141 >                    @SuppressWarnings("unchecked")
6142 >                    MapReduceKeysToIntTask<K,V>
6143 >                        t = (MapReduceKeysToIntTask<K,V>)c,
6144 >                        s = t.rights;
6145 >                    while (s != null) {
6146 >                        t.result = reducer.applyAsInt(t.result, s.result);
6147 >                        s = t.rights = s.nextRight;
6148                      }
6547                    else if (t.casPending(c, c - 1))
6548                        break;
6149                  }
6550            } catch (Throwable ex) {
6551                return tryCompleteComputation(ex);
6150              }
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);
6559            }
6560            return false;
6151          }
6562        public final Integer getRawResult() { return result; }
6152      }
6153  
6154 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6154 >    @SuppressWarnings("serial")
6155 >    static final class MapReduceValuesToIntTask<K,V>
6156          extends BulkTask<K,V,Integer> {
6157 <        final ObjectToInt<? super V> transformer;
6158 <        final IntByIntToInt reducer;
6157 >        final ToIntFunction<? super V> transformer;
6158 >        final IntBinaryOperator reducer;
6159          final int basis;
6160          int result;
6161          MapReduceValuesToIntTask<K,V> rights, nextRight;
6162          MapReduceValuesToIntTask
6163 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6163 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6164               MapReduceValuesToIntTask<K,V> nextRight,
6165 <             ObjectToInt<? super V> transformer,
6165 >             ToIntFunction<? super V> transformer,
6166               int basis,
6167 <             IntByIntToInt reducer) {
6168 <            super(m, p, b); this.nextRight = nextRight;
6167 >             IntBinaryOperator reducer) {
6168 >            super(p, b, i, f, t); this.nextRight = nextRight;
6169              this.transformer = transformer;
6170              this.basis = basis; this.reducer = reducer;
6171          }
6172 <        @SuppressWarnings("unchecked") public final boolean exec() {
6173 <            final ObjectToInt<? super V> transformer =
6174 <                this.transformer;
6175 <            final IntByIntToInt reducer = this.reducer;
6176 <            if (transformer == null || reducer == null)
6177 <                return abortOnNullFunction();
6178 <            try {
6179 <                final int id = this.basis;
6180 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6181 <                    do {} while (!casPending(c = pending, c+1));
6172 >        public final Integer getRawResult() { return result; }
6173 >        public final void compute() {
6174 >            final ToIntFunction<? super V> transformer;
6175 >            final IntBinaryOperator reducer;
6176 >            if ((transformer = this.transformer) != null &&
6177 >                (reducer = this.reducer) != null) {
6178 >                int r = this.basis;
6179 >                for (int i = baseIndex, f, h; batch > 0 &&
6180 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6181 >                    addToPendingCount(1);
6182                      (rights = new MapReduceValuesToIntTask<K,V>
6183 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6183 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6184 >                      rights, transformer, r, reducer)).fork();
6185                  }
6186 <                int r = id;
6187 <                Object v;
6597 <                while ((v = advance()) != null)
6598 <                    r = reducer.apply(r, transformer.apply((V)v));
6186 >                for (Node<K,V> p; (p = advance()) != null; )
6187 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
6188                  result = r;
6189 <                for (MapReduceValuesToIntTask<K,V> t = this, s;;) {
6190 <                    int c; BulkTask<K,V,?> par;
6191 <                    if ((c = t.pending) == 0) {
6192 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6193 <                            t.result = reducer.apply(t.result, s.result);
6194 <                        }
6195 <                        if ((par = t.parent) == null ||
6196 <                            !(par instanceof MapReduceValuesToIntTask)) {
6197 <                            t.quietlyComplete();
6609 <                            break;
6610 <                        }
6611 <                        t = (MapReduceValuesToIntTask<K,V>)par;
6189 >                CountedCompleter<?> c;
6190 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6191 >                    @SuppressWarnings("unchecked")
6192 >                    MapReduceValuesToIntTask<K,V>
6193 >                        t = (MapReduceValuesToIntTask<K,V>)c,
6194 >                        s = t.rights;
6195 >                    while (s != null) {
6196 >                        t.result = reducer.applyAsInt(t.result, s.result);
6197 >                        s = t.rights = s.nextRight;
6198                      }
6613                    else if (t.casPending(c, c - 1))
6614                        break;
6199                  }
6616            } catch (Throwable ex) {
6617                return tryCompleteComputation(ex);
6618            }
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);
6200              }
6626            return false;
6201          }
6628        public final Integer getRawResult() { return result; }
6202      }
6203  
6204 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6204 >    @SuppressWarnings("serial")
6205 >    static final class MapReduceEntriesToIntTask<K,V>
6206          extends BulkTask<K,V,Integer> {
6207 <        final ObjectToInt<Map.Entry<K,V>> transformer;
6208 <        final IntByIntToInt reducer;
6207 >        final ToIntFunction<Map.Entry<K,V>> transformer;
6208 >        final IntBinaryOperator reducer;
6209          final int basis;
6210          int result;
6211          MapReduceEntriesToIntTask<K,V> rights, nextRight;
6212          MapReduceEntriesToIntTask
6213 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6213 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6214               MapReduceEntriesToIntTask<K,V> nextRight,
6215 <             ObjectToInt<Map.Entry<K,V>> transformer,
6215 >             ToIntFunction<Map.Entry<K,V>> transformer,
6216               int basis,
6217 <             IntByIntToInt reducer) {
6218 <            super(m, p, b); this.nextRight = nextRight;
6217 >             IntBinaryOperator reducer) {
6218 >            super(p, b, i, f, t); this.nextRight = nextRight;
6219              this.transformer = transformer;
6220              this.basis = basis; this.reducer = reducer;
6221          }
6222 <        @SuppressWarnings("unchecked") public final boolean exec() {
6223 <            final ObjectToInt<Map.Entry<K,V>> transformer =
6224 <                this.transformer;
6225 <            final IntByIntToInt reducer = this.reducer;
6226 <            if (transformer == null || reducer == null)
6227 <                return abortOnNullFunction();
6228 <            try {
6229 <                final int id = this.basis;
6230 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6231 <                    do {} while (!casPending(c = pending, c+1));
6222 >        public final Integer getRawResult() { return result; }
6223 >        public final void compute() {
6224 >            final ToIntFunction<Map.Entry<K,V>> transformer;
6225 >            final IntBinaryOperator reducer;
6226 >            if ((transformer = this.transformer) != null &&
6227 >                (reducer = this.reducer) != null) {
6228 >                int r = this.basis;
6229 >                for (int i = baseIndex, f, h; batch > 0 &&
6230 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6231 >                    addToPendingCount(1);
6232                      (rights = new MapReduceEntriesToIntTask<K,V>
6233 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6233 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6234 >                      rights, transformer, r, reducer)).fork();
6235                  }
6236 <                int r = id;
6237 <                Object v;
6663 <                while ((v = advance()) != null)
6664 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6236 >                for (Node<K,V> p; (p = advance()) != null; )
6237 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
6238                  result = r;
6239 <                for (MapReduceEntriesToIntTask<K,V> t = this, s;;) {
6240 <                    int c; BulkTask<K,V,?> par;
6241 <                    if ((c = t.pending) == 0) {
6242 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6243 <                            t.result = reducer.apply(t.result, s.result);
6244 <                        }
6245 <                        if ((par = t.parent) == null ||
6246 <                            !(par instanceof MapReduceEntriesToIntTask)) {
6247 <                            t.quietlyComplete();
6675 <                            break;
6676 <                        }
6677 <                        t = (MapReduceEntriesToIntTask<K,V>)par;
6239 >                CountedCompleter<?> c;
6240 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6241 >                    @SuppressWarnings("unchecked")
6242 >                    MapReduceEntriesToIntTask<K,V>
6243 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
6244 >                        s = t.rights;
6245 >                    while (s != null) {
6246 >                        t.result = reducer.applyAsInt(t.result, s.result);
6247 >                        s = t.rights = s.nextRight;
6248                      }
6679                    else if (t.casPending(c, c - 1))
6680                        break;
6249                  }
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);
6250              }
6692            return false;
6251          }
6694        public final Integer getRawResult() { return result; }
6252      }
6253  
6254 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6254 >    @SuppressWarnings("serial")
6255 >    static final class MapReduceMappingsToIntTask<K,V>
6256          extends BulkTask<K,V,Integer> {
6257 <        final ObjectByObjectToInt<? super K, ? super V> transformer;
6258 <        final IntByIntToInt reducer;
6257 >        final ToIntBiFunction<? super K, ? super V> transformer;
6258 >        final IntBinaryOperator reducer;
6259          final int basis;
6260          int result;
6261          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6262          MapReduceMappingsToIntTask
6263 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6264 <             MapReduceMappingsToIntTask<K,V> rights,
6265 <             ObjectByObjectToInt<? super K, ? super V> transformer,
6263 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6264 >             MapReduceMappingsToIntTask<K,V> nextRight,
6265 >             ToIntBiFunction<? super K, ? super V> transformer,
6266               int basis,
6267 <             IntByIntToInt reducer) {
6268 <            super(m, p, b); this.nextRight = nextRight;
6267 >             IntBinaryOperator reducer) {
6268 >            super(p, b, i, f, t); this.nextRight = nextRight;
6269              this.transformer = transformer;
6270              this.basis = basis; this.reducer = reducer;
6271          }
6272 <        @SuppressWarnings("unchecked") public final boolean exec() {
6273 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
6274 <                this.transformer;
6275 <            final IntByIntToInt reducer = this.reducer;
6276 <            if (transformer == null || reducer == null)
6277 <                return abortOnNullFunction();
6278 <            try {
6279 <                final int id = this.basis;
6280 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6281 <                    do {} while (!casPending(c = pending, c+1));
6272 >        public final Integer getRawResult() { return result; }
6273 >        public final void compute() {
6274 >            final ToIntBiFunction<? super K, ? super V> transformer;
6275 >            final IntBinaryOperator reducer;
6276 >            if ((transformer = this.transformer) != null &&
6277 >                (reducer = this.reducer) != null) {
6278 >                int r = this.basis;
6279 >                for (int i = baseIndex, f, h; batch > 0 &&
6280 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6281 >                    addToPendingCount(1);
6282                      (rights = new MapReduceMappingsToIntTask<K,V>
6283 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6283 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6284 >                      rights, transformer, r, reducer)).fork();
6285                  }
6286 <                int r = id;
6287 <                Object v;
6729 <                while ((v = advance()) != null)
6730 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6286 >                for (Node<K,V> p; (p = advance()) != null; )
6287 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6288                  result = r;
6289 <                for (MapReduceMappingsToIntTask<K,V> t = this, s;;) {
6290 <                    int c; BulkTask<K,V,?> par;
6291 <                    if ((c = t.pending) == 0) {
6292 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6293 <                            t.result = reducer.apply(t.result, s.result);
6294 <                        }
6295 <                        if ((par = t.parent) == null ||
6296 <                            !(par instanceof MapReduceMappingsToIntTask)) {
6297 <                            t.quietlyComplete();
6741 <                            break;
6742 <                        }
6743 <                        t = (MapReduceMappingsToIntTask<K,V>)par;
6289 >                CountedCompleter<?> c;
6290 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6291 >                    @SuppressWarnings("unchecked")
6292 >                    MapReduceMappingsToIntTask<K,V>
6293 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6294 >                        s = t.rights;
6295 >                    while (s != null) {
6296 >                        t.result = reducer.applyAsInt(t.result, s.result);
6297 >                        s = t.rights = s.nextRight;
6298                      }
6745                    else if (t.casPending(c, c - 1))
6746                        break;
6299                  }
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);
6300              }
6758            return false;
6301          }
6760        public final Integer getRawResult() { return result; }
6302      }
6303  
6304      // Unsafe mechanics
6305 <    private static final sun.misc.Unsafe UNSAFE;
6306 <    private static final long counterOffset;
6307 <    private static final long sizeCtlOffset;
6308 <    private static final long ABASE;
6305 >    private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
6306 >    private static final long SIZECTL;
6307 >    private static final long TRANSFERINDEX;
6308 >    private static final long BASECOUNT;
6309 >    private static final long CELLSBUSY;
6310 >    private static final long CELLVALUE;
6311 >    private static final int ABASE;
6312      private static final int ASHIFT;
6313  
6314      static {
6771        int ss;
6315          try {
6316 <            UNSAFE = sun.misc.Unsafe.getUnsafe();
6317 <            Class<?> k = ConcurrentHashMap.class;
6318 <            counterOffset = UNSAFE.objectFieldOffset
6319 <                (k.getDeclaredField("counter"));
6320 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6321 <                (k.getDeclaredField("sizeCtl"));
6322 <            Class<?> sc = Node[].class;
6323 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6324 <            ss = UNSAFE.arrayIndexScale(sc);
6325 <        } catch (Exception e) {
6316 >            SIZECTL = U.objectFieldOffset
6317 >                (ConcurrentHashMap.class.getDeclaredField("sizeCtl"));
6318 >            TRANSFERINDEX = U.objectFieldOffset
6319 >                (ConcurrentHashMap.class.getDeclaredField("transferIndex"));
6320 >            BASECOUNT = U.objectFieldOffset
6321 >                (ConcurrentHashMap.class.getDeclaredField("baseCount"));
6322 >            CELLSBUSY = U.objectFieldOffset
6323 >                (ConcurrentHashMap.class.getDeclaredField("cellsBusy"));
6324 >
6325 >            CELLVALUE = U.objectFieldOffset
6326 >                (CounterCell.class.getDeclaredField("value"));
6327 >
6328 >            ABASE = U.arrayBaseOffset(Node[].class);
6329 >            int scale = U.arrayIndexScale(Node[].class);
6330 >            if ((scale & (scale - 1)) != 0)
6331 >                throw new Error("array index scale not a power of two");
6332 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6333 >        } catch (ReflectiveOperationException e) {
6334              throw new Error(e);
6335          }
6336 <        if ((ss & (ss-1)) != 0)
6337 <            throw new Error("data type scale not a power of two");
6338 <        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6336 >
6337 >        // Reduce the risk of rare disastrous classloading in first call to
6338 >        // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
6339 >        Class<?> ensureLoaded = LockSupport.class;
6340      }
6341   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines