ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.138
Committed: Wed Dec 31 07:54:13 2014 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.137: +2 -1 lines
Log Message:
standardize import statement order

File Contents

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