ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.131
Committed: Thu Aug 8 04:23:21 2013 UTC (10 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.130: +1 -1 lines
Log Message:
whitespace

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