ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.114
Committed: Wed Mar 27 20:56:44 2013 UTC (11 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.113: +2 -2 lines
Log Message:
coding style

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