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