ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.172
Committed: Tue Aug 15 02:48:30 2017 UTC (6 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.171: +3 -3 lines
Log Message:
typo

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