ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.83
Committed: Wed Jan 16 15:04:03 2013 UTC (11 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.82: +664 -20 lines
Log Message:
lambda-lib support

File Contents

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