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.lang.invoke.MethodHandles; |
10 |
import java.lang.invoke.VarHandle; |
11 |
import java.io.Serializable; |
12 |
import java.util.AbstractCollection; |
13 |
import java.util.AbstractMap; |
14 |
import java.util.AbstractSet; |
15 |
import java.util.ArrayList; |
16 |
import java.util.Collection; |
17 |
import java.util.Collections; |
18 |
import java.util.Comparator; |
19 |
import java.util.Iterator; |
20 |
import java.util.List; |
21 |
import java.util.Map; |
22 |
import java.util.NavigableSet; |
23 |
import java.util.NoSuchElementException; |
24 |
import java.util.Set; |
25 |
import java.util.SortedMap; |
26 |
import java.util.Spliterator; |
27 |
import java.util.function.BiConsumer; |
28 |
import java.util.function.BiFunction; |
29 |
import java.util.function.Consumer; |
30 |
import java.util.function.Function; |
31 |
import java.util.function.Predicate; |
32 |
import java.util.concurrent.atomic.LongAdder; |
33 |
|
34 |
/** |
35 |
* A scalable concurrent {@link ConcurrentNavigableMap} implementation. |
36 |
* The map is sorted according to the {@linkplain Comparable natural |
37 |
* ordering} of its keys, or by a {@link Comparator} provided at map |
38 |
* creation time, depending on which constructor is used. |
39 |
* |
40 |
* <p>This class implements a concurrent variant of <a |
41 |
* href="http://en.wikipedia.org/wiki/Skip_list" target="_top">SkipLists</a> |
42 |
* providing expected average <i>log(n)</i> time cost for the |
43 |
* {@code containsKey}, {@code get}, {@code put} and |
44 |
* {@code remove} operations and their variants. Insertion, removal, |
45 |
* update, and access operations safely execute concurrently by |
46 |
* multiple threads. |
47 |
* |
48 |
* <p>Iterators and spliterators are |
49 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
50 |
* |
51 |
* <p>Ascending key ordered views and their iterators are faster than |
52 |
* descending ones. |
53 |
* |
54 |
* <p>All {@code Map.Entry} pairs returned by methods in this class |
55 |
* and its views represent snapshots of mappings at the time they were |
56 |
* produced. They do <em>not</em> support the {@code Entry.setValue} |
57 |
* method. (Note however that it is possible to change mappings in the |
58 |
* associated map using {@code put}, {@code putIfAbsent}, or |
59 |
* {@code replace}, depending on exactly which effect you need.) |
60 |
* |
61 |
* <p>Beware that bulk operations {@code putAll}, {@code equals}, |
62 |
* {@code toArray}, {@code containsValue}, and {@code clear} are |
63 |
* <em>not</em> guaranteed to be performed atomically. For example, an |
64 |
* iterator operating concurrently with a {@code putAll} operation |
65 |
* might view only some of the added elements. |
66 |
* |
67 |
* <p>This class and its views and iterators implement all of the |
68 |
* <em>optional</em> methods of the {@link Map} and {@link Iterator} |
69 |
* interfaces. Like most other concurrent collections, this class does |
70 |
* <em>not</em> permit the use of {@code null} keys or values because some |
71 |
* null return values cannot be reliably distinguished from the absence of |
72 |
* elements. |
73 |
* |
74 |
* <p>This class is a member of the |
75 |
* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework"> |
76 |
* Java Collections Framework</a>. |
77 |
* |
78 |
* @author Doug Lea |
79 |
* @param <K> the type of keys maintained by this map |
80 |
* @param <V> the type of mapped values |
81 |
* @since 1.6 |
82 |
*/ |
83 |
public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V> |
84 |
implements ConcurrentNavigableMap<K,V>, Cloneable, Serializable { |
85 |
/* |
86 |
* This class implements a tree-like two-dimensionally linked skip |
87 |
* list in which the index levels are represented in separate |
88 |
* nodes from the base nodes holding data. There are two reasons |
89 |
* for taking this approach instead of the usual array-based |
90 |
* structure: 1) Array based implementations seem to encounter |
91 |
* more complexity and overhead 2) We can use cheaper algorithms |
92 |
* for the heavily-traversed index lists than can be used for the |
93 |
* base lists. Here's a picture of some of the basics for a |
94 |
* possible list with 2 levels of index: |
95 |
* |
96 |
* Head nodes Index nodes |
97 |
* +-+ right +-+ +-+ |
98 |
* |2|---------------->| |--------------------->| |->null |
99 |
* +-+ +-+ +-+ |
100 |
* | down | | |
101 |
* v v v |
102 |
* +-+ +-+ +-+ +-+ +-+ +-+ |
103 |
* |1|----------->| |->| |------>| |----------->| |------>| |->null |
104 |
* +-+ +-+ +-+ +-+ +-+ +-+ |
105 |
* v | | | | | |
106 |
* Nodes next v v v v v |
107 |
* +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ |
108 |
* | |->|A|->|B|->|C|->|D|->|E|->|F|->|G|->|H|->|I|->|J|->|K|->null |
109 |
* +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ |
110 |
* |
111 |
* The base lists use a variant of the HM linked ordered set |
112 |
* algorithm. See Tim Harris, "A pragmatic implementation of |
113 |
* non-blocking linked lists" |
114 |
* http://www.cl.cam.ac.uk/~tlh20/publications.html and Maged |
115 |
* Michael "High Performance Dynamic Lock-Free Hash Tables and |
116 |
* List-Based Sets" |
117 |
* http://www.research.ibm.com/people/m/michael/pubs.htm. The |
118 |
* basic idea in these lists is to mark the "next" pointers of |
119 |
* deleted nodes when deleting to avoid conflicts with concurrent |
120 |
* insertions, and when traversing to keep track of triples |
121 |
* (predecessor, node, successor) in order to detect when and how |
122 |
* to unlink these deleted nodes. |
123 |
* |
124 |
* Rather than using mark-bits to mark list deletions (which can |
125 |
* be slow and space-intensive using AtomicMarkedReference), nodes |
126 |
* use direct CAS'able next pointers. On deletion, instead of |
127 |
* marking a pointer, they splice in another node that can be |
128 |
* thought of as standing for a marked pointer (see method |
129 |
* unlinkNode). Using plain nodes acts roughly like "boxed" |
130 |
* implementations of marked pointers, but uses new nodes only |
131 |
* when nodes are deleted, not for every link. This requires less |
132 |
* space and supports faster traversal. Even if marked references |
133 |
* were better supported by JVMs, traversal using this technique |
134 |
* might still be faster because any search need only read ahead |
135 |
* one more node than otherwise required (to check for trailing |
136 |
* marker) rather than unmasking mark bits or whatever on each |
137 |
* read. |
138 |
* |
139 |
* This approach maintains the essential property needed in the HM |
140 |
* algorithm of changing the next-pointer of a deleted node so |
141 |
* that any other CAS of it will fail, but implements the idea by |
142 |
* changing the pointer to point to a different node (with |
143 |
* otherwise illegal null fields), not by marking it. While it |
144 |
* would be possible to further squeeze space by defining marker |
145 |
* nodes not to have key/value fields, it isn't worth the extra |
146 |
* type-testing overhead. The deletion markers are rarely |
147 |
* encountered during traversal, are easily detected via null |
148 |
* checks that are needed anyway, and are normally quickly garbage |
149 |
* collected. (Note that this technique would not work well in |
150 |
* systems without garbage collection.) |
151 |
* |
152 |
* In addition to using deletion markers, the lists also use |
153 |
* nullness of value fields to indicate deletion, in a style |
154 |
* similar to typical lazy-deletion schemes. If a node's value is |
155 |
* null, then it is considered logically deleted and ignored even |
156 |
* though it is still reachable. |
157 |
* |
158 |
* Here's the sequence of events for a deletion of node n with |
159 |
* predecessor b and successor f, initially: |
160 |
* |
161 |
* +------+ +------+ +------+ |
162 |
* ... | b |------>| n |----->| f | ... |
163 |
* +------+ +------+ +------+ |
164 |
* |
165 |
* 1. CAS n's value field from non-null to null. |
166 |
* Traversals encountering a node with null value ignore it. |
167 |
* However, ongoing insertions and deletions might still modify |
168 |
* n's next pointer. |
169 |
* |
170 |
* 2. CAS n's next pointer to point to a new marker node. |
171 |
* From this point on, no other nodes can be appended to n. |
172 |
* which avoids deletion errors in CAS-based linked lists. |
173 |
* |
174 |
* +------+ +------+ +------+ +------+ |
175 |
* ... | b |------>| n |----->|marker|------>| f | ... |
176 |
* +------+ +------+ +------+ +------+ |
177 |
* |
178 |
* 3. CAS b's next pointer over both n and its marker. |
179 |
* From this point on, no new traversals will encounter n, |
180 |
* and it can eventually be GCed. |
181 |
* +------+ +------+ |
182 |
* ... | b |----------------------------------->| f | ... |
183 |
* +------+ +------+ |
184 |
* |
185 |
* A failure at step 1 leads to simple retry due to a lost race |
186 |
* with another operation. Steps 2-3 can fail because some other |
187 |
* thread noticed during a traversal a node with null value and |
188 |
* helped out by marking and/or unlinking. This helping-out |
189 |
* ensures that no thread can become stuck waiting for progress of |
190 |
* the deleting thread. |
191 |
* |
192 |
* Skip lists add indexing to this scheme, so that the base-level |
193 |
* traversals start close to the locations being found, inserted |
194 |
* or deleted -- usually base level traversals only traverse a few |
195 |
* nodes. This doesn't change the basic algorithm except for the |
196 |
* need to make sure base traversals start at predecessors (here, |
197 |
* b) that are not (structurally) deleted, otherwise retrying |
198 |
* after processing the deletion. |
199 |
* |
200 |
* Index levels are maintained using CAS to link and unlink |
201 |
* successors ("right" fields). Races are allowed in index-list |
202 |
* operations that can (rarely) fail to link in a new index node. |
203 |
* (We can't do this of course for data nodes.) However, even |
204 |
* when this happens, the index lists correctly guide search. |
205 |
* This can impact performance, but since skip lists are |
206 |
* probabilistic anyway, the net result is that under contention, |
207 |
* the effective "p" value may be lower than its nominal value. |
208 |
* |
209 |
* Index insertion and deletion sometimes require a separate |
210 |
* traversal pass occurring after the base-level action, to add or |
211 |
* remove index nodes. This adds to single-threaded overhead, but |
212 |
* improves contended multithreaded performance by narrowing |
213 |
* interference windows, and allows deletion to ensure that all |
214 |
* index nodes will be made unreachable upon return from a public |
215 |
* remove operation, thus avoiding unwanted garbage retention. |
216 |
* |
217 |
* Indexing uses skip list parameters that maintain good search |
218 |
* performance while using sparser-than-usual indices: The |
219 |
* hardwired parameters k=1, p=0.5 (see method doPut) mean that |
220 |
* about one-quarter of the nodes have indices. Of those that do, |
221 |
* half have one level, a quarter have two, and so on (see Pugh's |
222 |
* Skip List Cookbook, sec 3.4), up to a maximum of 62 levels |
223 |
* (appropriate for up to 2^63 elements). The expected total |
224 |
* space requirement for a map is slightly less than for the |
225 |
* current implementation of java.util.TreeMap. |
226 |
* |
227 |
* Changing the level of the index (i.e, the height of the |
228 |
* tree-like structure) also uses CAS. Creation of an index with |
229 |
* height greater than the current level adds a level to the head |
230 |
* index by CAS'ing on a new top-most head. To maintain good |
231 |
* performance after a lot of removals, deletion methods |
232 |
* heuristically try to reduce the height if the topmost levels |
233 |
* appear to be empty. This may encounter races in which it is |
234 |
* possible (but rare) to reduce and "lose" a level just as it is |
235 |
* about to contain an index (that will then never be |
236 |
* encountered). This does no structural harm, and in practice |
237 |
* appears to be a better option than allowing unrestrained growth |
238 |
* of levels. |
239 |
* |
240 |
* This class provides concurrent-reader-style memory consistency, |
241 |
* ensuring that read-only methods report status and/or values no |
242 |
* staler than those holding at method entry. This is done by |
243 |
* performing all publication and structural updates using |
244 |
* (volatile) CAS, placing an acquireFence in a few access |
245 |
* methods, and ensuring that linked objects are transitively |
246 |
* acquired via dependent reads (normally once) unless performing |
247 |
* a volatile-mode CAS operation (that also acts as an acquire and |
248 |
* release). This form of fence-hoisting is similar to RCU and |
249 |
* related techniques (see McKenney's online book |
250 |
* https://www.kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html) |
251 |
* It minimizes overhead that may otherwise occur when using so |
252 |
* many volatile-mode reads. Using explicit acquireFences is |
253 |
* logistically easier than targeting particular fields to be read |
254 |
* in acquire mode: fences are just hoisted up as far as possible, |
255 |
* to the entry points or loop headers of a few methods. A |
256 |
* potential disadvantage is that these few remaining fences are |
257 |
* not easily optimized away by compilers under exclusively |
258 |
* single-thread use. It requires some care to avoid volatile |
259 |
* mode reads of other fields. (Note that the memory semantics of |
260 |
* a reference dependently read in plain mode exactly once are |
261 |
* equivalent to those for atomic opaque mode.) Iterators and |
262 |
* other traversals encounter each node and value exactly once. |
263 |
* Other operations locate an element (or position to insert an |
264 |
* element) via a sequence of dereferences. This search is broken |
265 |
* into two parts. Method findPredecessor (and its specialized |
266 |
* embeddings) searches index nodes only, returning a base-level |
267 |
* predecessor of the key. Callers carry out the base-level |
268 |
* search, restarting if encountering a marker preventing link |
269 |
* modification. In some cases, it is possible to encounter a |
270 |
* node multiple times while descending levels. For mutative |
271 |
* operations, the reported value is validated using CAS (else |
272 |
* retrying), preserving linearizability with respect to each |
273 |
* other. Others may return any (non-null) value holding in the |
274 |
* course of the method call. (Search-based methods also include |
275 |
* some useless-looking explicit null checks designed to allow |
276 |
* more fields to be nulled out upon removal, to reduce floating |
277 |
* garbage, but which is not currently done, pending discovery of |
278 |
* a way to do this with less impact on other operations.) |
279 |
* |
280 |
* To produce random values without interference across threads, |
281 |
* we use within-JDK thread local random support (via the |
282 |
* "secondary seed", to avoid interference with user-level |
283 |
* ThreadLocalRandom.) |
284 |
* |
285 |
* For explanation of algorithms sharing at least a couple of |
286 |
* features with this one, see Mikhail Fomitchev's thesis |
287 |
* (http://www.cs.yorku.ca/~mikhail/), Keir Fraser's thesis |
288 |
* (http://www.cl.cam.ac.uk/users/kaf24/), and Hakan Sundell's |
289 |
* thesis (http://www.cs.chalmers.se/~phs/). |
290 |
* |
291 |
* Notation guide for local variables |
292 |
* Node: b, n, f, p for predecessor, node, successor, aux |
293 |
* Index: q, r, d for index node, right, down. |
294 |
* Head: h |
295 |
* Keys: k, key |
296 |
* Values: v, value |
297 |
* Comparisons: c |
298 |
*/ |
299 |
|
300 |
private static final long serialVersionUID = -8627078645895051609L; |
301 |
|
302 |
/** |
303 |
* The comparator used to maintain order in this map, or null if |
304 |
* using natural ordering. (Non-private to simplify access in |
305 |
* nested classes.) |
306 |
* @serial |
307 |
*/ |
308 |
@SuppressWarnings("serial") // Conditionally serializable |
309 |
final Comparator<? super K> comparator; |
310 |
|
311 |
/** Lazily initialized topmost index of the skiplist. */ |
312 |
private transient Index<K,V> head; |
313 |
/** Lazily initialized element count */ |
314 |
private transient LongAdder adder; |
315 |
/** Lazily initialized key set */ |
316 |
private transient KeySet<K,V> keySet; |
317 |
/** Lazily initialized values collection */ |
318 |
private transient Values<K,V> values; |
319 |
/** Lazily initialized entry set */ |
320 |
private transient EntrySet<K,V> entrySet; |
321 |
/** Lazily initialized descending map */ |
322 |
private transient SubMap<K,V> descendingMap; |
323 |
|
324 |
/** |
325 |
* Nodes hold keys and values, and are singly linked in sorted |
326 |
* order, possibly with some intervening marker nodes. The list is |
327 |
* headed by a header node accessible as head.node. Headers and |
328 |
* marker nodes have null keys. The val field (but currently not |
329 |
* the key field) is nulled out upon deletion. |
330 |
*/ |
331 |
static final class Node<K,V> { |
332 |
final K key; // currently, never detached |
333 |
V val; |
334 |
Node<K,V> next; |
335 |
Node(K key, V value, Node<K,V> next) { |
336 |
this.key = key; |
337 |
this.val = value; |
338 |
this.next = next; |
339 |
} |
340 |
} |
341 |
|
342 |
/** |
343 |
* Index nodes represent the levels of the skip list. |
344 |
*/ |
345 |
static final class Index<K,V> { |
346 |
final Node<K,V> node; // currently, never detached |
347 |
final Index<K,V> down; |
348 |
Index<K,V> right; |
349 |
Index(Node<K,V> node, Index<K,V> down, Index<K,V> right) { |
350 |
this.node = node; |
351 |
this.down = down; |
352 |
this.right = right; |
353 |
} |
354 |
} |
355 |
|
356 |
/* ---------------- Utilities -------------- */ |
357 |
|
358 |
/** |
359 |
* Compares using comparator or natural ordering if null. |
360 |
* Called only by methods that have performed required type checks. |
361 |
*/ |
362 |
@SuppressWarnings({"unchecked", "rawtypes"}) |
363 |
static int cpr(Comparator c, Object x, Object y) { |
364 |
return (c != null) ? c.compare(x, y) : ((Comparable)x).compareTo(y); |
365 |
} |
366 |
|
367 |
/** |
368 |
* Returns the header for base node list, or null if uninitialized |
369 |
*/ |
370 |
final Node<K,V> baseHead() { |
371 |
Index<K,V> h; |
372 |
VarHandle.acquireFence(); |
373 |
return ((h = head) == null) ? null : h.node; |
374 |
} |
375 |
|
376 |
/** |
377 |
* Tries to unlink deleted node n from predecessor b (if both |
378 |
* exist), by first splicing in a marker if not already present. |
379 |
* Upon return, node n is sure to be unlinked from b, possibly |
380 |
* via the actions of some other thread. |
381 |
* |
382 |
* @param b if nonnull, predecessor |
383 |
* @param n if nonnull, node known to be deleted |
384 |
*/ |
385 |
static <K,V> void unlinkNode(Node<K,V> b, Node<K,V> n) { |
386 |
if (b != null && n != null) { |
387 |
Node<K,V> f, p; |
388 |
for (;;) { |
389 |
if ((f = n.next) != null && f.key == null) { |
390 |
p = f.next; // already marked |
391 |
break; |
392 |
} |
393 |
else if (NEXT.compareAndSet(n, f, |
394 |
new Node<K,V>(null, null, f))) { |
395 |
p = f; // add marker |
396 |
break; |
397 |
} |
398 |
} |
399 |
NEXT.compareAndSet(b, n, p); |
400 |
} |
401 |
} |
402 |
|
403 |
/** |
404 |
* Adds to element count, initializing adder if necessary |
405 |
* |
406 |
* @param c count to add |
407 |
*/ |
408 |
private void addCount(long c) { |
409 |
LongAdder a; |
410 |
do {} while ((a = adder) == null && |
411 |
!ADDER.compareAndSet(this, null, a = new LongAdder())); |
412 |
a.add(c); |
413 |
} |
414 |
|
415 |
/** |
416 |
* Returns element count, initializing adder if necessary. |
417 |
*/ |
418 |
final long getAdderCount() { |
419 |
LongAdder a; long c; |
420 |
do {} while ((a = adder) == null && |
421 |
!ADDER.compareAndSet(this, null, a = new LongAdder())); |
422 |
return ((c = a.sum()) <= 0L) ? 0L : c; // ignore transient negatives |
423 |
} |
424 |
|
425 |
/* ---------------- Traversal -------------- */ |
426 |
|
427 |
/** |
428 |
* Returns an index node with key strictly less than given key. |
429 |
* Also unlinks indexes to deleted nodes found along the way. |
430 |
* Callers rely on this side-effect of clearing indices to deleted |
431 |
* nodes. |
432 |
* |
433 |
* @param key if nonnull the key |
434 |
* @return a predecessor node of key, or null if uninitialized or null key |
435 |
*/ |
436 |
private Node<K,V> findPredecessor(Object key, Comparator<? super K> cmp) { |
437 |
Index<K,V> q; |
438 |
VarHandle.acquireFence(); |
439 |
if ((q = head) == null || key == null) |
440 |
return null; |
441 |
else { |
442 |
for (Index<K,V> r, d;;) { |
443 |
while ((r = q.right) != null) { |
444 |
Node<K,V> p; K k; |
445 |
if ((p = r.node) == null || (k = p.key) == null || |
446 |
p.val == null) // unlink index to deleted node |
447 |
RIGHT.compareAndSet(q, r, r.right); |
448 |
else if (cpr(cmp, key, k) > 0) |
449 |
q = r; |
450 |
else |
451 |
break; |
452 |
} |
453 |
if ((d = q.down) != null) |
454 |
q = d; |
455 |
else |
456 |
return q.node; |
457 |
} |
458 |
} |
459 |
} |
460 |
|
461 |
/** |
462 |
* Returns node holding key or null if no such, clearing out any |
463 |
* deleted nodes seen along the way. Repeatedly traverses at |
464 |
* base-level looking for key starting at predecessor returned |
465 |
* from findPredecessor, processing base-level deletions as |
466 |
* encountered. Restarts occur, at traversal step encountering |
467 |
* node n, if n's key field is null, indicating it is a marker, so |
468 |
* its predecessor is deleted before continuing, which we help do |
469 |
* by re-finding a valid predecessor. The traversal loops in |
470 |
* doPut, doRemove, and findNear all include the same checks. |
471 |
* |
472 |
* @param key the key |
473 |
* @return node holding key, or null if no such |
474 |
*/ |
475 |
private Node<K,V> findNode(Object key) { |
476 |
if (key == null) |
477 |
throw new NullPointerException(); // don't postpone errors |
478 |
Comparator<? super K> cmp = comparator; |
479 |
Node<K,V> b; |
480 |
outer: while ((b = findPredecessor(key, cmp)) != null) { |
481 |
for (;;) { |
482 |
Node<K,V> n; K k; V v; int c; |
483 |
if ((n = b.next) == null) |
484 |
break outer; // empty |
485 |
else if ((k = n.key) == null) |
486 |
break; // b is deleted |
487 |
else if ((v = n.val) == null) |
488 |
unlinkNode(b, n); // n is deleted |
489 |
else if ((c = cpr(cmp, key, k)) > 0) |
490 |
b = n; |
491 |
else if (c == 0) |
492 |
return n; |
493 |
else |
494 |
break outer; |
495 |
} |
496 |
} |
497 |
return null; |
498 |
} |
499 |
|
500 |
/** |
501 |
* Gets value for key. Same idea as findNode, except skips over |
502 |
* deletions and markers, and returns first encountered value to |
503 |
* avoid possibly inconsistent rereads. |
504 |
* |
505 |
* @param key the key |
506 |
* @return the value, or null if absent |
507 |
*/ |
508 |
private V doGet(Object key) { |
509 |
Index<K,V> q; |
510 |
VarHandle.acquireFence(); |
511 |
if (key == null) |
512 |
throw new NullPointerException(); |
513 |
Comparator<? super K> cmp = comparator; |
514 |
V result = null; |
515 |
if ((q = head) != null) { |
516 |
outer: for (Index<K,V> r, d;;) { |
517 |
while ((r = q.right) != null) { |
518 |
Node<K,V> p; K k; V v; int c; |
519 |
if ((p = r.node) == null || (k = p.key) == null || |
520 |
(v = p.val) == null) |
521 |
RIGHT.compareAndSet(q, r, r.right); |
522 |
else if ((c = cpr(cmp, key, k)) > 0) |
523 |
q = r; |
524 |
else if (c == 0) { |
525 |
result = v; |
526 |
break outer; |
527 |
} |
528 |
else |
529 |
break; |
530 |
} |
531 |
if ((d = q.down) != null) |
532 |
q = d; |
533 |
else { |
534 |
Node<K,V> b, n; |
535 |
if ((b = q.node) != null) { |
536 |
while ((n = b.next) != null) { |
537 |
V v; int c; |
538 |
K k = n.key; |
539 |
if ((v = n.val) == null || k == null || |
540 |
(c = cpr(cmp, key, k)) > 0) |
541 |
b = n; |
542 |
else { |
543 |
if (c == 0) |
544 |
result = v; |
545 |
break; |
546 |
} |
547 |
} |
548 |
} |
549 |
break; |
550 |
} |
551 |
} |
552 |
} |
553 |
return result; |
554 |
} |
555 |
|
556 |
/* ---------------- Insertion -------------- */ |
557 |
|
558 |
/** |
559 |
* Main insertion method. Adds element if not present, or |
560 |
* replaces value if present and onlyIfAbsent is false. |
561 |
* |
562 |
* @param key the key |
563 |
* @param value the value that must be associated with key |
564 |
* @param onlyIfAbsent if should not insert if already present |
565 |
* @return the old value, or null if newly inserted |
566 |
*/ |
567 |
private V doPut(K key, V value, boolean onlyIfAbsent) { |
568 |
if (key == null) |
569 |
throw new NullPointerException(); |
570 |
Comparator<? super K> cmp = comparator; |
571 |
for (;;) { |
572 |
Index<K,V> h; Node<K,V> b; |
573 |
VarHandle.acquireFence(); |
574 |
int levels = 0; // number of levels descended |
575 |
if ((h = head) == null) { // try to initialize |
576 |
Node<K,V> base = new Node<K,V>(null, null, null); |
577 |
h = new Index<K,V>(base, null, null); |
578 |
b = (HEAD.compareAndSet(this, null, h)) ? base : null; |
579 |
} |
580 |
else { |
581 |
for (Index<K,V> q = h, r, d;;) { // count while descending |
582 |
while ((r = q.right) != null) { |
583 |
Node<K,V> p; K k; |
584 |
if ((p = r.node) == null || (k = p.key) == null || |
585 |
p.val == null) |
586 |
RIGHT.compareAndSet(q, r, r.right); |
587 |
else if (cpr(cmp, key, k) > 0) |
588 |
q = r; |
589 |
else |
590 |
break; |
591 |
} |
592 |
if ((d = q.down) != null) { |
593 |
++levels; |
594 |
q = d; |
595 |
} |
596 |
else { |
597 |
b = q.node; |
598 |
break; |
599 |
} |
600 |
} |
601 |
} |
602 |
if (b != null) { |
603 |
Node<K,V> z = null; // new node, if inserted |
604 |
for (;;) { // find insertion point |
605 |
Node<K,V> n, p; K k; V v; int c; |
606 |
if ((n = b.next) == null) { |
607 |
if (b.key == null) // if empty, type check key now |
608 |
cpr(cmp, key, key); |
609 |
c = -1; |
610 |
} |
611 |
else if ((k = n.key) == null) |
612 |
break; // can't append; restart |
613 |
else if ((v = n.val) == null) { |
614 |
unlinkNode(b, n); |
615 |
c = 1; |
616 |
} |
617 |
else if ((c = cpr(cmp, key, k)) > 0) |
618 |
b = n; |
619 |
else if (c == 0 && |
620 |
(onlyIfAbsent || VAL.compareAndSet(n, v, value))) |
621 |
return v; |
622 |
|
623 |
if (c < 0 && |
624 |
NEXT.compareAndSet(b, n, |
625 |
p = new Node<K,V>(key, value, n))) { |
626 |
z = p; |
627 |
break; |
628 |
} |
629 |
} |
630 |
|
631 |
if (z != null) { |
632 |
int lr = ThreadLocalRandom.nextSecondarySeed(); |
633 |
if ((lr & 0x3) == 0) { // add indices with 1/4 prob |
634 |
int hr = ThreadLocalRandom.nextSecondarySeed(); |
635 |
long rnd = ((long)hr << 32) | ((long)lr & 0xffffffffL); |
636 |
int skips = levels; // levels to descend before add |
637 |
Index<K,V> x = null; |
638 |
for (;;) { // create at most 62 indices |
639 |
x = new Index<K,V>(z, x, null); |
640 |
if (rnd >= 0L || --skips < 0) |
641 |
break; |
642 |
else |
643 |
rnd <<= 1; |
644 |
} |
645 |
if (addIndices(h, skips, x, cmp) && skips < 0 && |
646 |
head == h) { // try to add new level |
647 |
Index<K,V> hx = new Index<K,V>(z, x, null); |
648 |
Index<K,V> nh = new Index<K,V>(h.node, h, hx); |
649 |
HEAD.compareAndSet(this, h, nh); |
650 |
} |
651 |
if (z.val == null) // deleted while adding indices |
652 |
findPredecessor(key, cmp); // clean |
653 |
} |
654 |
addCount(1L); |
655 |
return null; |
656 |
} |
657 |
} |
658 |
} |
659 |
} |
660 |
|
661 |
/** |
662 |
* Add indices after an insertion. Descends iteratively to the |
663 |
* highest level of insertion, then recursively, to chain index |
664 |
* nodes to lower ones. Returns null on (staleness) failure, |
665 |
* disabling higher-level insertions. Recursion depths are |
666 |
* exponentially less probable. |
667 |
* |
668 |
* @param q starting index for current level |
669 |
* @param skips levels to skip before inserting |
670 |
* @param x index for this insertion |
671 |
* @param cmp comparator |
672 |
*/ |
673 |
static <K,V> boolean addIndices(Index<K,V> q, int skips, Index<K,V> x, |
674 |
Comparator<? super K> cmp) { |
675 |
Node<K,V> z; K key; |
676 |
if (x != null && (z = x.node) != null && (key = z.key) != null && |
677 |
q != null) { // hoist checks |
678 |
boolean retrying = false; |
679 |
for (;;) { // find splice point |
680 |
Index<K,V> r, d; int c; |
681 |
if ((r = q.right) != null) { |
682 |
Node<K,V> p; K k; |
683 |
if ((p = r.node) == null || (k = p.key) == null || |
684 |
p.val == null) { |
685 |
RIGHT.compareAndSet(q, r, r.right); |
686 |
c = 0; |
687 |
} |
688 |
else if ((c = cpr(cmp, key, k)) > 0) |
689 |
q = r; |
690 |
else if (c == 0) |
691 |
break; // stale |
692 |
} |
693 |
else |
694 |
c = -1; |
695 |
|
696 |
if (c < 0) { |
697 |
if ((d = q.down) != null && skips > 0) { |
698 |
--skips; |
699 |
q = d; |
700 |
} |
701 |
else if (d != null && !retrying && |
702 |
!addIndices(d, 0, x.down, cmp)) |
703 |
break; |
704 |
else { |
705 |
x.right = r; |
706 |
if (RIGHT.compareAndSet(q, r, x)) |
707 |
return true; |
708 |
else |
709 |
retrying = true; // re-find splice point |
710 |
} |
711 |
} |
712 |
} |
713 |
} |
714 |
return false; |
715 |
} |
716 |
|
717 |
/* ---------------- Deletion -------------- */ |
718 |
|
719 |
/** |
720 |
* Main deletion method. Locates node, nulls value, appends a |
721 |
* deletion marker, unlinks predecessor, removes associated index |
722 |
* nodes, and possibly reduces head index level. |
723 |
* |
724 |
* @param key the key |
725 |
* @param value if non-null, the value that must be |
726 |
* associated with key |
727 |
* @return the node, or null if not found |
728 |
*/ |
729 |
final V doRemove(Object key, Object value) { |
730 |
if (key == null) |
731 |
throw new NullPointerException(); |
732 |
Comparator<? super K> cmp = comparator; |
733 |
V result = null; |
734 |
Node<K,V> b; |
735 |
outer: while ((b = findPredecessor(key, cmp)) != null && |
736 |
result == null) { |
737 |
for (;;) { |
738 |
Node<K,V> n; K k; V v; int c; |
739 |
if ((n = b.next) == null) |
740 |
break outer; |
741 |
else if ((k = n.key) == null) |
742 |
break; |
743 |
else if ((v = n.val) == null) |
744 |
unlinkNode(b, n); |
745 |
else if ((c = cpr(cmp, key, k)) > 0) |
746 |
b = n; |
747 |
else if (c < 0) |
748 |
break outer; |
749 |
else if (value != null && !value.equals(v)) |
750 |
break outer; |
751 |
else if (VAL.compareAndSet(n, v, null)) { |
752 |
result = v; |
753 |
unlinkNode(b, n); |
754 |
break; // loop to clean up |
755 |
} |
756 |
} |
757 |
} |
758 |
if (result != null) { |
759 |
tryReduceLevel(); |
760 |
addCount(-1L); |
761 |
} |
762 |
return result; |
763 |
} |
764 |
|
765 |
/** |
766 |
* Possibly reduce head level if it has no nodes. This method can |
767 |
* (rarely) make mistakes, in which case levels can disappear even |
768 |
* though they are about to contain index nodes. This impacts |
769 |
* performance, not correctness. To minimize mistakes as well as |
770 |
* to reduce hysteresis, the level is reduced by one only if the |
771 |
* topmost three levels look empty. Also, if the removed level |
772 |
* looks non-empty after CAS, we try to change it back quick |
773 |
* before anyone notices our mistake! (This trick works pretty |
774 |
* well because this method will practically never make mistakes |
775 |
* unless current thread stalls immediately before first CAS, in |
776 |
* which case it is very unlikely to stall again immediately |
777 |
* afterwards, so will recover.) |
778 |
* |
779 |
* We put up with all this rather than just let levels grow |
780 |
* because otherwise, even a small map that has undergone a large |
781 |
* number of insertions and removals will have a lot of levels, |
782 |
* slowing down access more than would an occasional unwanted |
783 |
* reduction. |
784 |
*/ |
785 |
private void tryReduceLevel() { |
786 |
Index<K,V> h, d, e; |
787 |
if ((h = head) != null && h.right == null && |
788 |
(d = h.down) != null && d.right == null && |
789 |
(e = d.down) != null && e.right == null && |
790 |
HEAD.compareAndSet(this, h, d) && |
791 |
h.right != null) // recheck |
792 |
HEAD.compareAndSet(this, d, h); // try to backout |
793 |
} |
794 |
|
795 |
/* ---------------- Finding and removing first element -------------- */ |
796 |
|
797 |
/** |
798 |
* Gets first valid node, unlinking deleted nodes if encountered. |
799 |
* @return first node or null if empty |
800 |
*/ |
801 |
final Node<K,V> findFirst() { |
802 |
Node<K,V> b, n; |
803 |
if ((b = baseHead()) != null) { |
804 |
while ((n = b.next) != null) { |
805 |
if (n.val == null) |
806 |
unlinkNode(b, n); |
807 |
else |
808 |
return n; |
809 |
} |
810 |
} |
811 |
return null; |
812 |
} |
813 |
|
814 |
/** |
815 |
* Entry snapshot version of findFirst |
816 |
*/ |
817 |
final AbstractMap.SimpleImmutableEntry<K,V> findFirstEntry() { |
818 |
Node<K,V> b, n; V v; |
819 |
if ((b = baseHead()) != null) { |
820 |
while ((n = b.next) != null) { |
821 |
if ((v = n.val) == null) |
822 |
unlinkNode(b, n); |
823 |
else |
824 |
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v); |
825 |
} |
826 |
} |
827 |
return null; |
828 |
} |
829 |
|
830 |
/** |
831 |
* Removes first entry; returns its snapshot. |
832 |
* @return null if empty, else snapshot of first entry |
833 |
*/ |
834 |
private AbstractMap.SimpleImmutableEntry<K,V> doRemoveFirstEntry() { |
835 |
Node<K,V> b, n; V v; |
836 |
if ((b = baseHead()) != null) { |
837 |
while ((n = b.next) != null) { |
838 |
if ((v = n.val) == null || VAL.compareAndSet(n, v, null)) { |
839 |
K k = n.key; |
840 |
unlinkNode(b, n); |
841 |
if (v != null) { |
842 |
tryReduceLevel(); |
843 |
findPredecessor(k, comparator); // clean index |
844 |
addCount(-1L); |
845 |
return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); |
846 |
} |
847 |
} |
848 |
} |
849 |
} |
850 |
return null; |
851 |
} |
852 |
|
853 |
/* ---------------- Finding and removing last element -------------- */ |
854 |
|
855 |
/** |
856 |
* Specialized version of find to get last valid node. |
857 |
* @return last node or null if empty |
858 |
*/ |
859 |
final Node<K,V> findLast() { |
860 |
outer: for (;;) { |
861 |
Index<K,V> q; Node<K,V> b; |
862 |
VarHandle.acquireFence(); |
863 |
if ((q = head) == null) |
864 |
break; |
865 |
for (Index<K,V> r, d;;) { |
866 |
while ((r = q.right) != null) { |
867 |
Node<K,V> p; |
868 |
if ((p = r.node) == null || p.val == null) |
869 |
RIGHT.compareAndSet(q, r, r.right); |
870 |
else |
871 |
q = r; |
872 |
} |
873 |
if ((d = q.down) != null) |
874 |
q = d; |
875 |
else { |
876 |
b = q.node; |
877 |
break; |
878 |
} |
879 |
} |
880 |
if (b != null) { |
881 |
for (;;) { |
882 |
Node<K,V> n; |
883 |
if ((n = b.next) == null) { |
884 |
if (b.key == null) // empty |
885 |
break outer; |
886 |
else |
887 |
return b; |
888 |
} |
889 |
else if (n.key == null) |
890 |
break; |
891 |
else if (n.val == null) |
892 |
unlinkNode(b, n); |
893 |
else |
894 |
b = n; |
895 |
} |
896 |
} |
897 |
} |
898 |
return null; |
899 |
} |
900 |
|
901 |
/** |
902 |
* Entry version of findLast |
903 |
* @return Entry for last node or null if empty |
904 |
*/ |
905 |
final AbstractMap.SimpleImmutableEntry<K,V> findLastEntry() { |
906 |
for (;;) { |
907 |
Node<K,V> n; V v; |
908 |
if ((n = findLast()) == null) |
909 |
return null; |
910 |
if ((v = n.val) != null) |
911 |
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v); |
912 |
} |
913 |
} |
914 |
|
915 |
/** |
916 |
* Removes last entry; returns its snapshot. |
917 |
* Specialized variant of doRemove. |
918 |
* @return null if empty, else snapshot of last entry |
919 |
*/ |
920 |
private Map.Entry<K,V> doRemoveLastEntry() { |
921 |
outer: for (;;) { |
922 |
Index<K,V> q; Node<K,V> b; |
923 |
VarHandle.acquireFence(); |
924 |
if ((q = head) == null) |
925 |
break; |
926 |
for (;;) { |
927 |
Index<K,V> d, r; Node<K,V> p; |
928 |
while ((r = q.right) != null) { |
929 |
if ((p = r.node) == null || p.val == null) |
930 |
RIGHT.compareAndSet(q, r, r.right); |
931 |
else if (p.next != null) |
932 |
q = r; // continue only if a successor |
933 |
else |
934 |
break; |
935 |
} |
936 |
if ((d = q.down) != null) |
937 |
q = d; |
938 |
else { |
939 |
b = q.node; |
940 |
break; |
941 |
} |
942 |
} |
943 |
if (b != null) { |
944 |
for (;;) { |
945 |
Node<K,V> n; K k; V v; |
946 |
if ((n = b.next) == null) { |
947 |
if (b.key == null) // empty |
948 |
break outer; |
949 |
else |
950 |
break; // retry |
951 |
} |
952 |
else if ((k = n.key) == null) |
953 |
break; |
954 |
else if ((v = n.val) == null) |
955 |
unlinkNode(b, n); |
956 |
else if (n.next != null) |
957 |
b = n; |
958 |
else if (VAL.compareAndSet(n, v, null)) { |
959 |
unlinkNode(b, n); |
960 |
tryReduceLevel(); |
961 |
findPredecessor(k, comparator); // clean index |
962 |
addCount(-1L); |
963 |
return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); |
964 |
} |
965 |
} |
966 |
} |
967 |
} |
968 |
return null; |
969 |
} |
970 |
|
971 |
/* ---------------- Relational operations -------------- */ |
972 |
|
973 |
// Control values OR'ed as arguments to findNear |
974 |
|
975 |
private static final int EQ = 1; |
976 |
private static final int LT = 2; |
977 |
private static final int GT = 0; // Actually checked as !LT |
978 |
|
979 |
/** |
980 |
* Utility for ceiling, floor, lower, higher methods. |
981 |
* @param key the key |
982 |
* @param rel the relation -- OR'ed combination of EQ, LT, GT |
983 |
* @return nearest node fitting relation, or null if no such |
984 |
*/ |
985 |
final Node<K,V> findNear(K key, int rel, Comparator<? super K> cmp) { |
986 |
if (key == null) |
987 |
throw new NullPointerException(); |
988 |
Node<K,V> result; |
989 |
outer: for (Node<K,V> b;;) { |
990 |
if ((b = findPredecessor(key, cmp)) == null) { |
991 |
result = null; |
992 |
break; // empty |
993 |
} |
994 |
for (;;) { |
995 |
Node<K,V> n; K k; int c; |
996 |
if ((n = b.next) == null) { |
997 |
result = ((rel & LT) != 0 && b.key != null) ? b : null; |
998 |
break outer; |
999 |
} |
1000 |
else if ((k = n.key) == null) |
1001 |
break; |
1002 |
else if (n.val == null) |
1003 |
unlinkNode(b, n); |
1004 |
else if (((c = cpr(cmp, key, k)) == 0 && (rel & EQ) != 0) || |
1005 |
(c < 0 && (rel & LT) == 0)) { |
1006 |
result = n; |
1007 |
break outer; |
1008 |
} |
1009 |
else if (c <= 0 && (rel & LT) != 0) { |
1010 |
result = (b.key != null) ? b : null; |
1011 |
break outer; |
1012 |
} |
1013 |
else |
1014 |
b = n; |
1015 |
} |
1016 |
} |
1017 |
return result; |
1018 |
} |
1019 |
|
1020 |
/** |
1021 |
* Variant of findNear returning SimpleImmutableEntry |
1022 |
* @param key the key |
1023 |
* @param rel the relation -- OR'ed combination of EQ, LT, GT |
1024 |
* @return Entry fitting relation, or null if no such |
1025 |
*/ |
1026 |
final AbstractMap.SimpleImmutableEntry<K,V> findNearEntry(K key, int rel, |
1027 |
Comparator<? super K> cmp) { |
1028 |
for (;;) { |
1029 |
Node<K,V> n; V v; |
1030 |
if ((n = findNear(key, rel, cmp)) == null) |
1031 |
return null; |
1032 |
if ((v = n.val) != null) |
1033 |
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v); |
1034 |
} |
1035 |
} |
1036 |
|
1037 |
/* ---------------- Constructors -------------- */ |
1038 |
|
1039 |
/** |
1040 |
* Constructs a new, empty map, sorted according to the |
1041 |
* {@linkplain Comparable natural ordering} of the keys. |
1042 |
*/ |
1043 |
public ConcurrentSkipListMap() { |
1044 |
this.comparator = null; |
1045 |
} |
1046 |
|
1047 |
/** |
1048 |
* Constructs a new, empty map, sorted according to the specified |
1049 |
* comparator. |
1050 |
* |
1051 |
* @param comparator the comparator that will be used to order this map. |
1052 |
* If {@code null}, the {@linkplain Comparable natural |
1053 |
* ordering} of the keys will be used. |
1054 |
*/ |
1055 |
public ConcurrentSkipListMap(Comparator<? super K> comparator) { |
1056 |
this.comparator = comparator; |
1057 |
} |
1058 |
|
1059 |
/** |
1060 |
* Constructs a new map containing the same mappings as the given map, |
1061 |
* sorted according to the {@linkplain Comparable natural ordering} of |
1062 |
* the keys. |
1063 |
* |
1064 |
* @param m the map whose mappings are to be placed in this map |
1065 |
* @throws ClassCastException if the keys in {@code m} are not |
1066 |
* {@link Comparable}, or are not mutually comparable |
1067 |
* @throws NullPointerException if the specified map or any of its keys |
1068 |
* or values are null |
1069 |
*/ |
1070 |
public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) { |
1071 |
this.comparator = null; |
1072 |
putAll(m); |
1073 |
} |
1074 |
|
1075 |
/** |
1076 |
* Constructs a new map containing the same mappings and using the |
1077 |
* same ordering as the specified sorted map. |
1078 |
* |
1079 |
* @param m the sorted map whose mappings are to be placed in this |
1080 |
* map, and whose comparator is to be used to sort this map |
1081 |
* @throws NullPointerException if the specified sorted map or any of |
1082 |
* its keys or values are null |
1083 |
*/ |
1084 |
public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) { |
1085 |
this.comparator = m.comparator(); |
1086 |
buildFromSorted(m); // initializes transients |
1087 |
} |
1088 |
|
1089 |
/** |
1090 |
* Returns a shallow copy of this {@code ConcurrentSkipListMap} |
1091 |
* instance. (The keys and values themselves are not cloned.) |
1092 |
* |
1093 |
* @return a shallow copy of this map |
1094 |
*/ |
1095 |
public ConcurrentSkipListMap<K,V> clone() { |
1096 |
try { |
1097 |
@SuppressWarnings("unchecked") |
1098 |
ConcurrentSkipListMap<K,V> clone = |
1099 |
(ConcurrentSkipListMap<K,V>) super.clone(); |
1100 |
clone.keySet = null; |
1101 |
clone.entrySet = null; |
1102 |
clone.values = null; |
1103 |
clone.descendingMap = null; |
1104 |
clone.adder = null; |
1105 |
clone.buildFromSorted(this); |
1106 |
return clone; |
1107 |
} catch (CloneNotSupportedException e) { |
1108 |
throw new InternalError(); |
1109 |
} |
1110 |
} |
1111 |
|
1112 |
/** |
1113 |
* Streamlined bulk insertion to initialize from elements of |
1114 |
* given sorted map. Call only from constructor or clone |
1115 |
* method. |
1116 |
*/ |
1117 |
private void buildFromSorted(SortedMap<K, ? extends V> map) { |
1118 |
if (map == null) |
1119 |
throw new NullPointerException(); |
1120 |
Iterator<? extends Map.Entry<? extends K, ? extends V>> it = |
1121 |
map.entrySet().iterator(); |
1122 |
|
1123 |
/* |
1124 |
* Add equally spaced indices at log intervals, using the bits |
1125 |
* of count during insertion. The maximum possible resulting |
1126 |
* level is less than the number of bits in a long (64). The |
1127 |
* preds array tracks the current rightmost node at each |
1128 |
* level. |
1129 |
*/ |
1130 |
@SuppressWarnings("unchecked") |
1131 |
Index<K,V>[] preds = (Index<K,V>[])new Index<?,?>[64]; |
1132 |
Node<K,V> bp = new Node<K,V>(null, null, null); |
1133 |
Index<K,V> h = preds[0] = new Index<K,V>(bp, null, null); |
1134 |
long count = 0; |
1135 |
|
1136 |
while (it.hasNext()) { |
1137 |
Map.Entry<? extends K, ? extends V> e = it.next(); |
1138 |
K k = e.getKey(); |
1139 |
V v = e.getValue(); |
1140 |
if (k == null || v == null) |
1141 |
throw new NullPointerException(); |
1142 |
Node<K,V> z = new Node<K,V>(k, v, null); |
1143 |
bp = bp.next = z; |
1144 |
if ((++count & 3L) == 0L) { |
1145 |
long m = count >>> 2; |
1146 |
int i = 0; |
1147 |
Index<K,V> idx = null, q; |
1148 |
do { |
1149 |
idx = new Index<K,V>(z, idx, null); |
1150 |
if ((q = preds[i]) == null) |
1151 |
preds[i] = h = new Index<K,V>(h.node, h, idx); |
1152 |
else |
1153 |
preds[i] = q.right = idx; |
1154 |
} while (++i < preds.length && ((m >>>= 1) & 1L) != 0L); |
1155 |
} |
1156 |
} |
1157 |
if (count != 0L) { |
1158 |
VarHandle.releaseFence(); // emulate volatile stores |
1159 |
addCount(count); |
1160 |
head = h; |
1161 |
VarHandle.fullFence(); |
1162 |
} |
1163 |
} |
1164 |
|
1165 |
/* ---------------- Serialization -------------- */ |
1166 |
|
1167 |
/** |
1168 |
* Saves this map to a stream (that is, serializes it). |
1169 |
* |
1170 |
* @param s the stream |
1171 |
* @throws java.io.IOException if an I/O error occurs |
1172 |
* @serialData The key (Object) and value (Object) for each |
1173 |
* key-value mapping represented by the map, followed by |
1174 |
* {@code null}. The key-value mappings are emitted in key-order |
1175 |
* (as determined by the Comparator, or by the keys' natural |
1176 |
* ordering if no Comparator). |
1177 |
*/ |
1178 |
private void writeObject(java.io.ObjectOutputStream s) |
1179 |
throws java.io.IOException { |
1180 |
// Write out the Comparator and any hidden stuff |
1181 |
s.defaultWriteObject(); |
1182 |
|
1183 |
// Write out keys and values (alternating) |
1184 |
Node<K,V> b, n; V v; |
1185 |
if ((b = baseHead()) != null) { |
1186 |
while ((n = b.next) != null) { |
1187 |
if ((v = n.val) != null) { |
1188 |
s.writeObject(n.key); |
1189 |
s.writeObject(v); |
1190 |
} |
1191 |
b = n; |
1192 |
} |
1193 |
} |
1194 |
s.writeObject(null); |
1195 |
} |
1196 |
|
1197 |
/** |
1198 |
* Reconstitutes this map from a stream (that is, deserializes it). |
1199 |
* @param s the stream |
1200 |
* @throws ClassNotFoundException if the class of a serialized object |
1201 |
* could not be found |
1202 |
* @throws java.io.IOException if an I/O error occurs |
1203 |
*/ |
1204 |
@SuppressWarnings("unchecked") |
1205 |
private void readObject(final java.io.ObjectInputStream s) |
1206 |
throws java.io.IOException, ClassNotFoundException { |
1207 |
// Read in the Comparator and any hidden stuff |
1208 |
s.defaultReadObject(); |
1209 |
|
1210 |
// Same idea as buildFromSorted |
1211 |
@SuppressWarnings("unchecked") |
1212 |
Index<K,V>[] preds = (Index<K,V>[])new Index<?,?>[64]; |
1213 |
Node<K,V> bp = new Node<K,V>(null, null, null); |
1214 |
Index<K,V> h = preds[0] = new Index<K,V>(bp, null, null); |
1215 |
Comparator<? super K> cmp = comparator; |
1216 |
K prevKey = null; |
1217 |
long count = 0; |
1218 |
|
1219 |
for (;;) { |
1220 |
K k = (K)s.readObject(); |
1221 |
if (k == null) |
1222 |
break; |
1223 |
V v = (V)s.readObject(); |
1224 |
if (v == null) |
1225 |
throw new NullPointerException(); |
1226 |
if (prevKey != null && cpr(cmp, prevKey, k) > 0) |
1227 |
throw new IllegalStateException("out of order"); |
1228 |
prevKey = k; |
1229 |
Node<K,V> z = new Node<K,V>(k, v, null); |
1230 |
bp = bp.next = z; |
1231 |
if ((++count & 3L) == 0L) { |
1232 |
long m = count >>> 2; |
1233 |
int i = 0; |
1234 |
Index<K,V> idx = null, q; |
1235 |
do { |
1236 |
idx = new Index<K,V>(z, idx, null); |
1237 |
if ((q = preds[i]) == null) |
1238 |
preds[i] = h = new Index<K,V>(h.node, h, idx); |
1239 |
else |
1240 |
preds[i] = q.right = idx; |
1241 |
} while (++i < preds.length && ((m >>>= 1) & 1L) != 0L); |
1242 |
} |
1243 |
} |
1244 |
if (count != 0L) { |
1245 |
VarHandle.releaseFence(); |
1246 |
addCount(count); |
1247 |
head = h; |
1248 |
VarHandle.fullFence(); |
1249 |
} |
1250 |
} |
1251 |
|
1252 |
/* ------ Map API methods ------ */ |
1253 |
|
1254 |
/** |
1255 |
* Returns {@code true} if this map contains a mapping for the specified |
1256 |
* key. |
1257 |
* |
1258 |
* @param key key whose presence in this map is to be tested |
1259 |
* @return {@code true} if this map contains a mapping for the specified key |
1260 |
* @throws ClassCastException if the specified key cannot be compared |
1261 |
* with the keys currently in the map |
1262 |
* @throws NullPointerException if the specified key is null |
1263 |
*/ |
1264 |
public boolean containsKey(Object key) { |
1265 |
return doGet(key) != null; |
1266 |
} |
1267 |
|
1268 |
/** |
1269 |
* Returns the value to which the specified key is mapped, |
1270 |
* or {@code null} if this map contains no mapping for the key. |
1271 |
* |
1272 |
* <p>More formally, if this map contains a mapping from a key |
1273 |
* {@code k} to a value {@code v} such that {@code key} compares |
1274 |
* equal to {@code k} according to the map's ordering, then this |
1275 |
* method returns {@code v}; otherwise it returns {@code null}. |
1276 |
* (There can be at most one such mapping.) |
1277 |
* |
1278 |
* @throws ClassCastException if the specified key cannot be compared |
1279 |
* with the keys currently in the map |
1280 |
* @throws NullPointerException if the specified key is null |
1281 |
*/ |
1282 |
public V get(Object key) { |
1283 |
return doGet(key); |
1284 |
} |
1285 |
|
1286 |
/** |
1287 |
* Returns the value to which the specified key is mapped, |
1288 |
* or the given defaultValue if this map contains no mapping for the key. |
1289 |
* |
1290 |
* @param key the key |
1291 |
* @param defaultValue the value to return if this map contains |
1292 |
* no mapping for the given key |
1293 |
* @return the mapping for the key, if present; else the defaultValue |
1294 |
* @throws NullPointerException if the specified key is null |
1295 |
* @since 1.8 |
1296 |
*/ |
1297 |
public V getOrDefault(Object key, V defaultValue) { |
1298 |
V v; |
1299 |
return (v = doGet(key)) == null ? defaultValue : v; |
1300 |
} |
1301 |
|
1302 |
/** |
1303 |
* Associates the specified value with the specified key in this map. |
1304 |
* If the map previously contained a mapping for the key, the old |
1305 |
* value is replaced. |
1306 |
* |
1307 |
* @param key key with which the specified value is to be associated |
1308 |
* @param value value to be associated with the specified key |
1309 |
* @return the previous value associated with the specified key, or |
1310 |
* {@code null} if there was no mapping for the key |
1311 |
* @throws ClassCastException if the specified key cannot be compared |
1312 |
* with the keys currently in the map |
1313 |
* @throws NullPointerException if the specified key or value is null |
1314 |
*/ |
1315 |
public V put(K key, V value) { |
1316 |
if (value == null) |
1317 |
throw new NullPointerException(); |
1318 |
return doPut(key, value, false); |
1319 |
} |
1320 |
|
1321 |
/** |
1322 |
* Removes the mapping for the specified key from this map if present. |
1323 |
* |
1324 |
* @param key key for which mapping should be removed |
1325 |
* @return the previous value associated with the specified key, or |
1326 |
* {@code null} if there was no mapping for the key |
1327 |
* @throws ClassCastException if the specified key cannot be compared |
1328 |
* with the keys currently in the map |
1329 |
* @throws NullPointerException if the specified key is null |
1330 |
*/ |
1331 |
public V remove(Object key) { |
1332 |
return doRemove(key, null); |
1333 |
} |
1334 |
|
1335 |
/** |
1336 |
* Returns {@code true} if this map maps one or more keys to the |
1337 |
* specified value. This operation requires time linear in the |
1338 |
* map size. Additionally, it is possible for the map to change |
1339 |
* during execution of this method, in which case the returned |
1340 |
* result may be inaccurate. |
1341 |
* |
1342 |
* @param value value whose presence in this map is to be tested |
1343 |
* @return {@code true} if a mapping to {@code value} exists; |
1344 |
* {@code false} otherwise |
1345 |
* @throws NullPointerException if the specified value is null |
1346 |
*/ |
1347 |
public boolean containsValue(Object value) { |
1348 |
if (value == null) |
1349 |
throw new NullPointerException(); |
1350 |
Node<K,V> b, n; V v; |
1351 |
if ((b = baseHead()) != null) { |
1352 |
while ((n = b.next) != null) { |
1353 |
if ((v = n.val) != null && value.equals(v)) |
1354 |
return true; |
1355 |
else |
1356 |
b = n; |
1357 |
} |
1358 |
} |
1359 |
return false; |
1360 |
} |
1361 |
|
1362 |
/** |
1363 |
* {@inheritDoc} |
1364 |
*/ |
1365 |
public int size() { |
1366 |
long c; |
1367 |
return ((baseHead() == null) ? 0 : |
1368 |
((c = getAdderCount()) >= Integer.MAX_VALUE) ? |
1369 |
Integer.MAX_VALUE : (int) c); |
1370 |
} |
1371 |
|
1372 |
/** |
1373 |
* {@inheritDoc} |
1374 |
*/ |
1375 |
public boolean isEmpty() { |
1376 |
return findFirst() == null; |
1377 |
} |
1378 |
|
1379 |
/** |
1380 |
* Removes all of the mappings from this map. |
1381 |
*/ |
1382 |
public void clear() { |
1383 |
Index<K,V> h, r, d; Node<K,V> b; |
1384 |
VarHandle.acquireFence(); |
1385 |
while ((h = head) != null) { |
1386 |
if ((r = h.right) != null) // remove indices |
1387 |
RIGHT.compareAndSet(h, r, null); |
1388 |
else if ((d = h.down) != null) // remove levels |
1389 |
HEAD.compareAndSet(this, h, d); |
1390 |
else { |
1391 |
long count = 0L; |
1392 |
if ((b = h.node) != null) { // remove nodes |
1393 |
Node<K,V> n; V v; |
1394 |
while ((n = b.next) != null) { |
1395 |
if ((v = n.val) != null && |
1396 |
VAL.compareAndSet(n, v, null)) { |
1397 |
--count; |
1398 |
v = null; |
1399 |
} |
1400 |
if (v == null) |
1401 |
unlinkNode(b, n); |
1402 |
} |
1403 |
} |
1404 |
if (count != 0L) |
1405 |
addCount(count); |
1406 |
else |
1407 |
break; |
1408 |
} |
1409 |
} |
1410 |
} |
1411 |
|
1412 |
/** |
1413 |
* If the specified key is not already associated with a value, |
1414 |
* attempts to compute its value using the given mapping function |
1415 |
* and enters it into this map unless {@code null}. The function |
1416 |
* is <em>NOT</em> guaranteed to be applied once atomically only |
1417 |
* if the value is not present. |
1418 |
* |
1419 |
* @param key key with which the specified value is to be associated |
1420 |
* @param mappingFunction the function to compute a value |
1421 |
* @return the current (existing or computed) value associated with |
1422 |
* the specified key, or null if the computed value is null |
1423 |
* @throws NullPointerException if the specified key is null |
1424 |
* or the mappingFunction is null |
1425 |
* @since 1.8 |
1426 |
*/ |
1427 |
public V computeIfAbsent(K key, |
1428 |
Function<? super K, ? extends V> mappingFunction) { |
1429 |
if (key == null || mappingFunction == null) |
1430 |
throw new NullPointerException(); |
1431 |
V v, p, r; |
1432 |
if ((v = doGet(key)) == null && |
1433 |
(r = mappingFunction.apply(key)) != null) |
1434 |
v = (p = doPut(key, r, true)) == null ? r : p; |
1435 |
return v; |
1436 |
} |
1437 |
|
1438 |
/** |
1439 |
* If the value for the specified key is present, attempts to |
1440 |
* compute a new mapping given the key and its current mapped |
1441 |
* value. The function is <em>NOT</em> guaranteed to be applied |
1442 |
* once atomically. |
1443 |
* |
1444 |
* @param key key with which a value may be associated |
1445 |
* @param remappingFunction the function to compute a value |
1446 |
* @return the new value associated with the specified key, or null if none |
1447 |
* @throws NullPointerException if the specified key is null |
1448 |
* or the remappingFunction is null |
1449 |
* @since 1.8 |
1450 |
*/ |
1451 |
public V computeIfPresent(K key, |
1452 |
BiFunction<? super K, ? super V, ? extends V> remappingFunction) { |
1453 |
if (key == null || remappingFunction == null) |
1454 |
throw new NullPointerException(); |
1455 |
Node<K,V> n; V v; |
1456 |
while ((n = findNode(key)) != null) { |
1457 |
if ((v = n.val) != null) { |
1458 |
V r = remappingFunction.apply(key, v); |
1459 |
if (r != null) { |
1460 |
if (VAL.compareAndSet(n, v, r)) |
1461 |
return r; |
1462 |
} |
1463 |
else if (doRemove(key, v) != null) |
1464 |
break; |
1465 |
} |
1466 |
} |
1467 |
return null; |
1468 |
} |
1469 |
|
1470 |
/** |
1471 |
* Attempts to compute a mapping for the specified key and its |
1472 |
* current mapped value (or {@code null} if there is no current |
1473 |
* mapping). The function is <em>NOT</em> guaranteed to be applied |
1474 |
* once atomically. |
1475 |
* |
1476 |
* @param key key with which the specified value is to be associated |
1477 |
* @param remappingFunction the function to compute a value |
1478 |
* @return the new value associated with the specified key, or null if none |
1479 |
* @throws NullPointerException if the specified key is null |
1480 |
* or the remappingFunction is null |
1481 |
* @since 1.8 |
1482 |
*/ |
1483 |
public V compute(K key, |
1484 |
BiFunction<? super K, ? super V, ? extends V> remappingFunction) { |
1485 |
if (key == null || remappingFunction == null) |
1486 |
throw new NullPointerException(); |
1487 |
for (;;) { |
1488 |
Node<K,V> n; V v; V r; |
1489 |
if ((n = findNode(key)) == null) { |
1490 |
if ((r = remappingFunction.apply(key, null)) == null) |
1491 |
break; |
1492 |
if (doPut(key, r, true) == null) |
1493 |
return r; |
1494 |
} |
1495 |
else if ((v = n.val) != null) { |
1496 |
if ((r = remappingFunction.apply(key, v)) != null) { |
1497 |
if (VAL.compareAndSet(n, v, r)) |
1498 |
return r; |
1499 |
} |
1500 |
else if (doRemove(key, v) != null) |
1501 |
break; |
1502 |
} |
1503 |
} |
1504 |
return null; |
1505 |
} |
1506 |
|
1507 |
/** |
1508 |
* If the specified key is not already associated with a value, |
1509 |
* associates it with the given value. Otherwise, replaces the |
1510 |
* value with the results of the given remapping function, or |
1511 |
* removes if {@code null}. The function is <em>NOT</em> |
1512 |
* guaranteed to be applied once atomically. |
1513 |
* |
1514 |
* @param key key with which the specified value is to be associated |
1515 |
* @param value the value to use if absent |
1516 |
* @param remappingFunction the function to recompute a value if present |
1517 |
* @return the new value associated with the specified key, or null if none |
1518 |
* @throws NullPointerException if the specified key or value is null |
1519 |
* or the remappingFunction is null |
1520 |
* @since 1.8 |
1521 |
*/ |
1522 |
public V merge(K key, V value, |
1523 |
BiFunction<? super V, ? super V, ? extends V> remappingFunction) { |
1524 |
if (key == null || value == null || remappingFunction == null) |
1525 |
throw new NullPointerException(); |
1526 |
for (;;) { |
1527 |
Node<K,V> n; V v; V r; |
1528 |
if ((n = findNode(key)) == null) { |
1529 |
if (doPut(key, value, true) == null) |
1530 |
return value; |
1531 |
} |
1532 |
else if ((v = n.val) != null) { |
1533 |
if ((r = remappingFunction.apply(v, value)) != null) { |
1534 |
if (VAL.compareAndSet(n, v, r)) |
1535 |
return r; |
1536 |
} |
1537 |
else if (doRemove(key, v) != null) |
1538 |
return null; |
1539 |
} |
1540 |
} |
1541 |
} |
1542 |
|
1543 |
/* ---------------- View methods -------------- */ |
1544 |
|
1545 |
/* |
1546 |
* Note: Lazy initialization works for views because view classes |
1547 |
* are stateless/immutable so it doesn't matter wrt correctness if |
1548 |
* more than one is created (which will only rarely happen). Even |
1549 |
* so, the following idiom conservatively ensures that the method |
1550 |
* returns the one it created if it does so, not one created by |
1551 |
* another racing thread. |
1552 |
*/ |
1553 |
|
1554 |
/** |
1555 |
* Returns a {@link NavigableSet} view of the keys contained in this map. |
1556 |
* |
1557 |
* <p>The set's iterator returns the keys in ascending order. |
1558 |
* The set's spliterator additionally reports {@link Spliterator#CONCURRENT}, |
1559 |
* {@link Spliterator#NONNULL}, {@link Spliterator#SORTED} and |
1560 |
* {@link Spliterator#ORDERED}, with an encounter order that is ascending |
1561 |
* key order. |
1562 |
* |
1563 |
* <p>The {@linkplain Spliterator#getComparator() spliterator's comparator} |
1564 |
* is {@code null} if the {@linkplain #comparator() map's comparator} |
1565 |
* is {@code null}. |
1566 |
* Otherwise, the spliterator's comparator is the same as or imposes the |
1567 |
* same total ordering as the map's comparator. |
1568 |
* |
1569 |
* <p>The set is backed by the map, so changes to the map are |
1570 |
* reflected in the set, and vice-versa. The set supports element |
1571 |
* removal, which removes the corresponding mapping from the map, |
1572 |
* via the {@code Iterator.remove}, {@code Set.remove}, |
1573 |
* {@code removeAll}, {@code retainAll}, and {@code clear} |
1574 |
* operations. It does not support the {@code add} or {@code addAll} |
1575 |
* operations. |
1576 |
* |
1577 |
* <p>The view's iterators and spliterators are |
1578 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
1579 |
* |
1580 |
* <p>This method is equivalent to method {@code navigableKeySet}. |
1581 |
* |
1582 |
* @return a navigable set view of the keys in this map |
1583 |
*/ |
1584 |
public NavigableSet<K> keySet() { |
1585 |
KeySet<K,V> ks; |
1586 |
if ((ks = keySet) != null) return ks; |
1587 |
return keySet = new KeySet<>(this); |
1588 |
} |
1589 |
|
1590 |
public NavigableSet<K> navigableKeySet() { |
1591 |
KeySet<K,V> ks; |
1592 |
if ((ks = keySet) != null) return ks; |
1593 |
return keySet = new KeySet<>(this); |
1594 |
} |
1595 |
|
1596 |
/** |
1597 |
* Returns a {@link Collection} view of the values contained in this map. |
1598 |
* <p>The collection's iterator returns the values in ascending order |
1599 |
* of the corresponding keys. The collections's spliterator additionally |
1600 |
* reports {@link Spliterator#CONCURRENT}, {@link Spliterator#NONNULL} and |
1601 |
* {@link Spliterator#ORDERED}, with an encounter order that is ascending |
1602 |
* order of the corresponding keys. |
1603 |
* |
1604 |
* <p>The collection is backed by the map, so changes to the map are |
1605 |
* reflected in the collection, and vice-versa. The collection |
1606 |
* supports element removal, which removes the corresponding |
1607 |
* mapping from the map, via the {@code Iterator.remove}, |
1608 |
* {@code Collection.remove}, {@code removeAll}, |
1609 |
* {@code retainAll} and {@code clear} operations. It does not |
1610 |
* support the {@code add} or {@code addAll} operations. |
1611 |
* |
1612 |
* <p>The view's iterators and spliterators are |
1613 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
1614 |
*/ |
1615 |
public Collection<V> values() { |
1616 |
Values<K,V> vs; |
1617 |
if ((vs = values) != null) return vs; |
1618 |
return values = new Values<>(this); |
1619 |
} |
1620 |
|
1621 |
/** |
1622 |
* Returns a {@link Set} view of the mappings contained in this map. |
1623 |
* |
1624 |
* <p>The set's iterator returns the entries in ascending key order. The |
1625 |
* set's spliterator additionally reports {@link Spliterator#CONCURRENT}, |
1626 |
* {@link Spliterator#NONNULL}, {@link Spliterator#SORTED} and |
1627 |
* {@link Spliterator#ORDERED}, with an encounter order that is ascending |
1628 |
* key order. |
1629 |
* |
1630 |
* <p>The set is backed by the map, so changes to the map are |
1631 |
* reflected in the set, and vice-versa. The set supports element |
1632 |
* removal, which removes the corresponding mapping from the map, |
1633 |
* via the {@code Iterator.remove}, {@code Set.remove}, |
1634 |
* {@code removeAll}, {@code retainAll} and {@code clear} |
1635 |
* operations. It does not support the {@code add} or |
1636 |
* {@code addAll} operations. |
1637 |
* |
1638 |
* <p>The view's iterators and spliterators are |
1639 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
1640 |
* |
1641 |
* <p>The {@code Map.Entry} elements traversed by the {@code iterator} |
1642 |
* or {@code spliterator} do <em>not</em> support the {@code setValue} |
1643 |
* operation. |
1644 |
* |
1645 |
* @return a set view of the mappings contained in this map, |
1646 |
* sorted in ascending key order |
1647 |
*/ |
1648 |
public Set<Map.Entry<K,V>> entrySet() { |
1649 |
EntrySet<K,V> es; |
1650 |
if ((es = entrySet) != null) return es; |
1651 |
return entrySet = new EntrySet<K,V>(this); |
1652 |
} |
1653 |
|
1654 |
public ConcurrentNavigableMap<K,V> descendingMap() { |
1655 |
ConcurrentNavigableMap<K,V> dm; |
1656 |
if ((dm = descendingMap) != null) return dm; |
1657 |
return descendingMap = |
1658 |
new SubMap<K,V>(this, null, false, null, false, true); |
1659 |
} |
1660 |
|
1661 |
public NavigableSet<K> descendingKeySet() { |
1662 |
return descendingMap().navigableKeySet(); |
1663 |
} |
1664 |
|
1665 |
/* ---------------- AbstractMap Overrides -------------- */ |
1666 |
|
1667 |
/** |
1668 |
* Compares the specified object with this map for equality. |
1669 |
* Returns {@code true} if the given object is also a map and the |
1670 |
* two maps represent the same mappings. More formally, two maps |
1671 |
* {@code m1} and {@code m2} represent the same mappings if |
1672 |
* {@code m1.entrySet().equals(m2.entrySet())}. This |
1673 |
* operation may return misleading results if either map is |
1674 |
* concurrently modified during execution of this method. |
1675 |
* |
1676 |
* @param o object to be compared for equality with this map |
1677 |
* @return {@code true} if the specified object is equal to this map |
1678 |
*/ |
1679 |
public boolean equals(Object o) { |
1680 |
if (o == this) |
1681 |
return true; |
1682 |
if (!(o instanceof Map)) |
1683 |
return false; |
1684 |
Map<?,?> m = (Map<?,?>) o; |
1685 |
try { |
1686 |
Comparator<? super K> cmp = comparator; |
1687 |
// See JDK-8223553 for Iterator type wildcard rationale |
1688 |
Iterator<? extends Map.Entry<?,?>> it = m.entrySet().iterator(); |
1689 |
if (m instanceof SortedMap && |
1690 |
((SortedMap<?,?>)m).comparator() == cmp) { |
1691 |
Node<K,V> b, n; |
1692 |
if ((b = baseHead()) != null) { |
1693 |
while ((n = b.next) != null) { |
1694 |
K k; V v; |
1695 |
if ((v = n.val) != null && (k = n.key) != null) { |
1696 |
if (!it.hasNext()) |
1697 |
return false; |
1698 |
Map.Entry<?,?> e = it.next(); |
1699 |
Object mk = e.getKey(); |
1700 |
Object mv = e.getValue(); |
1701 |
if (mk == null || mv == null) |
1702 |
return false; |
1703 |
try { |
1704 |
if (cpr(cmp, k, mk) != 0) |
1705 |
return false; |
1706 |
} catch (ClassCastException cce) { |
1707 |
return false; |
1708 |
} |
1709 |
if (!mv.equals(v)) |
1710 |
return false; |
1711 |
} |
1712 |
b = n; |
1713 |
} |
1714 |
} |
1715 |
return !it.hasNext(); |
1716 |
} |
1717 |
else { |
1718 |
while (it.hasNext()) { |
1719 |
V v; |
1720 |
Map.Entry<?,?> e = it.next(); |
1721 |
Object mk = e.getKey(); |
1722 |
Object mv = e.getValue(); |
1723 |
if (mk == null || mv == null || |
1724 |
(v = get(mk)) == null || !v.equals(mv)) |
1725 |
return false; |
1726 |
} |
1727 |
Node<K,V> b, n; |
1728 |
if ((b = baseHead()) != null) { |
1729 |
K k; V v; Object mv; |
1730 |
while ((n = b.next) != null) { |
1731 |
if ((v = n.val) != null && (k = n.key) != null && |
1732 |
((mv = m.get(k)) == null || !mv.equals(v))) |
1733 |
return false; |
1734 |
b = n; |
1735 |
} |
1736 |
} |
1737 |
return true; |
1738 |
} |
1739 |
} catch (ClassCastException | NullPointerException unused) { |
1740 |
return false; |
1741 |
} |
1742 |
} |
1743 |
|
1744 |
/* ------ ConcurrentMap API methods ------ */ |
1745 |
|
1746 |
/** |
1747 |
* {@inheritDoc} |
1748 |
* |
1749 |
* @return the previous value associated with the specified key, |
1750 |
* or {@code null} if there was no mapping for the key |
1751 |
* @throws ClassCastException if the specified key cannot be compared |
1752 |
* with the keys currently in the map |
1753 |
* @throws NullPointerException if the specified key or value is null |
1754 |
*/ |
1755 |
public V putIfAbsent(K key, V value) { |
1756 |
if (value == null) |
1757 |
throw new NullPointerException(); |
1758 |
return doPut(key, value, true); |
1759 |
} |
1760 |
|
1761 |
/** |
1762 |
* {@inheritDoc} |
1763 |
* |
1764 |
* @throws ClassCastException if the specified key cannot be compared |
1765 |
* with the keys currently in the map |
1766 |
* @throws NullPointerException if the specified key is null |
1767 |
*/ |
1768 |
public boolean remove(Object key, Object value) { |
1769 |
if (key == null) |
1770 |
throw new NullPointerException(); |
1771 |
return value != null && doRemove(key, value) != null; |
1772 |
} |
1773 |
|
1774 |
/** |
1775 |
* {@inheritDoc} |
1776 |
* |
1777 |
* @throws ClassCastException if the specified key cannot be compared |
1778 |
* with the keys currently in the map |
1779 |
* @throws NullPointerException if any of the arguments are null |
1780 |
*/ |
1781 |
public boolean replace(K key, V oldValue, V newValue) { |
1782 |
if (key == null || oldValue == null || newValue == null) |
1783 |
throw new NullPointerException(); |
1784 |
for (;;) { |
1785 |
Node<K,V> n; V v; |
1786 |
if ((n = findNode(key)) == null) |
1787 |
return false; |
1788 |
if ((v = n.val) != null) { |
1789 |
if (!oldValue.equals(v)) |
1790 |
return false; |
1791 |
if (VAL.compareAndSet(n, v, newValue)) |
1792 |
return true; |
1793 |
} |
1794 |
} |
1795 |
} |
1796 |
|
1797 |
/** |
1798 |
* {@inheritDoc} |
1799 |
* |
1800 |
* @return the previous value associated with the specified key, |
1801 |
* or {@code null} if there was no mapping for the key |
1802 |
* @throws ClassCastException if the specified key cannot be compared |
1803 |
* with the keys currently in the map |
1804 |
* @throws NullPointerException if the specified key or value is null |
1805 |
*/ |
1806 |
public V replace(K key, V value) { |
1807 |
if (key == null || value == null) |
1808 |
throw new NullPointerException(); |
1809 |
for (;;) { |
1810 |
Node<K,V> n; V v; |
1811 |
if ((n = findNode(key)) == null) |
1812 |
return null; |
1813 |
if ((v = n.val) != null && VAL.compareAndSet(n, v, value)) |
1814 |
return v; |
1815 |
} |
1816 |
} |
1817 |
|
1818 |
/* ------ SortedMap API methods ------ */ |
1819 |
|
1820 |
public Comparator<? super K> comparator() { |
1821 |
return comparator; |
1822 |
} |
1823 |
|
1824 |
/** |
1825 |
* @throws NoSuchElementException {@inheritDoc} |
1826 |
*/ |
1827 |
public K firstKey() { |
1828 |
Node<K,V> n = findFirst(); |
1829 |
if (n == null) |
1830 |
throw new NoSuchElementException(); |
1831 |
return n.key; |
1832 |
} |
1833 |
|
1834 |
/** |
1835 |
* @throws NoSuchElementException {@inheritDoc} |
1836 |
*/ |
1837 |
public K lastKey() { |
1838 |
Node<K,V> n = findLast(); |
1839 |
if (n == null) |
1840 |
throw new NoSuchElementException(); |
1841 |
return n.key; |
1842 |
} |
1843 |
|
1844 |
/** |
1845 |
* @throws ClassCastException {@inheritDoc} |
1846 |
* @throws NullPointerException if {@code fromKey} or {@code toKey} is null |
1847 |
* @throws IllegalArgumentException {@inheritDoc} |
1848 |
*/ |
1849 |
public ConcurrentNavigableMap<K,V> subMap(K fromKey, |
1850 |
boolean fromInclusive, |
1851 |
K toKey, |
1852 |
boolean toInclusive) { |
1853 |
if (fromKey == null || toKey == null) |
1854 |
throw new NullPointerException(); |
1855 |
return new SubMap<K,V> |
1856 |
(this, fromKey, fromInclusive, toKey, toInclusive, false); |
1857 |
} |
1858 |
|
1859 |
/** |
1860 |
* @throws ClassCastException {@inheritDoc} |
1861 |
* @throws NullPointerException if {@code toKey} is null |
1862 |
* @throws IllegalArgumentException {@inheritDoc} |
1863 |
*/ |
1864 |
public ConcurrentNavigableMap<K,V> headMap(K toKey, |
1865 |
boolean inclusive) { |
1866 |
if (toKey == null) |
1867 |
throw new NullPointerException(); |
1868 |
return new SubMap<K,V> |
1869 |
(this, null, false, toKey, inclusive, false); |
1870 |
} |
1871 |
|
1872 |
/** |
1873 |
* @throws ClassCastException {@inheritDoc} |
1874 |
* @throws NullPointerException if {@code fromKey} is null |
1875 |
* @throws IllegalArgumentException {@inheritDoc} |
1876 |
*/ |
1877 |
public ConcurrentNavigableMap<K,V> tailMap(K fromKey, |
1878 |
boolean inclusive) { |
1879 |
if (fromKey == null) |
1880 |
throw new NullPointerException(); |
1881 |
return new SubMap<K,V> |
1882 |
(this, fromKey, inclusive, null, false, false); |
1883 |
} |
1884 |
|
1885 |
/** |
1886 |
* @throws ClassCastException {@inheritDoc} |
1887 |
* @throws NullPointerException if {@code fromKey} or {@code toKey} is null |
1888 |
* @throws IllegalArgumentException {@inheritDoc} |
1889 |
*/ |
1890 |
public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) { |
1891 |
return subMap(fromKey, true, toKey, false); |
1892 |
} |
1893 |
|
1894 |
/** |
1895 |
* @throws ClassCastException {@inheritDoc} |
1896 |
* @throws NullPointerException if {@code toKey} is null |
1897 |
* @throws IllegalArgumentException {@inheritDoc} |
1898 |
*/ |
1899 |
public ConcurrentNavigableMap<K,V> headMap(K toKey) { |
1900 |
return headMap(toKey, false); |
1901 |
} |
1902 |
|
1903 |
/** |
1904 |
* @throws ClassCastException {@inheritDoc} |
1905 |
* @throws NullPointerException if {@code fromKey} is null |
1906 |
* @throws IllegalArgumentException {@inheritDoc} |
1907 |
*/ |
1908 |
public ConcurrentNavigableMap<K,V> tailMap(K fromKey) { |
1909 |
return tailMap(fromKey, true); |
1910 |
} |
1911 |
|
1912 |
/* ---------------- Relational operations -------------- */ |
1913 |
|
1914 |
/** |
1915 |
* Returns a key-value mapping associated with the greatest key |
1916 |
* strictly less than the given key, or {@code null} if there is |
1917 |
* no such key. The returned entry does <em>not</em> support the |
1918 |
* {@code Entry.setValue} method. |
1919 |
* |
1920 |
* @throws ClassCastException {@inheritDoc} |
1921 |
* @throws NullPointerException if the specified key is null |
1922 |
*/ |
1923 |
public Map.Entry<K,V> lowerEntry(K key) { |
1924 |
return findNearEntry(key, LT, comparator); |
1925 |
} |
1926 |
|
1927 |
/** |
1928 |
* @throws ClassCastException {@inheritDoc} |
1929 |
* @throws NullPointerException if the specified key is null |
1930 |
*/ |
1931 |
public K lowerKey(K key) { |
1932 |
Node<K,V> n = findNear(key, LT, comparator); |
1933 |
return (n == null) ? null : n.key; |
1934 |
} |
1935 |
|
1936 |
/** |
1937 |
* Returns a key-value mapping associated with the greatest key |
1938 |
* less than or equal to the given key, or {@code null} if there |
1939 |
* is no such key. The returned entry does <em>not</em> support |
1940 |
* the {@code Entry.setValue} method. |
1941 |
* |
1942 |
* @param key the key |
1943 |
* @throws ClassCastException {@inheritDoc} |
1944 |
* @throws NullPointerException if the specified key is null |
1945 |
*/ |
1946 |
public Map.Entry<K,V> floorEntry(K key) { |
1947 |
return findNearEntry(key, LT|EQ, comparator); |
1948 |
} |
1949 |
|
1950 |
/** |
1951 |
* @param key the key |
1952 |
* @throws ClassCastException {@inheritDoc} |
1953 |
* @throws NullPointerException if the specified key is null |
1954 |
*/ |
1955 |
public K floorKey(K key) { |
1956 |
Node<K,V> n = findNear(key, LT|EQ, comparator); |
1957 |
return (n == null) ? null : n.key; |
1958 |
} |
1959 |
|
1960 |
/** |
1961 |
* Returns a key-value mapping associated with the least key |
1962 |
* greater than or equal to the given key, or {@code null} if |
1963 |
* there is no such entry. The returned entry does <em>not</em> |
1964 |
* support the {@code Entry.setValue} method. |
1965 |
* |
1966 |
* @throws ClassCastException {@inheritDoc} |
1967 |
* @throws NullPointerException if the specified key is null |
1968 |
*/ |
1969 |
public Map.Entry<K,V> ceilingEntry(K key) { |
1970 |
return findNearEntry(key, GT|EQ, comparator); |
1971 |
} |
1972 |
|
1973 |
/** |
1974 |
* @throws ClassCastException {@inheritDoc} |
1975 |
* @throws NullPointerException if the specified key is null |
1976 |
*/ |
1977 |
public K ceilingKey(K key) { |
1978 |
Node<K,V> n = findNear(key, GT|EQ, comparator); |
1979 |
return (n == null) ? null : n.key; |
1980 |
} |
1981 |
|
1982 |
/** |
1983 |
* Returns a key-value mapping associated with the least key |
1984 |
* strictly greater than the given key, or {@code null} if there |
1985 |
* is no such key. The returned entry does <em>not</em> support |
1986 |
* the {@code Entry.setValue} method. |
1987 |
* |
1988 |
* @param key the key |
1989 |
* @throws ClassCastException {@inheritDoc} |
1990 |
* @throws NullPointerException if the specified key is null |
1991 |
*/ |
1992 |
public Map.Entry<K,V> higherEntry(K key) { |
1993 |
return findNearEntry(key, GT, comparator); |
1994 |
} |
1995 |
|
1996 |
/** |
1997 |
* @param key the key |
1998 |
* @throws ClassCastException {@inheritDoc} |
1999 |
* @throws NullPointerException if the specified key is null |
2000 |
*/ |
2001 |
public K higherKey(K key) { |
2002 |
Node<K,V> n = findNear(key, GT, comparator); |
2003 |
return (n == null) ? null : n.key; |
2004 |
} |
2005 |
|
2006 |
/** |
2007 |
* Returns a key-value mapping associated with the least |
2008 |
* key in this map, or {@code null} if the map is empty. |
2009 |
* The returned entry does <em>not</em> support |
2010 |
* the {@code Entry.setValue} method. |
2011 |
*/ |
2012 |
public Map.Entry<K,V> firstEntry() { |
2013 |
return findFirstEntry(); |
2014 |
} |
2015 |
|
2016 |
/** |
2017 |
* Returns a key-value mapping associated with the greatest |
2018 |
* key in this map, or {@code null} if the map is empty. |
2019 |
* The returned entry does <em>not</em> support |
2020 |
* the {@code Entry.setValue} method. |
2021 |
*/ |
2022 |
public Map.Entry<K,V> lastEntry() { |
2023 |
return findLastEntry(); |
2024 |
} |
2025 |
|
2026 |
/** |
2027 |
* Removes and returns a key-value mapping associated with |
2028 |
* the least key in this map, or {@code null} if the map is empty. |
2029 |
* The returned entry does <em>not</em> support |
2030 |
* the {@code Entry.setValue} method. |
2031 |
*/ |
2032 |
public Map.Entry<K,V> pollFirstEntry() { |
2033 |
return doRemoveFirstEntry(); |
2034 |
} |
2035 |
|
2036 |
/** |
2037 |
* Removes and returns a key-value mapping associated with |
2038 |
* the greatest key in this map, or {@code null} if the map is empty. |
2039 |
* The returned entry does <em>not</em> support |
2040 |
* the {@code Entry.setValue} method. |
2041 |
*/ |
2042 |
public Map.Entry<K,V> pollLastEntry() { |
2043 |
return doRemoveLastEntry(); |
2044 |
} |
2045 |
|
2046 |
/* ---------------- Iterators -------------- */ |
2047 |
|
2048 |
/** |
2049 |
* Base of iterator classes |
2050 |
*/ |
2051 |
abstract class Iter<T> implements Iterator<T> { |
2052 |
/** the last node returned by next() */ |
2053 |
Node<K,V> lastReturned; |
2054 |
/** the next node to return from next(); */ |
2055 |
Node<K,V> next; |
2056 |
/** Cache of next value field to maintain weak consistency */ |
2057 |
V nextValue; |
2058 |
|
2059 |
/** Initializes ascending iterator for entire range. */ |
2060 |
Iter() { |
2061 |
advance(baseHead()); |
2062 |
} |
2063 |
|
2064 |
public final boolean hasNext() { |
2065 |
return next != null; |
2066 |
} |
2067 |
|
2068 |
/** Advances next to higher entry. */ |
2069 |
final void advance(Node<K,V> b) { |
2070 |
Node<K,V> n = null; |
2071 |
V v = null; |
2072 |
if ((lastReturned = b) != null) { |
2073 |
while ((n = b.next) != null && (v = n.val) == null) |
2074 |
b = n; |
2075 |
} |
2076 |
nextValue = v; |
2077 |
next = n; |
2078 |
} |
2079 |
|
2080 |
public final void remove() { |
2081 |
Node<K,V> n; K k; |
2082 |
if ((n = lastReturned) == null || (k = n.key) == null) |
2083 |
throw new IllegalStateException(); |
2084 |
// It would not be worth all of the overhead to directly |
2085 |
// unlink from here. Using remove is fast enough. |
2086 |
ConcurrentSkipListMap.this.remove(k); |
2087 |
lastReturned = null; |
2088 |
} |
2089 |
} |
2090 |
|
2091 |
final class ValueIterator extends Iter<V> { |
2092 |
public V next() { |
2093 |
V v; |
2094 |
if ((v = nextValue) == null) |
2095 |
throw new NoSuchElementException(); |
2096 |
advance(next); |
2097 |
return v; |
2098 |
} |
2099 |
} |
2100 |
|
2101 |
final class KeyIterator extends Iter<K> { |
2102 |
public K next() { |
2103 |
Node<K,V> n; |
2104 |
if ((n = next) == null) |
2105 |
throw new NoSuchElementException(); |
2106 |
K k = n.key; |
2107 |
advance(n); |
2108 |
return k; |
2109 |
} |
2110 |
} |
2111 |
|
2112 |
final class EntryIterator extends Iter<Map.Entry<K,V>> { |
2113 |
public Map.Entry<K,V> next() { |
2114 |
Node<K,V> n; |
2115 |
if ((n = next) == null) |
2116 |
throw new NoSuchElementException(); |
2117 |
K k = n.key; |
2118 |
V v = nextValue; |
2119 |
advance(n); |
2120 |
return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); |
2121 |
} |
2122 |
} |
2123 |
|
2124 |
/* ---------------- View Classes -------------- */ |
2125 |
|
2126 |
/* |
2127 |
* View classes are static, delegating to a ConcurrentNavigableMap |
2128 |
* to allow use by SubMaps, which outweighs the ugliness of |
2129 |
* needing type-tests for Iterator methods. |
2130 |
*/ |
2131 |
|
2132 |
static final <E> List<E> toList(Collection<E> c) { |
2133 |
// Using size() here would be a pessimization. |
2134 |
ArrayList<E> list = new ArrayList<E>(); |
2135 |
for (E e : c) |
2136 |
list.add(e); |
2137 |
return list; |
2138 |
} |
2139 |
|
2140 |
static final class KeySet<K,V> |
2141 |
extends AbstractSet<K> implements NavigableSet<K> { |
2142 |
final ConcurrentNavigableMap<K,V> m; |
2143 |
KeySet(ConcurrentNavigableMap<K,V> map) { m = map; } |
2144 |
public int size() { return m.size(); } |
2145 |
public boolean isEmpty() { return m.isEmpty(); } |
2146 |
public boolean contains(Object o) { return m.containsKey(o); } |
2147 |
public boolean remove(Object o) { return m.remove(o) != null; } |
2148 |
public void clear() { m.clear(); } |
2149 |
public K lower(K e) { return m.lowerKey(e); } |
2150 |
public K floor(K e) { return m.floorKey(e); } |
2151 |
public K ceiling(K e) { return m.ceilingKey(e); } |
2152 |
public K higher(K e) { return m.higherKey(e); } |
2153 |
public Comparator<? super K> comparator() { return m.comparator(); } |
2154 |
public K first() { return m.firstKey(); } |
2155 |
public K last() { return m.lastKey(); } |
2156 |
public K pollFirst() { |
2157 |
Map.Entry<K,V> e = m.pollFirstEntry(); |
2158 |
return (e == null) ? null : e.getKey(); |
2159 |
} |
2160 |
public K pollLast() { |
2161 |
Map.Entry<K,V> e = m.pollLastEntry(); |
2162 |
return (e == null) ? null : e.getKey(); |
2163 |
} |
2164 |
public Iterator<K> iterator() { |
2165 |
return (m instanceof ConcurrentSkipListMap) |
2166 |
? ((ConcurrentSkipListMap<K,V>)m).new KeyIterator() |
2167 |
: ((SubMap<K,V>)m).new SubMapKeyIterator(); |
2168 |
} |
2169 |
public boolean equals(Object o) { |
2170 |
if (o == this) |
2171 |
return true; |
2172 |
if (!(o instanceof Set)) |
2173 |
return false; |
2174 |
Collection<?> c = (Collection<?>) o; |
2175 |
try { |
2176 |
return containsAll(c) && c.containsAll(this); |
2177 |
} catch (ClassCastException | NullPointerException unused) { |
2178 |
return false; |
2179 |
} |
2180 |
} |
2181 |
public Object[] toArray() { return toList(this).toArray(); } |
2182 |
public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } |
2183 |
public Iterator<K> descendingIterator() { |
2184 |
return descendingSet().iterator(); |
2185 |
} |
2186 |
public NavigableSet<K> subSet(K fromElement, |
2187 |
boolean fromInclusive, |
2188 |
K toElement, |
2189 |
boolean toInclusive) { |
2190 |
return new KeySet<>(m.subMap(fromElement, fromInclusive, |
2191 |
toElement, toInclusive)); |
2192 |
} |
2193 |
public NavigableSet<K> headSet(K toElement, boolean inclusive) { |
2194 |
return new KeySet<>(m.headMap(toElement, inclusive)); |
2195 |
} |
2196 |
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) { |
2197 |
return new KeySet<>(m.tailMap(fromElement, inclusive)); |
2198 |
} |
2199 |
public NavigableSet<K> subSet(K fromElement, K toElement) { |
2200 |
return subSet(fromElement, true, toElement, false); |
2201 |
} |
2202 |
public NavigableSet<K> headSet(K toElement) { |
2203 |
return headSet(toElement, false); |
2204 |
} |
2205 |
public NavigableSet<K> tailSet(K fromElement) { |
2206 |
return tailSet(fromElement, true); |
2207 |
} |
2208 |
public NavigableSet<K> descendingSet() { |
2209 |
return new KeySet<>(m.descendingMap()); |
2210 |
} |
2211 |
|
2212 |
public Spliterator<K> spliterator() { |
2213 |
return (m instanceof ConcurrentSkipListMap) |
2214 |
? ((ConcurrentSkipListMap<K,V>)m).keySpliterator() |
2215 |
: ((SubMap<K,V>)m).new SubMapKeyIterator(); |
2216 |
} |
2217 |
} |
2218 |
|
2219 |
static final class Values<K,V> extends AbstractCollection<V> { |
2220 |
final ConcurrentNavigableMap<K,V> m; |
2221 |
Values(ConcurrentNavigableMap<K,V> map) { |
2222 |
m = map; |
2223 |
} |
2224 |
public Iterator<V> iterator() { |
2225 |
return (m instanceof ConcurrentSkipListMap) |
2226 |
? ((ConcurrentSkipListMap<K,V>)m).new ValueIterator() |
2227 |
: ((SubMap<K,V>)m).new SubMapValueIterator(); |
2228 |
} |
2229 |
public int size() { return m.size(); } |
2230 |
public boolean isEmpty() { return m.isEmpty(); } |
2231 |
public boolean contains(Object o) { return m.containsValue(o); } |
2232 |
public void clear() { m.clear(); } |
2233 |
public Object[] toArray() { return toList(this).toArray(); } |
2234 |
public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } |
2235 |
|
2236 |
public Spliterator<V> spliterator() { |
2237 |
return (m instanceof ConcurrentSkipListMap) |
2238 |
? ((ConcurrentSkipListMap<K,V>)m).valueSpliterator() |
2239 |
: ((SubMap<K,V>)m).new SubMapValueIterator(); |
2240 |
} |
2241 |
|
2242 |
public boolean removeIf(Predicate<? super V> filter) { |
2243 |
if (filter == null) throw new NullPointerException(); |
2244 |
if (m instanceof ConcurrentSkipListMap) |
2245 |
return ((ConcurrentSkipListMap<K,V>)m).removeValueIf(filter); |
2246 |
// else use iterator |
2247 |
Iterator<Map.Entry<K,V>> it = |
2248 |
((SubMap<K,V>)m).new SubMapEntryIterator(); |
2249 |
boolean removed = false; |
2250 |
while (it.hasNext()) { |
2251 |
Map.Entry<K,V> e = it.next(); |
2252 |
V v = e.getValue(); |
2253 |
if (filter.test(v) && m.remove(e.getKey(), v)) |
2254 |
removed = true; |
2255 |
} |
2256 |
return removed; |
2257 |
} |
2258 |
} |
2259 |
|
2260 |
static final class EntrySet<K,V> extends AbstractSet<Map.Entry<K,V>> { |
2261 |
final ConcurrentNavigableMap<K,V> m; |
2262 |
EntrySet(ConcurrentNavigableMap<K,V> map) { |
2263 |
m = map; |
2264 |
} |
2265 |
public Iterator<Map.Entry<K,V>> iterator() { |
2266 |
return (m instanceof ConcurrentSkipListMap) |
2267 |
? ((ConcurrentSkipListMap<K,V>)m).new EntryIterator() |
2268 |
: ((SubMap<K,V>)m).new SubMapEntryIterator(); |
2269 |
} |
2270 |
|
2271 |
public boolean contains(Object o) { |
2272 |
if (!(o instanceof Map.Entry)) |
2273 |
return false; |
2274 |
Map.Entry<?,?> e = (Map.Entry<?,?>)o; |
2275 |
V v = m.get(e.getKey()); |
2276 |
return v != null && v.equals(e.getValue()); |
2277 |
} |
2278 |
public boolean remove(Object o) { |
2279 |
if (!(o instanceof Map.Entry)) |
2280 |
return false; |
2281 |
Map.Entry<?,?> e = (Map.Entry<?,?>)o; |
2282 |
return m.remove(e.getKey(), |
2283 |
e.getValue()); |
2284 |
} |
2285 |
public boolean isEmpty() { |
2286 |
return m.isEmpty(); |
2287 |
} |
2288 |
public int size() { |
2289 |
return m.size(); |
2290 |
} |
2291 |
public void clear() { |
2292 |
m.clear(); |
2293 |
} |
2294 |
public boolean equals(Object o) { |
2295 |
if (o == this) |
2296 |
return true; |
2297 |
if (!(o instanceof Set)) |
2298 |
return false; |
2299 |
Collection<?> c = (Collection<?>) o; |
2300 |
try { |
2301 |
return containsAll(c) && c.containsAll(this); |
2302 |
} catch (ClassCastException | NullPointerException unused) { |
2303 |
return false; |
2304 |
} |
2305 |
} |
2306 |
public Object[] toArray() { return toList(this).toArray(); } |
2307 |
public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } |
2308 |
|
2309 |
public Spliterator<Map.Entry<K,V>> spliterator() { |
2310 |
return (m instanceof ConcurrentSkipListMap) |
2311 |
? ((ConcurrentSkipListMap<K,V>)m).entrySpliterator() |
2312 |
: ((SubMap<K,V>)m).new SubMapEntryIterator(); |
2313 |
} |
2314 |
public boolean removeIf(Predicate<? super Entry<K,V>> filter) { |
2315 |
if (filter == null) throw new NullPointerException(); |
2316 |
if (m instanceof ConcurrentSkipListMap) |
2317 |
return ((ConcurrentSkipListMap<K,V>)m).removeEntryIf(filter); |
2318 |
// else use iterator |
2319 |
Iterator<Map.Entry<K,V>> it = |
2320 |
((SubMap<K,V>)m).new SubMapEntryIterator(); |
2321 |
boolean removed = false; |
2322 |
while (it.hasNext()) { |
2323 |
Map.Entry<K,V> e = it.next(); |
2324 |
if (filter.test(e) && m.remove(e.getKey(), e.getValue())) |
2325 |
removed = true; |
2326 |
} |
2327 |
return removed; |
2328 |
} |
2329 |
} |
2330 |
|
2331 |
/** |
2332 |
* Submaps returned by {@link ConcurrentSkipListMap} submap operations |
2333 |
* represent a subrange of mappings of their underlying maps. |
2334 |
* Instances of this class support all methods of their underlying |
2335 |
* maps, differing in that mappings outside their range are ignored, |
2336 |
* and attempts to add mappings outside their ranges result in {@link |
2337 |
* IllegalArgumentException}. Instances of this class are constructed |
2338 |
* only using the {@code subMap}, {@code headMap}, and {@code tailMap} |
2339 |
* methods of their underlying maps. |
2340 |
* |
2341 |
* @serial include |
2342 |
*/ |
2343 |
static final class SubMap<K,V> extends AbstractMap<K,V> |
2344 |
implements ConcurrentNavigableMap<K,V>, Serializable { |
2345 |
private static final long serialVersionUID = -7647078645895051609L; |
2346 |
|
2347 |
/** Underlying map */ |
2348 |
final ConcurrentSkipListMap<K,V> m; |
2349 |
/** lower bound key, or null if from start */ |
2350 |
@SuppressWarnings("serial") // Conditionally serializable |
2351 |
private final K lo; |
2352 |
/** upper bound key, or null if to end */ |
2353 |
@SuppressWarnings("serial") // Conditionally serializable |
2354 |
private final K hi; |
2355 |
/** inclusion flag for lo */ |
2356 |
private final boolean loInclusive; |
2357 |
/** inclusion flag for hi */ |
2358 |
private final boolean hiInclusive; |
2359 |
/** direction */ |
2360 |
final boolean isDescending; |
2361 |
|
2362 |
// Lazily initialized view holders |
2363 |
private transient KeySet<K,V> keySetView; |
2364 |
private transient Values<K,V> valuesView; |
2365 |
private transient EntrySet<K,V> entrySetView; |
2366 |
|
2367 |
/** |
2368 |
* Creates a new submap, initializing all fields. |
2369 |
*/ |
2370 |
SubMap(ConcurrentSkipListMap<K,V> map, |
2371 |
K fromKey, boolean fromInclusive, |
2372 |
K toKey, boolean toInclusive, |
2373 |
boolean isDescending) { |
2374 |
Comparator<? super K> cmp = map.comparator; |
2375 |
if (fromKey != null && toKey != null && |
2376 |
cpr(cmp, fromKey, toKey) > 0) |
2377 |
throw new IllegalArgumentException("inconsistent range"); |
2378 |
this.m = map; |
2379 |
this.lo = fromKey; |
2380 |
this.hi = toKey; |
2381 |
this.loInclusive = fromInclusive; |
2382 |
this.hiInclusive = toInclusive; |
2383 |
this.isDescending = isDescending; |
2384 |
} |
2385 |
|
2386 |
/* ---------------- Utilities -------------- */ |
2387 |
|
2388 |
boolean tooLow(Object key, Comparator<? super K> cmp) { |
2389 |
int c; |
2390 |
return (lo != null && ((c = cpr(cmp, key, lo)) < 0 || |
2391 |
(c == 0 && !loInclusive))); |
2392 |
} |
2393 |
|
2394 |
boolean tooHigh(Object key, Comparator<? super K> cmp) { |
2395 |
int c; |
2396 |
return (hi != null && ((c = cpr(cmp, key, hi)) > 0 || |
2397 |
(c == 0 && !hiInclusive))); |
2398 |
} |
2399 |
|
2400 |
boolean inBounds(Object key, Comparator<? super K> cmp) { |
2401 |
return !tooLow(key, cmp) && !tooHigh(key, cmp); |
2402 |
} |
2403 |
|
2404 |
void checkKeyBounds(K key, Comparator<? super K> cmp) { |
2405 |
if (key == null) |
2406 |
throw new NullPointerException(); |
2407 |
if (!inBounds(key, cmp)) |
2408 |
throw new IllegalArgumentException("key out of range"); |
2409 |
} |
2410 |
|
2411 |
/** |
2412 |
* Returns true if node key is less than upper bound of range. |
2413 |
*/ |
2414 |
boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n, |
2415 |
Comparator<? super K> cmp) { |
2416 |
if (n == null) |
2417 |
return false; |
2418 |
if (hi == null) |
2419 |
return true; |
2420 |
K k = n.key; |
2421 |
if (k == null) // pass by markers and headers |
2422 |
return true; |
2423 |
int c = cpr(cmp, k, hi); |
2424 |
return c < 0 || (c == 0 && hiInclusive); |
2425 |
} |
2426 |
|
2427 |
/** |
2428 |
* Returns lowest node. This node might not be in range, so |
2429 |
* most usages need to check bounds. |
2430 |
*/ |
2431 |
ConcurrentSkipListMap.Node<K,V> loNode(Comparator<? super K> cmp) { |
2432 |
if (lo == null) |
2433 |
return m.findFirst(); |
2434 |
else if (loInclusive) |
2435 |
return m.findNear(lo, GT|EQ, cmp); |
2436 |
else |
2437 |
return m.findNear(lo, GT, cmp); |
2438 |
} |
2439 |
|
2440 |
/** |
2441 |
* Returns highest node. This node might not be in range, so |
2442 |
* most usages need to check bounds. |
2443 |
*/ |
2444 |
ConcurrentSkipListMap.Node<K,V> hiNode(Comparator<? super K> cmp) { |
2445 |
if (hi == null) |
2446 |
return m.findLast(); |
2447 |
else if (hiInclusive) |
2448 |
return m.findNear(hi, LT|EQ, cmp); |
2449 |
else |
2450 |
return m.findNear(hi, LT, cmp); |
2451 |
} |
2452 |
|
2453 |
/** |
2454 |
* Returns lowest absolute key (ignoring directionality). |
2455 |
*/ |
2456 |
K lowestKey() { |
2457 |
Comparator<? super K> cmp = m.comparator; |
2458 |
ConcurrentSkipListMap.Node<K,V> n = loNode(cmp); |
2459 |
if (isBeforeEnd(n, cmp)) |
2460 |
return n.key; |
2461 |
else |
2462 |
throw new NoSuchElementException(); |
2463 |
} |
2464 |
|
2465 |
/** |
2466 |
* Returns highest absolute key (ignoring directionality). |
2467 |
*/ |
2468 |
K highestKey() { |
2469 |
Comparator<? super K> cmp = m.comparator; |
2470 |
ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp); |
2471 |
if (n != null) { |
2472 |
K last = n.key; |
2473 |
if (inBounds(last, cmp)) |
2474 |
return last; |
2475 |
} |
2476 |
throw new NoSuchElementException(); |
2477 |
} |
2478 |
|
2479 |
Map.Entry<K,V> lowestEntry() { |
2480 |
Comparator<? super K> cmp = m.comparator; |
2481 |
for (;;) { |
2482 |
ConcurrentSkipListMap.Node<K,V> n; V v; |
2483 |
if ((n = loNode(cmp)) == null || !isBeforeEnd(n, cmp)) |
2484 |
return null; |
2485 |
else if ((v = n.val) != null) |
2486 |
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v); |
2487 |
} |
2488 |
} |
2489 |
|
2490 |
Map.Entry<K,V> highestEntry() { |
2491 |
Comparator<? super K> cmp = m.comparator; |
2492 |
for (;;) { |
2493 |
ConcurrentSkipListMap.Node<K,V> n; V v; |
2494 |
if ((n = hiNode(cmp)) == null || !inBounds(n.key, cmp)) |
2495 |
return null; |
2496 |
else if ((v = n.val) != null) |
2497 |
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v); |
2498 |
} |
2499 |
} |
2500 |
|
2501 |
Map.Entry<K,V> removeLowest() { |
2502 |
Comparator<? super K> cmp = m.comparator; |
2503 |
for (;;) { |
2504 |
ConcurrentSkipListMap.Node<K,V> n; K k; V v; |
2505 |
if ((n = loNode(cmp)) == null) |
2506 |
return null; |
2507 |
else if (!inBounds((k = n.key), cmp)) |
2508 |
return null; |
2509 |
else if ((v = m.doRemove(k, null)) != null) |
2510 |
return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); |
2511 |
} |
2512 |
} |
2513 |
|
2514 |
Map.Entry<K,V> removeHighest() { |
2515 |
Comparator<? super K> cmp = m.comparator; |
2516 |
for (;;) { |
2517 |
ConcurrentSkipListMap.Node<K,V> n; K k; V v; |
2518 |
if ((n = hiNode(cmp)) == null) |
2519 |
return null; |
2520 |
else if (!inBounds((k = n.key), cmp)) |
2521 |
return null; |
2522 |
else if ((v = m.doRemove(k, null)) != null) |
2523 |
return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); |
2524 |
} |
2525 |
} |
2526 |
|
2527 |
/** |
2528 |
* Submap version of ConcurrentSkipListMap.findNearEntry. |
2529 |
*/ |
2530 |
Map.Entry<K,V> getNearEntry(K key, int rel) { |
2531 |
Comparator<? super K> cmp = m.comparator; |
2532 |
if (isDescending) { // adjust relation for direction |
2533 |
if ((rel & LT) == 0) |
2534 |
rel |= LT; |
2535 |
else |
2536 |
rel &= ~LT; |
2537 |
} |
2538 |
if (tooLow(key, cmp)) |
2539 |
return ((rel & LT) != 0) ? null : lowestEntry(); |
2540 |
if (tooHigh(key, cmp)) |
2541 |
return ((rel & LT) != 0) ? highestEntry() : null; |
2542 |
AbstractMap.SimpleImmutableEntry<K,V> e = |
2543 |
m.findNearEntry(key, rel, cmp); |
2544 |
if (e == null || !inBounds(e.getKey(), cmp)) |
2545 |
return null; |
2546 |
else |
2547 |
return e; |
2548 |
} |
2549 |
|
2550 |
// Almost the same as getNearEntry, except for keys |
2551 |
K getNearKey(K key, int rel) { |
2552 |
Comparator<? super K> cmp = m.comparator; |
2553 |
if (isDescending) { // adjust relation for direction |
2554 |
if ((rel & LT) == 0) |
2555 |
rel |= LT; |
2556 |
else |
2557 |
rel &= ~LT; |
2558 |
} |
2559 |
if (tooLow(key, cmp)) { |
2560 |
if ((rel & LT) == 0) { |
2561 |
ConcurrentSkipListMap.Node<K,V> n = loNode(cmp); |
2562 |
if (isBeforeEnd(n, cmp)) |
2563 |
return n.key; |
2564 |
} |
2565 |
return null; |
2566 |
} |
2567 |
if (tooHigh(key, cmp)) { |
2568 |
if ((rel & LT) != 0) { |
2569 |
ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp); |
2570 |
if (n != null) { |
2571 |
K last = n.key; |
2572 |
if (inBounds(last, cmp)) |
2573 |
return last; |
2574 |
} |
2575 |
} |
2576 |
return null; |
2577 |
} |
2578 |
for (;;) { |
2579 |
Node<K,V> n = m.findNear(key, rel, cmp); |
2580 |
if (n == null || !inBounds(n.key, cmp)) |
2581 |
return null; |
2582 |
if (n.val != null) |
2583 |
return n.key; |
2584 |
} |
2585 |
} |
2586 |
|
2587 |
/* ---------------- Map API methods -------------- */ |
2588 |
|
2589 |
public boolean containsKey(Object key) { |
2590 |
if (key == null) throw new NullPointerException(); |
2591 |
return inBounds(key, m.comparator) && m.containsKey(key); |
2592 |
} |
2593 |
|
2594 |
public V get(Object key) { |
2595 |
if (key == null) throw new NullPointerException(); |
2596 |
return (!inBounds(key, m.comparator)) ? null : m.get(key); |
2597 |
} |
2598 |
|
2599 |
public V put(K key, V value) { |
2600 |
checkKeyBounds(key, m.comparator); |
2601 |
return m.put(key, value); |
2602 |
} |
2603 |
|
2604 |
public V remove(Object key) { |
2605 |
return (!inBounds(key, m.comparator)) ? null : m.remove(key); |
2606 |
} |
2607 |
|
2608 |
public int size() { |
2609 |
Comparator<? super K> cmp = m.comparator; |
2610 |
long count = 0; |
2611 |
for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp); |
2612 |
isBeforeEnd(n, cmp); |
2613 |
n = n.next) { |
2614 |
if (n.val != null) |
2615 |
++count; |
2616 |
} |
2617 |
return count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)count; |
2618 |
} |
2619 |
|
2620 |
public boolean isEmpty() { |
2621 |
Comparator<? super K> cmp = m.comparator; |
2622 |
return !isBeforeEnd(loNode(cmp), cmp); |
2623 |
} |
2624 |
|
2625 |
public boolean containsValue(Object value) { |
2626 |
if (value == null) |
2627 |
throw new NullPointerException(); |
2628 |
Comparator<? super K> cmp = m.comparator; |
2629 |
for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp); |
2630 |
isBeforeEnd(n, cmp); |
2631 |
n = n.next) { |
2632 |
V v = n.val; |
2633 |
if (v != null && value.equals(v)) |
2634 |
return true; |
2635 |
} |
2636 |
return false; |
2637 |
} |
2638 |
|
2639 |
public void clear() { |
2640 |
Comparator<? super K> cmp = m.comparator; |
2641 |
for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp); |
2642 |
isBeforeEnd(n, cmp); |
2643 |
n = n.next) { |
2644 |
if (n.val != null) |
2645 |
m.remove(n.key); |
2646 |
} |
2647 |
} |
2648 |
|
2649 |
/* ---------------- ConcurrentMap API methods -------------- */ |
2650 |
|
2651 |
public V putIfAbsent(K key, V value) { |
2652 |
checkKeyBounds(key, m.comparator); |
2653 |
return m.putIfAbsent(key, value); |
2654 |
} |
2655 |
|
2656 |
public boolean remove(Object key, Object value) { |
2657 |
return inBounds(key, m.comparator) && m.remove(key, value); |
2658 |
} |
2659 |
|
2660 |
public boolean replace(K key, V oldValue, V newValue) { |
2661 |
checkKeyBounds(key, m.comparator); |
2662 |
return m.replace(key, oldValue, newValue); |
2663 |
} |
2664 |
|
2665 |
public V replace(K key, V value) { |
2666 |
checkKeyBounds(key, m.comparator); |
2667 |
return m.replace(key, value); |
2668 |
} |
2669 |
|
2670 |
/* ---------------- SortedMap API methods -------------- */ |
2671 |
|
2672 |
public Comparator<? super K> comparator() { |
2673 |
Comparator<? super K> cmp = m.comparator(); |
2674 |
if (isDescending) |
2675 |
return Collections.reverseOrder(cmp); |
2676 |
else |
2677 |
return cmp; |
2678 |
} |
2679 |
|
2680 |
/** |
2681 |
* Utility to create submaps, where given bounds override |
2682 |
* unbounded(null) ones and/or are checked against bounded ones. |
2683 |
*/ |
2684 |
SubMap<K,V> newSubMap(K fromKey, boolean fromInclusive, |
2685 |
K toKey, boolean toInclusive) { |
2686 |
Comparator<? super K> cmp = m.comparator; |
2687 |
if (isDescending) { // flip senses |
2688 |
K tk = fromKey; |
2689 |
fromKey = toKey; |
2690 |
toKey = tk; |
2691 |
boolean ti = fromInclusive; |
2692 |
fromInclusive = toInclusive; |
2693 |
toInclusive = ti; |
2694 |
} |
2695 |
if (lo != null) { |
2696 |
if (fromKey == null) { |
2697 |
fromKey = lo; |
2698 |
fromInclusive = loInclusive; |
2699 |
} |
2700 |
else { |
2701 |
int c = cpr(cmp, fromKey, lo); |
2702 |
if (c < 0 || (c == 0 && !loInclusive && fromInclusive)) |
2703 |
throw new IllegalArgumentException("key out of range"); |
2704 |
} |
2705 |
} |
2706 |
if (hi != null) { |
2707 |
if (toKey == null) { |
2708 |
toKey = hi; |
2709 |
toInclusive = hiInclusive; |
2710 |
} |
2711 |
else { |
2712 |
int c = cpr(cmp, toKey, hi); |
2713 |
if (c > 0 || (c == 0 && !hiInclusive && toInclusive)) |
2714 |
throw new IllegalArgumentException("key out of range"); |
2715 |
} |
2716 |
} |
2717 |
return new SubMap<K,V>(m, fromKey, fromInclusive, |
2718 |
toKey, toInclusive, isDescending); |
2719 |
} |
2720 |
|
2721 |
public SubMap<K,V> subMap(K fromKey, boolean fromInclusive, |
2722 |
K toKey, boolean toInclusive) { |
2723 |
if (fromKey == null || toKey == null) |
2724 |
throw new NullPointerException(); |
2725 |
return newSubMap(fromKey, fromInclusive, toKey, toInclusive); |
2726 |
} |
2727 |
|
2728 |
public SubMap<K,V> headMap(K toKey, boolean inclusive) { |
2729 |
if (toKey == null) |
2730 |
throw new NullPointerException(); |
2731 |
return newSubMap(null, false, toKey, inclusive); |
2732 |
} |
2733 |
|
2734 |
public SubMap<K,V> tailMap(K fromKey, boolean inclusive) { |
2735 |
if (fromKey == null) |
2736 |
throw new NullPointerException(); |
2737 |
return newSubMap(fromKey, inclusive, null, false); |
2738 |
} |
2739 |
|
2740 |
public SubMap<K,V> subMap(K fromKey, K toKey) { |
2741 |
return subMap(fromKey, true, toKey, false); |
2742 |
} |
2743 |
|
2744 |
public SubMap<K,V> headMap(K toKey) { |
2745 |
return headMap(toKey, false); |
2746 |
} |
2747 |
|
2748 |
public SubMap<K,V> tailMap(K fromKey) { |
2749 |
return tailMap(fromKey, true); |
2750 |
} |
2751 |
|
2752 |
public SubMap<K,V> descendingMap() { |
2753 |
return new SubMap<K,V>(m, lo, loInclusive, |
2754 |
hi, hiInclusive, !isDescending); |
2755 |
} |
2756 |
|
2757 |
/* ---------------- Relational methods -------------- */ |
2758 |
|
2759 |
public Map.Entry<K,V> ceilingEntry(K key) { |
2760 |
return getNearEntry(key, GT|EQ); |
2761 |
} |
2762 |
|
2763 |
public K ceilingKey(K key) { |
2764 |
return getNearKey(key, GT|EQ); |
2765 |
} |
2766 |
|
2767 |
public Map.Entry<K,V> lowerEntry(K key) { |
2768 |
return getNearEntry(key, LT); |
2769 |
} |
2770 |
|
2771 |
public K lowerKey(K key) { |
2772 |
return getNearKey(key, LT); |
2773 |
} |
2774 |
|
2775 |
public Map.Entry<K,V> floorEntry(K key) { |
2776 |
return getNearEntry(key, LT|EQ); |
2777 |
} |
2778 |
|
2779 |
public K floorKey(K key) { |
2780 |
return getNearKey(key, LT|EQ); |
2781 |
} |
2782 |
|
2783 |
public Map.Entry<K,V> higherEntry(K key) { |
2784 |
return getNearEntry(key, GT); |
2785 |
} |
2786 |
|
2787 |
public K higherKey(K key) { |
2788 |
return getNearKey(key, GT); |
2789 |
} |
2790 |
|
2791 |
public K firstKey() { |
2792 |
return isDescending ? highestKey() : lowestKey(); |
2793 |
} |
2794 |
|
2795 |
public K lastKey() { |
2796 |
return isDescending ? lowestKey() : highestKey(); |
2797 |
} |
2798 |
|
2799 |
public Map.Entry<K,V> firstEntry() { |
2800 |
return isDescending ? highestEntry() : lowestEntry(); |
2801 |
} |
2802 |
|
2803 |
public Map.Entry<K,V> lastEntry() { |
2804 |
return isDescending ? lowestEntry() : highestEntry(); |
2805 |
} |
2806 |
|
2807 |
public Map.Entry<K,V> pollFirstEntry() { |
2808 |
return isDescending ? removeHighest() : removeLowest(); |
2809 |
} |
2810 |
|
2811 |
public Map.Entry<K,V> pollLastEntry() { |
2812 |
return isDescending ? removeLowest() : removeHighest(); |
2813 |
} |
2814 |
|
2815 |
/* ---------------- Submap Views -------------- */ |
2816 |
|
2817 |
public NavigableSet<K> keySet() { |
2818 |
KeySet<K,V> ks; |
2819 |
if ((ks = keySetView) != null) return ks; |
2820 |
return keySetView = new KeySet<>(this); |
2821 |
} |
2822 |
|
2823 |
public NavigableSet<K> navigableKeySet() { |
2824 |
KeySet<K,V> ks; |
2825 |
if ((ks = keySetView) != null) return ks; |
2826 |
return keySetView = new KeySet<>(this); |
2827 |
} |
2828 |
|
2829 |
public Collection<V> values() { |
2830 |
Values<K,V> vs; |
2831 |
if ((vs = valuesView) != null) return vs; |
2832 |
return valuesView = new Values<>(this); |
2833 |
} |
2834 |
|
2835 |
public Set<Map.Entry<K,V>> entrySet() { |
2836 |
EntrySet<K,V> es; |
2837 |
if ((es = entrySetView) != null) return es; |
2838 |
return entrySetView = new EntrySet<K,V>(this); |
2839 |
} |
2840 |
|
2841 |
public NavigableSet<K> descendingKeySet() { |
2842 |
return descendingMap().navigableKeySet(); |
2843 |
} |
2844 |
|
2845 |
/** |
2846 |
* Variant of main Iter class to traverse through submaps. |
2847 |
* Also serves as back-up Spliterator for views. |
2848 |
*/ |
2849 |
abstract class SubMapIter<T> implements Iterator<T>, Spliterator<T> { |
2850 |
/** the last node returned by next() */ |
2851 |
Node<K,V> lastReturned; |
2852 |
/** the next node to return from next(); */ |
2853 |
Node<K,V> next; |
2854 |
/** Cache of next value field to maintain weak consistency */ |
2855 |
V nextValue; |
2856 |
|
2857 |
SubMapIter() { |
2858 |
VarHandle.acquireFence(); |
2859 |
Comparator<? super K> cmp = m.comparator; |
2860 |
for (;;) { |
2861 |
next = isDescending ? hiNode(cmp) : loNode(cmp); |
2862 |
if (next == null) |
2863 |
break; |
2864 |
V x = next.val; |
2865 |
if (x != null) { |
2866 |
if (! inBounds(next.key, cmp)) |
2867 |
next = null; |
2868 |
else |
2869 |
nextValue = x; |
2870 |
break; |
2871 |
} |
2872 |
} |
2873 |
} |
2874 |
|
2875 |
public final boolean hasNext() { |
2876 |
return next != null; |
2877 |
} |
2878 |
|
2879 |
final void advance() { |
2880 |
if (next == null) |
2881 |
throw new NoSuchElementException(); |
2882 |
lastReturned = next; |
2883 |
if (isDescending) |
2884 |
descend(); |
2885 |
else |
2886 |
ascend(); |
2887 |
} |
2888 |
|
2889 |
private void ascend() { |
2890 |
Comparator<? super K> cmp = m.comparator; |
2891 |
for (;;) { |
2892 |
next = next.next; |
2893 |
if (next == null) |
2894 |
break; |
2895 |
V x = next.val; |
2896 |
if (x != null) { |
2897 |
if (tooHigh(next.key, cmp)) |
2898 |
next = null; |
2899 |
else |
2900 |
nextValue = x; |
2901 |
break; |
2902 |
} |
2903 |
} |
2904 |
} |
2905 |
|
2906 |
private void descend() { |
2907 |
Comparator<? super K> cmp = m.comparator; |
2908 |
for (;;) { |
2909 |
next = m.findNear(lastReturned.key, LT, cmp); |
2910 |
if (next == null) |
2911 |
break; |
2912 |
V x = next.val; |
2913 |
if (x != null) { |
2914 |
if (tooLow(next.key, cmp)) |
2915 |
next = null; |
2916 |
else |
2917 |
nextValue = x; |
2918 |
break; |
2919 |
} |
2920 |
} |
2921 |
} |
2922 |
|
2923 |
public void remove() { |
2924 |
Node<K,V> l = lastReturned; |
2925 |
if (l == null) |
2926 |
throw new IllegalStateException(); |
2927 |
m.remove(l.key); |
2928 |
lastReturned = null; |
2929 |
} |
2930 |
|
2931 |
public Spliterator<T> trySplit() { |
2932 |
return null; |
2933 |
} |
2934 |
|
2935 |
public boolean tryAdvance(Consumer<? super T> action) { |
2936 |
if (hasNext()) { |
2937 |
action.accept(next()); |
2938 |
return true; |
2939 |
} |
2940 |
return false; |
2941 |
} |
2942 |
|
2943 |
public void forEachRemaining(Consumer<? super T> action) { |
2944 |
while (hasNext()) |
2945 |
action.accept(next()); |
2946 |
} |
2947 |
|
2948 |
public long estimateSize() { |
2949 |
return Long.MAX_VALUE; |
2950 |
} |
2951 |
|
2952 |
} |
2953 |
|
2954 |
final class SubMapValueIterator extends SubMapIter<V> { |
2955 |
public V next() { |
2956 |
V v = nextValue; |
2957 |
advance(); |
2958 |
return v; |
2959 |
} |
2960 |
public int characteristics() { |
2961 |
return 0; |
2962 |
} |
2963 |
} |
2964 |
|
2965 |
final class SubMapKeyIterator extends SubMapIter<K> { |
2966 |
public K next() { |
2967 |
Node<K,V> n = next; |
2968 |
advance(); |
2969 |
return n.key; |
2970 |
} |
2971 |
public int characteristics() { |
2972 |
return Spliterator.DISTINCT | Spliterator.ORDERED | |
2973 |
Spliterator.SORTED; |
2974 |
} |
2975 |
public final Comparator<? super K> getComparator() { |
2976 |
return SubMap.this.comparator(); |
2977 |
} |
2978 |
} |
2979 |
|
2980 |
final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> { |
2981 |
public Map.Entry<K,V> next() { |
2982 |
Node<K,V> n = next; |
2983 |
V v = nextValue; |
2984 |
advance(); |
2985 |
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v); |
2986 |
} |
2987 |
public int characteristics() { |
2988 |
return Spliterator.DISTINCT; |
2989 |
} |
2990 |
} |
2991 |
} |
2992 |
|
2993 |
// default Map method overrides |
2994 |
|
2995 |
public void forEach(BiConsumer<? super K, ? super V> action) { |
2996 |
if (action == null) throw new NullPointerException(); |
2997 |
Node<K,V> b, n; V v; |
2998 |
if ((b = baseHead()) != null) { |
2999 |
while ((n = b.next) != null) { |
3000 |
if ((v = n.val) != null) |
3001 |
action.accept(n.key, v); |
3002 |
b = n; |
3003 |
} |
3004 |
} |
3005 |
} |
3006 |
|
3007 |
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { |
3008 |
if (function == null) throw new NullPointerException(); |
3009 |
Node<K,V> b, n; V v; |
3010 |
if ((b = baseHead()) != null) { |
3011 |
while ((n = b.next) != null) { |
3012 |
while ((v = n.val) != null) { |
3013 |
V r = function.apply(n.key, v); |
3014 |
if (r == null) throw new NullPointerException(); |
3015 |
if (VAL.compareAndSet(n, v, r)) |
3016 |
break; |
3017 |
} |
3018 |
b = n; |
3019 |
} |
3020 |
} |
3021 |
} |
3022 |
|
3023 |
/** |
3024 |
* Helper method for EntrySet.removeIf. |
3025 |
*/ |
3026 |
boolean removeEntryIf(Predicate<? super Entry<K,V>> function) { |
3027 |
if (function == null) throw new NullPointerException(); |
3028 |
boolean removed = false; |
3029 |
Node<K,V> b, n; V v; |
3030 |
if ((b = baseHead()) != null) { |
3031 |
while ((n = b.next) != null) { |
3032 |
if ((v = n.val) != null) { |
3033 |
K k = n.key; |
3034 |
Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v); |
3035 |
if (function.test(e) && remove(k, v)) |
3036 |
removed = true; |
3037 |
} |
3038 |
b = n; |
3039 |
} |
3040 |
} |
3041 |
return removed; |
3042 |
} |
3043 |
|
3044 |
/** |
3045 |
* Helper method for Values.removeIf. |
3046 |
*/ |
3047 |
boolean removeValueIf(Predicate<? super V> function) { |
3048 |
if (function == null) throw new NullPointerException(); |
3049 |
boolean removed = false; |
3050 |
Node<K,V> b, n; V v; |
3051 |
if ((b = baseHead()) != null) { |
3052 |
while ((n = b.next) != null) { |
3053 |
if ((v = n.val) != null && function.test(v) && remove(n.key, v)) |
3054 |
removed = true; |
3055 |
b = n; |
3056 |
} |
3057 |
} |
3058 |
return removed; |
3059 |
} |
3060 |
|
3061 |
/** |
3062 |
* Base class providing common structure for Spliterators. |
3063 |
* (Although not all that much common functionality; as usual for |
3064 |
* view classes, details annoyingly vary in key, value, and entry |
3065 |
* subclasses in ways that are not worth abstracting out for |
3066 |
* internal classes.) |
3067 |
* |
3068 |
* The basic split strategy is to recursively descend from top |
3069 |
* level, row by row, descending to next row when either split |
3070 |
* off, or the end of row is encountered. Control of the number of |
3071 |
* splits relies on some statistical estimation: The expected |
3072 |
* remaining number of elements of a skip list when advancing |
3073 |
* either across or down decreases by about 25%. |
3074 |
*/ |
3075 |
abstract static class CSLMSpliterator<K,V> { |
3076 |
final Comparator<? super K> comparator; |
3077 |
final K fence; // exclusive upper bound for keys, or null if to end |
3078 |
Index<K,V> row; // the level to split out |
3079 |
Node<K,V> current; // current traversal node; initialize at origin |
3080 |
long est; // size estimate |
3081 |
CSLMSpliterator(Comparator<? super K> comparator, Index<K,V> row, |
3082 |
Node<K,V> origin, K fence, long est) { |
3083 |
this.comparator = comparator; this.row = row; |
3084 |
this.current = origin; this.fence = fence; this.est = est; |
3085 |
} |
3086 |
|
3087 |
public final long estimateSize() { return est; } |
3088 |
} |
3089 |
|
3090 |
static final class KeySpliterator<K,V> extends CSLMSpliterator<K,V> |
3091 |
implements Spliterator<K> { |
3092 |
KeySpliterator(Comparator<? super K> comparator, Index<K,V> row, |
3093 |
Node<K,V> origin, K fence, long est) { |
3094 |
super(comparator, row, origin, fence, est); |
3095 |
} |
3096 |
|
3097 |
public KeySpliterator<K,V> trySplit() { |
3098 |
Node<K,V> e; K ek; |
3099 |
Comparator<? super K> cmp = comparator; |
3100 |
K f = fence; |
3101 |
if ((e = current) != null && (ek = e.key) != null) { |
3102 |
for (Index<K,V> q = row; q != null; q = row = q.down) { |
3103 |
Index<K,V> s; Node<K,V> b, n; K sk; |
3104 |
if ((s = q.right) != null && (b = s.node) != null && |
3105 |
(n = b.next) != null && n.val != null && |
3106 |
(sk = n.key) != null && cpr(cmp, sk, ek) > 0 && |
3107 |
(f == null || cpr(cmp, sk, f) < 0)) { |
3108 |
current = n; |
3109 |
Index<K,V> r = q.down; |
3110 |
row = (s.right != null) ? s : s.down; |
3111 |
est -= est >>> 2; |
3112 |
return new KeySpliterator<K,V>(cmp, r, e, sk, est); |
3113 |
} |
3114 |
} |
3115 |
} |
3116 |
return null; |
3117 |
} |
3118 |
|
3119 |
public void forEachRemaining(Consumer<? super K> action) { |
3120 |
if (action == null) throw new NullPointerException(); |
3121 |
Comparator<? super K> cmp = comparator; |
3122 |
K f = fence; |
3123 |
Node<K,V> e = current; |
3124 |
current = null; |
3125 |
for (; e != null; e = e.next) { |
3126 |
K k; |
3127 |
if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) |
3128 |
break; |
3129 |
if (e.val != null) |
3130 |
action.accept(k); |
3131 |
} |
3132 |
} |
3133 |
|
3134 |
public boolean tryAdvance(Consumer<? super K> action) { |
3135 |
if (action == null) throw new NullPointerException(); |
3136 |
Comparator<? super K> cmp = comparator; |
3137 |
K f = fence; |
3138 |
Node<K,V> e = current; |
3139 |
for (; e != null; e = e.next) { |
3140 |
K k; |
3141 |
if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) { |
3142 |
e = null; |
3143 |
break; |
3144 |
} |
3145 |
if (e.val != null) { |
3146 |
current = e.next; |
3147 |
action.accept(k); |
3148 |
return true; |
3149 |
} |
3150 |
} |
3151 |
current = e; |
3152 |
return false; |
3153 |
} |
3154 |
|
3155 |
public int characteristics() { |
3156 |
return Spliterator.DISTINCT | Spliterator.SORTED | |
3157 |
Spliterator.ORDERED | Spliterator.CONCURRENT | |
3158 |
Spliterator.NONNULL; |
3159 |
} |
3160 |
|
3161 |
public final Comparator<? super K> getComparator() { |
3162 |
return comparator; |
3163 |
} |
3164 |
} |
3165 |
// factory method for KeySpliterator |
3166 |
final KeySpliterator<K,V> keySpliterator() { |
3167 |
Index<K,V> h; Node<K,V> n; long est; |
3168 |
VarHandle.acquireFence(); |
3169 |
if ((h = head) == null) { |
3170 |
n = null; |
3171 |
est = 0L; |
3172 |
} |
3173 |
else { |
3174 |
n = h.node; |
3175 |
est = getAdderCount(); |
3176 |
} |
3177 |
return new KeySpliterator<K,V>(comparator, h, n, null, est); |
3178 |
} |
3179 |
|
3180 |
static final class ValueSpliterator<K,V> extends CSLMSpliterator<K,V> |
3181 |
implements Spliterator<V> { |
3182 |
ValueSpliterator(Comparator<? super K> comparator, Index<K,V> row, |
3183 |
Node<K,V> origin, K fence, long est) { |
3184 |
super(comparator, row, origin, fence, est); |
3185 |
} |
3186 |
|
3187 |
public ValueSpliterator<K,V> trySplit() { |
3188 |
Node<K,V> e; K ek; |
3189 |
Comparator<? super K> cmp = comparator; |
3190 |
K f = fence; |
3191 |
if ((e = current) != null && (ek = e.key) != null) { |
3192 |
for (Index<K,V> q = row; q != null; q = row = q.down) { |
3193 |
Index<K,V> s; Node<K,V> b, n; K sk; |
3194 |
if ((s = q.right) != null && (b = s.node) != null && |
3195 |
(n = b.next) != null && n.val != null && |
3196 |
(sk = n.key) != null && cpr(cmp, sk, ek) > 0 && |
3197 |
(f == null || cpr(cmp, sk, f) < 0)) { |
3198 |
current = n; |
3199 |
Index<K,V> r = q.down; |
3200 |
row = (s.right != null) ? s : s.down; |
3201 |
est -= est >>> 2; |
3202 |
return new ValueSpliterator<K,V>(cmp, r, e, sk, est); |
3203 |
} |
3204 |
} |
3205 |
} |
3206 |
return null; |
3207 |
} |
3208 |
|
3209 |
public void forEachRemaining(Consumer<? super V> action) { |
3210 |
if (action == null) throw new NullPointerException(); |
3211 |
Comparator<? super K> cmp = comparator; |
3212 |
K f = fence; |
3213 |
Node<K,V> e = current; |
3214 |
current = null; |
3215 |
for (; e != null; e = e.next) { |
3216 |
K k; V v; |
3217 |
if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) |
3218 |
break; |
3219 |
if ((v = e.val) != null) |
3220 |
action.accept(v); |
3221 |
} |
3222 |
} |
3223 |
|
3224 |
public boolean tryAdvance(Consumer<? super V> action) { |
3225 |
if (action == null) throw new NullPointerException(); |
3226 |
Comparator<? super K> cmp = comparator; |
3227 |
K f = fence; |
3228 |
Node<K,V> e = current; |
3229 |
for (; e != null; e = e.next) { |
3230 |
K k; V v; |
3231 |
if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) { |
3232 |
e = null; |
3233 |
break; |
3234 |
} |
3235 |
if ((v = e.val) != null) { |
3236 |
current = e.next; |
3237 |
action.accept(v); |
3238 |
return true; |
3239 |
} |
3240 |
} |
3241 |
current = e; |
3242 |
return false; |
3243 |
} |
3244 |
|
3245 |
public int characteristics() { |
3246 |
return Spliterator.CONCURRENT | Spliterator.ORDERED | |
3247 |
Spliterator.NONNULL; |
3248 |
} |
3249 |
} |
3250 |
|
3251 |
// Almost the same as keySpliterator() |
3252 |
final ValueSpliterator<K,V> valueSpliterator() { |
3253 |
Index<K,V> h; Node<K,V> n; long est; |
3254 |
VarHandle.acquireFence(); |
3255 |
if ((h = head) == null) { |
3256 |
n = null; |
3257 |
est = 0L; |
3258 |
} |
3259 |
else { |
3260 |
n = h.node; |
3261 |
est = getAdderCount(); |
3262 |
} |
3263 |
return new ValueSpliterator<K,V>(comparator, h, n, null, est); |
3264 |
} |
3265 |
|
3266 |
static final class EntrySpliterator<K,V> extends CSLMSpliterator<K,V> |
3267 |
implements Spliterator<Map.Entry<K,V>> { |
3268 |
EntrySpliterator(Comparator<? super K> comparator, Index<K,V> row, |
3269 |
Node<K,V> origin, K fence, long est) { |
3270 |
super(comparator, row, origin, fence, est); |
3271 |
} |
3272 |
|
3273 |
public EntrySpliterator<K,V> trySplit() { |
3274 |
Node<K,V> e; K ek; |
3275 |
Comparator<? super K> cmp = comparator; |
3276 |
K f = fence; |
3277 |
if ((e = current) != null && (ek = e.key) != null) { |
3278 |
for (Index<K,V> q = row; q != null; q = row = q.down) { |
3279 |
Index<K,V> s; Node<K,V> b, n; K sk; |
3280 |
if ((s = q.right) != null && (b = s.node) != null && |
3281 |
(n = b.next) != null && n.val != null && |
3282 |
(sk = n.key) != null && cpr(cmp, sk, ek) > 0 && |
3283 |
(f == null || cpr(cmp, sk, f) < 0)) { |
3284 |
current = n; |
3285 |
Index<K,V> r = q.down; |
3286 |
row = (s.right != null) ? s : s.down; |
3287 |
est -= est >>> 2; |
3288 |
return new EntrySpliterator<K,V>(cmp, r, e, sk, est); |
3289 |
} |
3290 |
} |
3291 |
} |
3292 |
return null; |
3293 |
} |
3294 |
|
3295 |
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) { |
3296 |
if (action == null) throw new NullPointerException(); |
3297 |
Comparator<? super K> cmp = comparator; |
3298 |
K f = fence; |
3299 |
Node<K,V> e = current; |
3300 |
current = null; |
3301 |
for (; e != null; e = e.next) { |
3302 |
K k; V v; |
3303 |
if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) |
3304 |
break; |
3305 |
if ((v = e.val) != null) { |
3306 |
action.accept |
3307 |
(new AbstractMap.SimpleImmutableEntry<K,V>(k, v)); |
3308 |
} |
3309 |
} |
3310 |
} |
3311 |
|
3312 |
public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) { |
3313 |
if (action == null) throw new NullPointerException(); |
3314 |
Comparator<? super K> cmp = comparator; |
3315 |
K f = fence; |
3316 |
Node<K,V> e = current; |
3317 |
for (; e != null; e = e.next) { |
3318 |
K k; V v; |
3319 |
if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) { |
3320 |
e = null; |
3321 |
break; |
3322 |
} |
3323 |
if ((v = e.val) != null) { |
3324 |
current = e.next; |
3325 |
action.accept |
3326 |
(new AbstractMap.SimpleImmutableEntry<K,V>(k, v)); |
3327 |
return true; |
3328 |
} |
3329 |
} |
3330 |
current = e; |
3331 |
return false; |
3332 |
} |
3333 |
|
3334 |
public int characteristics() { |
3335 |
return Spliterator.DISTINCT | Spliterator.SORTED | |
3336 |
Spliterator.ORDERED | Spliterator.CONCURRENT | |
3337 |
Spliterator.NONNULL; |
3338 |
} |
3339 |
|
3340 |
public final Comparator<Map.Entry<K,V>> getComparator() { |
3341 |
// Adapt or create a key-based comparator |
3342 |
if (comparator != null) { |
3343 |
return Map.Entry.comparingByKey(comparator); |
3344 |
} |
3345 |
else { |
3346 |
return (Comparator<Map.Entry<K,V>> & Serializable) (e1, e2) -> { |
3347 |
@SuppressWarnings("unchecked") |
3348 |
Comparable<? super K> k1 = (Comparable<? super K>) e1.getKey(); |
3349 |
return k1.compareTo(e2.getKey()); |
3350 |
}; |
3351 |
} |
3352 |
} |
3353 |
} |
3354 |
|
3355 |
// Almost the same as keySpliterator() |
3356 |
final EntrySpliterator<K,V> entrySpliterator() { |
3357 |
Index<K,V> h; Node<K,V> n; long est; |
3358 |
VarHandle.acquireFence(); |
3359 |
if ((h = head) == null) { |
3360 |
n = null; |
3361 |
est = 0L; |
3362 |
} |
3363 |
else { |
3364 |
n = h.node; |
3365 |
est = getAdderCount(); |
3366 |
} |
3367 |
return new EntrySpliterator<K,V>(comparator, h, n, null, est); |
3368 |
} |
3369 |
|
3370 |
// VarHandle mechanics |
3371 |
private static final VarHandle HEAD; |
3372 |
private static final VarHandle ADDER; |
3373 |
private static final VarHandle NEXT; |
3374 |
private static final VarHandle VAL; |
3375 |
private static final VarHandle RIGHT; |
3376 |
static { |
3377 |
try { |
3378 |
MethodHandles.Lookup l = MethodHandles.lookup(); |
3379 |
HEAD = l.findVarHandle(ConcurrentSkipListMap.class, "head", |
3380 |
Index.class); |
3381 |
ADDER = l.findVarHandle(ConcurrentSkipListMap.class, "adder", |
3382 |
LongAdder.class); |
3383 |
NEXT = l.findVarHandle(Node.class, "next", Node.class); |
3384 |
VAL = l.findVarHandle(Node.class, "val", Object.class); |
3385 |
RIGHT = l.findVarHandle(Index.class, "right", Index.class); |
3386 |
} catch (ReflectiveOperationException e) { |
3387 |
throw new ExceptionInInitializerError(e); |
3388 |
} |
3389 |
} |
3390 |
} |