ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.126
Committed: Wed Jun 19 17:14:20 2013 UTC (10 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.125: +1 -1 lines
Log Message:
javadoc punctuation

File Contents

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