ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.160
Committed: Thu Jun 2 13:16:27 2016 UTC (8 years ago) by dl
Branch: MAIN
Changes since 1.159: +23 -26 lines
Log Message:
VarHandles conversion; pass 1

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