ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.129
Committed: Thu Jul 18 18:21:22 2013 UTC (10 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.128: +4 -0 lines
Log Message:
javadoc warning fixes: add serialization method @throws

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