ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.139
Committed: Wed Dec 31 09:37:20 2014 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.138: +0 -3 lines
Log Message:
remove unused/redundant imports

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