ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.166
Committed: Sat Mar 11 17:36:10 2017 UTC (7 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.165: +0 -1 lines
Log Message:
fix unused imports reported by errorprone [RemoveUnusedImports]

File Contents

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