ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.184
Committed: Wed Apr 24 16:54:49 2019 UTC (5 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.183: +1 -0 lines
Log Message:
8222930: ConcurrentSkipListMap.clone() shares size variable between original and clone

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