ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.88
Committed: Tue Jan 22 18:25:32 2013 UTC (11 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.87: +379 -176 lines
Log Message:
Spliterators

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