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