ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.111
Committed: Mon Mar 18 19:35:09 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.110: +1 -1 lines
Log Message:
key param specs

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