ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.93
Committed: Mon Jan 28 22:34:06 2013 UTC (11 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.92: +1 -1 lines
Log Message:
remove bad @param

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