2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
36 package java.util.concurrent;
40 * A scalable concurrent {@link ConcurrentNavigableMap} implementation.
41 * The map is sorted according to the {@linkplain Comparable natural
42 * ordering} of its keys, or by a {@link Comparator} provided at map
43 * creation time, depending on which constructor is used.
45 * <p>This class implements a concurrent variant of <a
46 * href="http://en.wikipedia.org/wiki/Skip_list" target="_top">SkipLists</a>
47 * providing expected average <i>log(n)</i> time cost for the
48 * <tt>containsKey</tt>, <tt>get</tt>, <tt>put</tt> and
49 * <tt>remove</tt> operations and their variants. Insertion, removal,
50 * update, and access operations safely execute concurrently by
51 * multiple threads. Iterators are <i>weakly consistent</i>, returning
52 * elements reflecting the state of the map at some point at or since
53 * the creation of the iterator. They do <em>not</em> throw {@link
54 * ConcurrentModificationException}, and may proceed concurrently with
55 * other operations. Ascending key ordered views and their iterators
56 * are faster than descending ones.
58 * <p>All <tt>Map.Entry</tt> pairs returned by methods in this class
59 * and its views represent snapshots of mappings at the time they were
60 * produced. They do <em>not</em> support the <tt>Entry.setValue</tt>
61 * method. (Note however that it is possible to change mappings in the
62 * associated map using <tt>put</tt>, <tt>putIfAbsent</tt>, or
63 * <tt>replace</tt>, depending on exactly which effect you need.)
65 * <p>Beware that, unlike in most collections, the <tt>size</tt>
66 * method is <em>not</em> a constant-time operation. Because of the
67 * asynchronous nature of these maps, determining the current number
68 * of elements requires a traversal of the elements, and so may report
69 * inaccurate results if this collection is modified during traversal.
70 * Additionally, the bulk operations <tt>putAll</tt>, <tt>equals</tt>,
71 * <tt>toArray</tt>, <tt>containsValue</tt>, and <tt>clear</tt> are
72 * <em>not</em> guaranteed to be performed atomically. For example, an
73 * iterator operating concurrently with a <tt>putAll</tt> operation
74 * might view only some of the added elements.
76 * <p>This class and its views and iterators implement all of the
77 * <em>optional</em> methods of the {@link Map} and {@link Iterator}
78 * interfaces. Like most other concurrent collections, this class does
79 * <em>not</em> permit the use of <tt>null</tt> keys or values because some
80 * null return values cannot be reliably distinguished from the absence of
83 * <p>This class is a member of the
84 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
85 * Java Collections Framework</a>.
88 * @param <K> the type of keys maintained by this map
89 * @param <V> the type of mapped values
92 public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
93 implements ConcurrentNavigableMap<K,V>,
95 java.io.Serializable {
97 * This class implements a tree-like two-dimensionally linked skip
98 * list in which the index levels are represented in separate
99 * nodes from the base nodes holding data. There are two reasons
100 * for taking this approach instead of the usual array-based
101 * structure: 1) Array based implementations seem to encounter
102 * more complexity and overhead 2) We can use cheaper algorithms
103 * for the heavily-traversed index lists than can be used for the
104 * base lists. Here's a picture of some of the basics for a
105 * possible list with 2 levels of index:
107 * Head nodes Index nodes
109 * |2|---------------->| |--------------------->| |->null
113 * +-+ +-+ +-+ +-+ +-+ +-+
114 * |1|----------->| |->| |------>| |----------->| |------>| |->null
115 * +-+ +-+ +-+ +-+ +-+ +-+
117 * Nodes next v v v v v
118 * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
119 * | |->|A|->|B|->|C|->|D|->|E|->|F|->|G|->|H|->|I|->|J|->|K|->null
120 * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
122 * The base lists use a variant of the HM linked ordered set
123 * algorithm. See Tim Harris, "A pragmatic implementation of
124 * non-blocking linked lists"
125 * http://www.cl.cam.ac.uk/~tlh20/publications.html and Maged
126 * Michael "High Performance Dynamic Lock-Free Hash Tables and
128 * http://www.research.ibm.com/people/m/michael/pubs.htm. The
129 * basic idea in these lists is to mark the "next" pointers of
130 * deleted nodes when deleting to avoid conflicts with concurrent
131 * insertions, and when traversing to keep track of triples
132 * (predecessor, node, successor) in order to detect when and how
133 * to unlink these deleted nodes.
135 * Rather than using mark-bits to mark list deletions (which can
136 * be slow and space-intensive using AtomicMarkedReference), nodes
137 * use direct CAS'able next pointers. On deletion, instead of
138 * marking a pointer, they splice in another node that can be
139 * thought of as standing for a marked pointer (indicating this by
140 * using otherwise impossible field values). Using plain nodes
141 * acts roughly like "boxed" implementations of marked pointers,
142 * but uses new nodes only when nodes are deleted, not for every
143 * link. This requires less space and supports faster
144 * traversal. Even if marked references were better supported by
145 * JVMs, traversal using this technique might still be faster
146 * because any search need only read ahead one more node than
147 * otherwise required (to check for trailing marker) rather than
148 * unmasking mark bits or whatever on each read.
150 * This approach maintains the essential property needed in the HM
151 * algorithm of changing the next-pointer of a deleted node so
152 * that any other CAS of it will fail, but implements the idea by
153 * changing the pointer to point to a different node, not by
154 * marking it. While it would be possible to further squeeze
155 * space by defining marker nodes not to have key/value fields, it
156 * isn't worth the extra type-testing overhead. The deletion
157 * markers are rarely encountered during traversal and are
158 * normally quickly garbage collected. (Note that this technique
159 * would not work well in systems without garbage collection.)
161 * In addition to using deletion markers, the lists also use
162 * nullness of value fields to indicate deletion, in a style
163 * similar to typical lazy-deletion schemes. If a node's value is
164 * null, then it is considered logically deleted and ignored even
165 * though it is still reachable. This maintains proper control of
166 * concurrent replace vs delete operations -- an attempted replace
167 * must fail if a delete beat it by nulling field, and a delete
168 * must return the last non-null value held in the field. (Note:
169 * Null, rather than some special marker, is used for value fields
170 * here because it just so happens to mesh with the Map API
171 * requirement that method get returns null if there is no
172 * mapping, which allows nodes to remain concurrently readable
173 * even when deleted. Using any other marker value here would be
176 * Here's the sequence of events for a deletion of node n with
177 * predecessor b and successor f, initially:
179 * +------+ +------+ +------+
180 * ... | b |------>| n |----->| f | ...
181 * +------+ +------+ +------+
183 * 1. CAS n's value field from non-null to null.
184 * From this point on, no public operations encountering
185 * the node consider this mapping to exist. However, other
186 * ongoing insertions and deletions might still modify
189 * 2. CAS n's next pointer to point to a new marker node.
190 * From this point on, no other nodes can be appended to n.
191 * which avoids deletion errors in CAS-based linked lists.
193 * +------+ +------+ +------+ +------+
194 * ... | b |------>| n |----->|marker|------>| f | ...
195 * +------+ +------+ +------+ +------+
197 * 3. CAS b's next pointer over both n and its marker.
198 * From this point on, no new traversals will encounter n,
199 * and it can eventually be GCed.
201 * ... | b |----------------------------------->| f | ...
204 * A failure at step 1 leads to simple retry due to a lost race
205 * with another operation. Steps 2-3 can fail because some other
206 * thread noticed during a traversal a node with null value and
207 * helped out by marking and/or unlinking. This helping-out
208 * ensures that no thread can become stuck waiting for progress of
209 * the deleting thread. The use of marker nodes slightly
210 * complicates helping-out code because traversals must track
211 * consistent reads of up to four nodes (b, n, marker, f), not
212 * just (b, n, f), although the next field of a marker is
213 * immutable, and once a next field is CAS'ed to point to a
214 * marker, it never again changes, so this requires less care.
216 * Skip lists add indexing to this scheme, so that the base-level
217 * traversals start close to the locations being found, inserted
218 * or deleted -- usually base level traversals only traverse a few
219 * nodes. This doesn't change the basic algorithm except for the
220 * need to make sure base traversals start at predecessors (here,
221 * b) that are not (structurally) deleted, otherwise retrying
222 * after processing the deletion.
224 * Index levels are maintained as lists with volatile next fields,
225 * using CAS to link and unlink. Races are allowed in index-list
226 * operations that can (rarely) fail to link in a new index node
227 * or delete one. (We can't do this of course for data nodes.)
228 * However, even when this happens, the index lists remain sorted,
229 * so correctly serve as indices. This can impact performance,
230 * but since skip lists are probabilistic anyway, the net result
231 * is that under contention, the effective "p" value may be lower
232 * than its nominal value. And race windows are kept small enough
233 * that in practice these failures are rare, even under a lot of
236 * The fact that retries (for both base and index lists) are
237 * relatively cheap due to indexing allows some minor
238 * simplifications of retry logic. Traversal restarts are
239 * performed after most "helping-out" CASes. This isn't always
240 * strictly necessary, but the implicit backoffs tend to help
241 * reduce other downstream failed CAS's enough to outweigh restart
242 * cost. This worsens the worst case, but seems to improve even
243 * highly contended cases.
245 * Unlike most skip-list implementations, index insertion and
246 * deletion here require a separate traversal pass occuring after
247 * the base-level action, to add or remove index nodes. This adds
248 * to single-threaded overhead, but improves contended
249 * multithreaded performance by narrowing interference windows,
250 * and allows deletion to ensure that all index nodes will be made
251 * unreachable upon return from a public remove operation, thus
252 * avoiding unwanted garbage retention. This is more important
253 * here than in some other data structures because we cannot null
254 * out node fields referencing user keys since they might still be
255 * read by other ongoing traversals.
257 * Indexing uses skip list parameters that maintain good search
258 * performance while using sparser-than-usual indices: The
259 * hardwired parameters k=1, p=0.5 (see method randomLevel) mean
260 * that about one-quarter of the nodes have indices. Of those that
261 * do, half have one level, a quarter have two, and so on (see
262 * Pugh's Skip List Cookbook, sec 3.4). The expected total space
263 * requirement for a map is slightly less than for the current
264 * implementation of java.util.TreeMap.
266 * Changing the level of the index (i.e, the height of the
267 * tree-like structure) also uses CAS. The head index has initial
268 * level/height of one. Creation of an index with height greater
269 * than the current level adds a level to the head index by
270 * CAS'ing on a new top-most head. To maintain good performance
271 * after a lot of removals, deletion methods heuristically try to
272 * reduce the height if the topmost levels appear to be empty.
273 * This may encounter races in which it possible (but rare) to
274 * reduce and "lose" a level just as it is about to contain an
275 * index (that will then never be encountered). This does no
276 * structural harm, and in practice appears to be a better option
277 * than allowing unrestrained growth of levels.
279 * The code for all this is more verbose than you'd like. Most
280 * operations entail locating an element (or position to insert an
281 * element). The code to do this can't be nicely factored out
282 * because subsequent uses require a snapshot of predecessor
283 * and/or successor and/or value fields which can't be returned
284 * all at once, at least not without creating yet another object
285 * to hold them -- creating such little objects is an especially
286 * bad idea for basic internal search operations because it adds
287 * to GC overhead. (This is one of the few times I've wished Java
288 * had macros.) Instead, some traversal code is interleaved within
289 * insertion and removal operations. The control logic to handle
290 * all the retry conditions is sometimes twisty. Most search is
291 * broken into 2 parts. findPredecessor() searches index nodes
292 * only, returning a base-level predecessor of the key. findNode()
293 * finishes out the base-level search. Even with this factoring,
294 * there is a fair amount of near-duplication of code to handle
297 * For explanation of algorithms sharing at least a couple of
298 * features with this one, see Mikhail Fomitchev's thesis
299 * (http://www.cs.yorku.ca/~mikhail/), Keir Fraser's thesis
300 * (http://www.cl.cam.ac.uk/users/kaf24/), and Hakan Sundell's
301 * thesis (http://www.cs.chalmers.se/~phs/).
303 * Given the use of tree-like index nodes, you might wonder why
304 * this doesn't use some kind of search tree instead, which would
305 * support somewhat faster search operations. The reason is that
306 * there are no known efficient lock-free insertion and deletion
307 * algorithms for search trees. The immutability of the "down"
308 * links of index nodes (as opposed to mutable "left" fields in
309 * true trees) makes this tractable using only CAS operations.
311 * Notation guide for local variables
312 * Node: b, n, f for predecessor, node, successor
313 * Index: q, r, d for index node, right, down.
314 * t for another index node
322 private static final long serialVersionUID = -8627078645895051609L;
325 * Generates the initial random seed for the cheaper per-instance
326 * random number generators used in randomLevel.
328 private static final Random seedGenerator = new Random();
331 * Special value used to identify base-level header
333 private static final Object BASE_HEADER = new Object();
336 * The topmost head index of the skiplist.
338 private transient volatile HeadIndex<K,V> head;
341 * The comparator used to maintain order in this map, or null
342 * if using natural ordering.
345 private final Comparator<? super K> comparator;
348 * Seed for simple random number generator. Not volatile since it
349 * doesn't matter too much if different threads don't see updates.
351 private transient int randomSeed;
353 /** Lazily initialized key set */
354 private transient KeySet keySet;
355 /** Lazily initialized entry set */
356 private transient EntrySet entrySet;
357 /** Lazily initialized values collection */
358 private transient Values values;
359 /** Lazily initialized descending key set */
360 private transient ConcurrentNavigableMap<K,V> descendingMap;
363 * Initializes or resets state. Needed by constructors, clone,
364 * clear, readObject. and ConcurrentSkipListSet.clone.
365 * (Note that comparator must be separately initialized.)
367 final void initialize() {
371 descendingMap = null;
372 randomSeed = seedGenerator.nextInt() | 0x0100; // ensure nonzero
373 head = new HeadIndex<K,V>(new Node<K,V>(null, BASE_HEADER, null),
378 * compareAndSet head node
380 private boolean casHead(HeadIndex<K,V> cmp, HeadIndex<K,V> val) {
388 /* ---------------- Nodes -------------- */
391 * Nodes hold keys and values, and are singly linked in sorted
392 * order, possibly with some intervening marker nodes. The list is
393 * headed by a dummy node accessible as head.node. The value field
394 * is declared only as Object because it takes special non-V
395 * values for marker and header nodes.
397 static final class Node<K,V> {
399 volatile Object value;
400 volatile Node<K,V> next;
403 * Creates a new regular node.
405 Node(K key, Object value, Node<K,V> next) {
412 * Creates a new marker node. A marker is distinguished by
413 * having its value field point to itself. Marker nodes also
414 * have null keys, a fact that is exploited in a few places,
415 * but this doesn't distinguish markers from the base-level
416 * header node (head.node), which also has a null key.
418 Node(Node<K,V> next) {
425 * compareAndSet value field
427 boolean casValue(Object cmp, Object val) {
436 * compareAndSet next field
438 boolean casNext(Node<K,V> cmp, Node<K,V> val) {
447 * Returns true if this node is a marker. This method isn't
448 * actually called in any current code checking for markers
449 * because callers will have already read value field and need
450 * to use that read (not another done here) and so directly
451 * test if value points to node.
452 * @param n a possibly null reference to a node
453 * @return true if this node is a marker node
456 return value == this;
460 * Returns true if this node is the header of base-level list.
461 * @return true if this node is header node
463 boolean isBaseHeader() {
464 return value == BASE_HEADER;
468 * Tries to append a deletion marker to this node.
469 * @param f the assumed current successor of this node
470 * @return true if successful
472 boolean appendMarker(Node<K,V> f) {
473 return casNext(f, new Node<K,V>(f));
477 * Helps out a deletion by appending marker or unlinking from
478 * predecessor. This is called during traversals when value
479 * field seen to be null.
480 * @param b predecessor
483 void helpDelete(Node<K,V> b, Node<K,V> f) {
485 * Rechecking links and then doing only one of the
486 * help-out stages per call tends to minimize CAS
487 * interference among helping threads.
489 if (f == next && this == b.next) {
490 if (f == null || f.value != f) // not already marked
493 b.casNext(this, f.next);
498 * Returns value if this node contains a valid key-value pair,
500 * @return this node's value if it isn't a marker or header or
501 * is deleted, else null.
505 if (v == this || v == BASE_HEADER)
511 * Creates and returns a new SimpleImmutableEntry holding current
512 * mapping if this node holds a valid value, else null.
513 * @return new entry or null
515 AbstractMap.SimpleImmutableEntry<K,V> createSnapshot() {
516 V v = getValidValue();
519 return new AbstractMap.SimpleImmutableEntry<K,V>(key, v);
523 /* ---------------- Indexing -------------- */
526 * Index nodes represent the levels of the skip list. Note that
527 * even though both Nodes and Indexes have forward-pointing
528 * fields, they have different types and are handled in different
529 * ways, that can't nicely be captured by placing field in a
530 * shared abstract class.
532 static class Index<K,V> {
533 final Node<K,V> node;
534 final Index<K,V> down;
535 volatile Index<K,V> right;
538 * Creates index node with given values.
540 Index(Node<K,V> node, Index<K,V> down, Index<K,V> right) {
547 * compareAndSet right field
549 final boolean casRight(Index<K,V> cmp, Index<K,V> val) {
558 * Returns true if the node this indexes has been deleted.
559 * @return true if indexed node is known to be deleted
561 final boolean indexesDeletedNode() {
562 return node.value == null;
566 * Tries to CAS newSucc as successor. To minimize races with
567 * unlink that may lose this index node, if the node being
568 * indexed is known to be deleted, it doesn't try to link in.
569 * @param succ the expected current successor
570 * @param newSucc the new successor
571 * @return true if successful
573 final boolean link(Index<K,V> succ, Index<K,V> newSucc) {
575 newSucc.right = succ;
576 return n.value != null && casRight(succ, newSucc);
580 * Tries to CAS right field to skip over apparent successor
581 * succ. Fails (forcing a retraversal by caller) if this node
582 * is known to be deleted.
583 * @param succ the expected current successor
584 * @return true if successful
586 final boolean unlink(Index<K,V> succ) {
587 return !indexesDeletedNode() && casRight(succ, succ.right);
591 /* ---------------- Head nodes -------------- */
594 * Nodes heading each level keep track of their level.
596 static final class HeadIndex<K,V> extends Index<K,V> {
598 HeadIndex(Node<K,V> node, Index<K,V> down, Index<K,V> right, int level) {
599 super(node, down, right);
604 /* ---------------- Comparison utilities -------------- */
607 * Represents a key with a comparator as a Comparable.
609 * Because most sorted collections seem to use natural ordering on
610 * Comparables (Strings, Integers, etc), most internal methods are
611 * geared to use them. This is generally faster than checking
612 * per-comparison whether to use comparator or comparable because
613 * it doesn't require a (Comparable) cast for each comparison.
614 * (Optimizers can only sometimes remove such redundant checks
615 * themselves.) When Comparators are used,
616 * ComparableUsingComparators are created so that they act in the
617 * same way as natural orderings. This penalizes use of
618 * Comparators vs Comparables, which seems like the right
621 static final class ComparableUsingComparator<K> implements Comparable<K> {
623 final Comparator<? super K> cmp;
624 ComparableUsingComparator(K key, Comparator<? super K> cmp) {
625 this.actualKey = key;
628 public int compareTo(K k2) {
629 return cmp.compare(actualKey, k2);
634 * If using comparator, return a ComparableUsingComparator, else
635 * cast key as Comparable, which may cause ClassCastException,
636 * which is propagated back to caller.
638 private Comparable<? super K> comparable(Object key)
639 throws ClassCastException {
641 throw new NullPointerException();
642 if (comparator != null)
643 return new ComparableUsingComparator<K>((K)key, comparator);
645 return (Comparable<? super K>)key;
649 * Compares using comparator or natural ordering. Used when the
650 * ComparableUsingComparator approach doesn't apply.
652 int compare(K k1, K k2) throws ClassCastException {
653 Comparator<? super K> cmp = comparator;
655 return cmp.compare(k1, k2);
657 return ((Comparable<? super K>)k1).compareTo(k2);
661 * Returns true if given key greater than or equal to least and
662 * strictly less than fence, bypassing either test if least or
663 * fence are null. Needed mainly in submap operations.
665 boolean inHalfOpenRange(K key, K least, K fence) {
667 throw new NullPointerException();
668 return ((least == null || compare(key, least) >= 0) &&
669 (fence == null || compare(key, fence) < 0));
673 * Returns true if given key greater than or equal to least and less
674 * or equal to fence. Needed mainly in submap operations.
676 boolean inOpenRange(K key, K least, K fence) {
678 throw new NullPointerException();
679 return ((least == null || compare(key, least) >= 0) &&
680 (fence == null || compare(key, fence) <= 0));
683 /* ---------------- Traversal -------------- */
686 * Returns a base-level node with key strictly less than given key,
687 * or the base-level header if there is no such node. Also
688 * unlinks indexes to deleted nodes found along the way. Callers
689 * rely on this side-effect of clearing indices to deleted nodes.
691 * @return a predecessor of key
693 private Node<K,V> findPredecessor(Comparable<? super K> key) {
695 throw new NullPointerException(); // don't postpone errors
698 Index<K,V> r = q.right;
701 Node<K,V> n = r.node;
703 if (n.value == null) {
706 r = q.right; // reread r
709 if (key.compareTo(k) > 0) {
715 Index<K,V> d = q.down;
726 * Returns node holding key or null if no such, clearing out any
727 * deleted nodes seen along the way. Repeatedly traverses at
728 * base-level looking for key starting at predecessor returned
729 * from findPredecessor, processing base-level deletions as
730 * encountered. Some callers rely on this side-effect of clearing
733 * Restarts occur, at traversal step centered on node n, if:
735 * (1) After reading n's next field, n is no longer assumed
736 * predecessor b's current successor, which means that
737 * we don't have a consistent 3-node snapshot and so cannot
738 * unlink any subsequent deleted nodes encountered.
740 * (2) n's value field is null, indicating n is deleted, in
741 * which case we help out an ongoing structural deletion
742 * before retrying. Even though there are cases where such
743 * unlinking doesn't require restart, they aren't sorted out
744 * here because doing so would not usually outweigh cost of
747 * (3) n is a marker or n's predecessor's value field is null,
748 * indicating (among other possibilities) that
749 * findPredecessor returned a deleted node. We can't unlink
750 * the node because we don't know its predecessor, so rely
751 * on another call to findPredecessor to notice and return
752 * some earlier predecessor, which it will do. This check is
753 * only strictly needed at beginning of loop, (and the
754 * b.value check isn't strictly needed at all) but is done
755 * each iteration to help avoid contention with other
756 * threads by callers that will fail to be able to change
757 * links, and so will retry anyway.
759 * The traversal loops in doPut, doRemove, and findNear all
760 * include the same three kinds of checks. And specialized
761 * versions appear in findFirst, and findLast and their
762 * variants. They can't easily share code because each uses the
763 * reads of fields held in locals occurring in the orders they
767 * @return node holding key, or null if no such
769 private Node<K,V> findNode(Comparable<? super K> key) {
771 Node<K,V> b = findPredecessor(key);
772 Node<K,V> n = b.next;
776 Node<K,V> f = n.next;
777 if (n != b.next) // inconsistent read
780 if (v == null) { // n is deleted
784 if (v == n || b.value == null) // b is deleted
786 int c = key.compareTo(n.key);
798 * Gets value for key using findNode.
799 * @param okey the key
800 * @return the value, or null if absent
802 private V doGet(Object okey) {
803 Comparable<? super K> key = comparable(okey);
805 * Loop needed here and elsewhere in case value field goes
806 * null just as it is about to be returned, in which case we
807 * lost a race with a deletion, so must retry.
810 Node<K,V> n = findNode(key);
819 /* ---------------- Insertion -------------- */
822 * Main insertion method. Adds element if not present, or
823 * replaces value if present and onlyIfAbsent is false.
824 * @param kkey the key
825 * @param value the value that must be associated with key
826 * @param onlyIfAbsent if should not insert if already present
827 * @return the old value, or null if newly inserted
829 private V doPut(K kkey, V value, boolean onlyIfAbsent) {
830 Comparable<? super K> key = comparable(kkey);
832 Node<K,V> b = findPredecessor(key);
833 Node<K,V> n = b.next;
836 Node<K,V> f = n.next;
837 if (n != b.next) // inconsistent read
840 if (v == null) { // n is deleted
844 if (v == n || b.value == null) // b is deleted
846 int c = key.compareTo(n.key);
853 if (onlyIfAbsent || n.casValue(v, value))
856 break; // restart if lost race to replace value
858 // else c < 0; fall through
861 Node<K,V> z = new Node<K,V>(kkey, value, n);
862 if (!b.casNext(n, z))
863 break; // restart if lost race to append to b
864 int level = randomLevel();
866 insertIndex(z, level);
873 * Returns a random level for inserting a new node.
874 * Hardwired to k=1, p=0.5, max 31 (see above and
875 * Pugh's "Skip List Cookbook", sec 3.4).
877 * This uses the simplest of the generators described in George
878 * Marsaglia's "Xorshift RNGs" paper. This is not a high-quality
879 * generator but is acceptable here.
881 private int randomLevel() {
885 randomSeed = x ^= x << 5;
886 if ((x & 0x80000001) != 0) // test highest and lowest bits
889 while (((x >>>= 1) & 1) != 0) ++level;
894 * Creates and adds index nodes for the given node.
896 * @param level the level of the index
898 private void insertIndex(Node<K,V> z, int level) {
899 HeadIndex<K,V> h = head;
903 Index<K,V> idx = null;
904 for (int i = 1; i <= level; ++i)
905 idx = new Index<K,V>(z, idx, null);
906 addIndex(idx, h, level);
908 } else { // Add a new level
910 * To reduce interference by other threads checking for
911 * empty levels in tryReduceLevel, new levels are added
912 * with initialized right pointers. Which in turn requires
913 * keeping levels in an array to access them while
914 * creating new head index nodes from the opposite
918 Index<K,V>[] idxs = (Index<K,V>[])new Index[level+1];
919 Index<K,V> idx = null;
920 for (int i = 1; i <= level; ++i)
921 idxs[i] = idx = new Index<K,V>(z, idx, null);
927 int oldLevel = oldh.level;
928 if (level <= oldLevel) { // lost race to add level
932 HeadIndex<K,V> newh = oldh;
933 Node<K,V> oldbase = oldh.node;
934 for (int j = oldLevel+1; j <= level; ++j)
935 newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j);
936 if (casHead(oldh, newh)) {
941 addIndex(idxs[k], oldh, k);
946 * Adds given index nodes from given level down to 1.
947 * @param idx the topmost index node being inserted
948 * @param h the value of head to use to insert. This must be
949 * snapshotted by callers to provide correct insertion level
950 * @param indexLevel the level of the index
952 private void addIndex(Index<K,V> idx, HeadIndex<K,V> h, int indexLevel) {
953 // Track next level to insert in case of retries
954 int insertionLevel = indexLevel;
955 Comparable<? super K> key = comparable(idx.node.key);
956 if (key == null) throw new NullPointerException();
958 // Similar to findPredecessor, but adding index nodes along
963 Index<K,V> r = q.right;
967 Node<K,V> n = r.node;
968 // compare before deletion check avoids needing recheck
969 int c = key.compareTo(n.key);
970 if (n.value == null) {
983 if (j == insertionLevel) {
984 // Don't insert index if node already deleted
985 if (t.indexesDeletedNode()) {
986 findNode(key); // cleans up
991 if (--insertionLevel == 0) {
992 // need final deletion check before return
993 if (t.indexesDeletedNode())
999 if (--j >= insertionLevel && j < indexLevel)
1007 /* ---------------- Deletion -------------- */
1010 * Main deletion method. Locates node, nulls value, appends a
1011 * deletion marker, unlinks predecessor, removes associated index
1012 * nodes, and possibly reduces head index level.
1014 * Index nodes are cleared out simply by calling findPredecessor.
1015 * which unlinks indexes to deleted nodes found along path to key,
1016 * which will include the indexes to this node. This is done
1017 * unconditionally. We can't check beforehand whether there are
1018 * index nodes because it might be the case that some or all
1019 * indexes hadn't been inserted yet for this node during initial
1020 * search for it, and we'd like to ensure lack of garbage
1021 * retention, so must call to be sure.
1023 * @param okey the key
1024 * @param value if non-null, the value that must be
1025 * associated with key
1026 * @return the node, or null if not found
1028 final V doRemove(Object okey, Object value) {
1029 Comparable<? super K> key = comparable(okey);
1031 Node<K,V> b = findPredecessor(key);
1032 Node<K,V> n = b.next;
1036 Node<K,V> f = n.next;
1037 if (n != b.next) // inconsistent read
1040 if (v == null) { // n is deleted
1044 if (v == n || b.value == null) // b is deleted
1046 int c = key.compareTo(n.key);
1054 if (value != null && !value.equals(v))
1056 if (!n.casValue(v, null))
1058 if (!n.appendMarker(f) || !b.casNext(n, f))
1059 findNode(key); // Retry via findNode
1061 findPredecessor(key); // Clean index
1062 if (head.right == null)
1071 * Possibly reduce head level if it has no nodes. This method can
1072 * (rarely) make mistakes, in which case levels can disappear even
1073 * though they are about to contain index nodes. This impacts
1074 * performance, not correctness. To minimize mistakes as well as
1075 * to reduce hysteresis, the level is reduced by one only if the
1076 * topmost three levels look empty. Also, if the removed level
1077 * looks non-empty after CAS, we try to change it back quick
1078 * before anyone notices our mistake! (This trick works pretty
1079 * well because this method will practically never make mistakes
1080 * unless current thread stalls immediately before first CAS, in
1081 * which case it is very unlikely to stall again immediately
1082 * afterwards, so will recover.)
1084 * We put up with all this rather than just let levels grow
1085 * because otherwise, even a small map that has undergone a large
1086 * number of insertions and removals will have a lot of levels,
1087 * slowing down access more than would an occasional unwanted
1090 private void tryReduceLevel() {
1091 HeadIndex<K,V> h = head;
1095 (d = (HeadIndex<K,V>)h.down) != null &&
1096 (e = (HeadIndex<K,V>)d.down) != null &&
1100 casHead(h, d) && // try to set
1101 h.right != null) // recheck
1102 casHead(d, h); // try to backout
1105 /* ---------------- Finding and removing first element -------------- */
1108 * Specialized variant of findNode to get first valid node.
1109 * @return first node or null if empty
1111 Node<K,V> findFirst() {
1113 Node<K,V> b = head.node;
1114 Node<K,V> n = b.next;
1117 if (n.value != null)
1119 n.helpDelete(b, n.next);
1124 * Removes first entry; returns its snapshot.
1125 * @return null if empty, else snapshot of first entry
1127 Map.Entry<K,V> doRemoveFirstEntry() {
1129 Node<K,V> b = head.node;
1130 Node<K,V> n = b.next;
1133 Node<K,V> f = n.next;
1141 if (!n.casValue(v, null))
1143 if (!n.appendMarker(f) || !b.casNext(n, f))
1144 findFirst(); // retry
1145 clearIndexToFirst();
1146 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, (V)v);
1151 * Clears out index nodes associated with deleted first entry.
1153 private void clearIndexToFirst() {
1155 Index<K,V> q = head;
1157 Index<K,V> r = q.right;
1158 if (r != null && r.indexesDeletedNode() && !q.unlink(r))
1160 if ((q = q.down) == null) {
1161 if (head.right == null)
1170 /* ---------------- Finding and removing last element -------------- */
1173 * Specialized version of find to get last valid node.
1174 * @return last node or null if empty
1176 Node<K,V> findLast() {
1178 * findPredecessor can't be used to traverse index level
1179 * because this doesn't use comparisons. So traversals of
1180 * both levels are folded together.
1182 Index<K,V> q = head;
1185 if ((r = q.right) != null) {
1186 if (r.indexesDeletedNode()) {
1188 q = head; // restart
1192 } else if ((d = q.down) != null) {
1195 Node<K,V> b = q.node;
1196 Node<K,V> n = b.next;
1199 return b.isBaseHeader() ? null : b;
1200 Node<K,V> f = n.next; // inconsistent read
1204 if (v == null) { // n is deleted
1208 if (v == n || b.value == null) // b is deleted
1213 q = head; // restart
1219 * Specialized variant of findPredecessor to get predecessor of last
1220 * valid node. Needed when removing the last entry. It is possible
1221 * that all successors of returned node will have been deleted upon
1222 * return, in which case this method can be retried.
1223 * @return likely predecessor of last node
1225 private Node<K,V> findPredecessorOfLast() {
1227 Index<K,V> q = head;
1230 if ((r = q.right) != null) {
1231 if (r.indexesDeletedNode()) {
1233 break; // must restart
1235 // proceed as far across as possible without overshooting
1236 if (r.node.next != null) {
1241 if ((d = q.down) != null)
1250 * Removes last entry; returns its snapshot.
1251 * Specialized variant of doRemove.
1252 * @return null if empty, else snapshot of last entry
1254 Map.Entry<K,V> doRemoveLastEntry() {
1256 Node<K,V> b = findPredecessorOfLast();
1257 Node<K,V> n = b.next;
1259 if (b.isBaseHeader()) // empty
1262 continue; // all b's successors are deleted; retry
1265 Node<K,V> f = n.next;
1266 if (n != b.next) // inconsistent read
1269 if (v == null) { // n is deleted
1273 if (v == n || b.value == null) // b is deleted
1280 if (!n.casValue(v, null))
1283 Comparable<? super K> ck = comparable(key);
1284 if (!n.appendMarker(f) || !b.casNext(n, f))
1285 findNode(ck); // Retry via findNode
1287 findPredecessor(ck); // Clean index
1288 if (head.right == null)
1291 return new AbstractMap.SimpleImmutableEntry<K,V>(key, (V)v);
1296 /* ---------------- Relational operations -------------- */
1298 // Control values OR'ed as arguments to findNear
1300 private static final int EQ = 1;
1301 private static final int LT = 2;
1302 private static final int GT = 0; // Actually checked as !LT
1305 * Utility for ceiling, floor, lower, higher methods.
1306 * @param kkey the key
1307 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1308 * @return nearest node fitting relation, or null if no such
1310 Node<K,V> findNear(K kkey, int rel) {
1311 Comparable<? super K> key = comparable(kkey);
1313 Node<K,V> b = findPredecessor(key);
1314 Node<K,V> n = b.next;
1317 return ((rel & LT) == 0 || b.isBaseHeader()) ? null : b;
1318 Node<K,V> f = n.next;
1319 if (n != b.next) // inconsistent read
1322 if (v == null) { // n is deleted
1326 if (v == n || b.value == null) // b is deleted
1328 int c = key.compareTo(n.key);
1329 if ((c == 0 && (rel & EQ) != 0) ||
1330 (c < 0 && (rel & LT) == 0))
1332 if ( c <= 0 && (rel & LT) != 0)
1333 return b.isBaseHeader() ? null : b;
1341 * Returns SimpleImmutableEntry for results of findNear.
1342 * @param key the key
1343 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1344 * @return Entry fitting relation, or null if no such
1346 AbstractMap.SimpleImmutableEntry<K,V> getNear(K key, int rel) {
1348 Node<K,V> n = findNear(key, rel);
1351 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
1358 /* ---------------- Constructors -------------- */
1361 * Constructs a new, empty map, sorted according to the
1362 * {@linkplain Comparable natural ordering} of the keys.
1364 public ConcurrentSkipListMap() {
1365 this.comparator = null;
1370 * Constructs a new, empty map, sorted according to the specified
1373 * @param comparator the comparator that will be used to order this map.
1374 * If <tt>null</tt>, the {@linkplain Comparable natural
1375 * ordering} of the keys will be used.
1377 public ConcurrentSkipListMap(Comparator<? super K> comparator) {
1378 this.comparator = comparator;
1383 * Constructs a new map containing the same mappings as the given map,
1384 * sorted according to the {@linkplain Comparable natural ordering} of
1387 * @param m the map whose mappings are to be placed in this map
1388 * @throws ClassCastException if the keys in <tt>m</tt> are not
1389 * {@link Comparable}, or are not mutually comparable
1390 * @throws NullPointerException if the specified map or any of its keys
1391 * or values are null
1393 public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {
1394 this.comparator = null;
1400 * Constructs a new map containing the same mappings and using the
1401 * same ordering as the specified sorted map.
1403 * @param m the sorted map whose mappings are to be placed in this
1404 * map, and whose comparator is to be used to sort this map
1405 * @throws NullPointerException if the specified sorted map or any of
1406 * its keys or values are null
1408 public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {
1409 this.comparator = m.comparator();
1415 * Returns a shallow copy of this <tt>ConcurrentSkipListMap</tt>
1416 * instance. (The keys and values themselves are not cloned.)
1418 * @return a shallow copy of this map
1420 public ConcurrentSkipListMap<K,V> clone() {
1421 ConcurrentSkipListMap<K,V> clone = null;
1423 clone = (ConcurrentSkipListMap<K,V>) super.clone();
1424 } catch (CloneNotSupportedException e) {
1425 throw new InternalError();
1429 clone.buildFromSorted(this);
1434 * Streamlined bulk insertion to initialize from elements of
1435 * given sorted map. Call only from constructor or clone
1438 private void buildFromSorted(SortedMap<K, ? extends V> map) {
1440 throw new NullPointerException();
1442 HeadIndex<K,V> h = head;
1443 Node<K,V> basepred = h.node;
1445 // Track the current rightmost node at each level. Uses an
1446 // ArrayList to avoid committing to initial or maximum level.
1447 ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1450 for (int i = 0; i <= h.level; ++i)
1453 for (int i = h.level; i > 0; --i) {
1458 Iterator<? extends Map.Entry<? extends K, ? extends V>> it =
1459 map.entrySet().iterator();
1460 while (it.hasNext()) {
1461 Map.Entry<? extends K, ? extends V> e = it.next();
1462 int j = randomLevel();
1463 if (j > h.level) j = h.level + 1;
1466 if (k == null || v == null)
1467 throw new NullPointerException();
1468 Node<K,V> z = new Node<K,V>(k, v, null);
1472 Index<K,V> idx = null;
1473 for (int i = 1; i <= j; ++i) {
1474 idx = new Index<K,V>(z, idx, null);
1476 h = new HeadIndex<K,V>(h.node, h, idx, i);
1478 if (i < preds.size()) {
1479 preds.get(i).right = idx;
1489 /* ---------------- Serialization -------------- */
1492 * Save the state of this map to a stream.
1494 * @serialData The key (Object) and value (Object) for each
1495 * key-value mapping represented by the map, followed by
1496 * <tt>null</tt>. The key-value mappings are emitted in key-order
1497 * (as determined by the Comparator, or by the keys' natural
1498 * ordering if no Comparator).
1500 private void writeObject(java.io.ObjectOutputStream s)
1501 throws java.io.IOException {
1502 // Write out the Comparator and any hidden stuff
1503 s.defaultWriteObject();
1505 // Write out keys and values (alternating)
1506 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1507 V v = n.getValidValue();
1509 s.writeObject(n.key);
1513 s.writeObject(null);
1517 * Reconstitute the map from a stream.
1519 private void readObject(final java.io.ObjectInputStream s)
1520 throws java.io.IOException, ClassNotFoundException {
1521 // Read in the Comparator and any hidden stuff
1522 s.defaultReadObject();
1527 * This is nearly identical to buildFromSorted, but is
1528 * distinct because readObject calls can't be nicely adapted
1529 * as the kind of iterator needed by buildFromSorted. (They
1530 * can be, but doing so requires type cheats and/or creation
1531 * of adaptor classes.) It is simpler to just adapt the code.
1534 HeadIndex<K,V> h = head;
1535 Node<K,V> basepred = h.node;
1536 ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1537 for (int i = 0; i <= h.level; ++i)
1540 for (int i = h.level; i > 0; --i) {
1546 Object k = s.readObject();
1549 Object v = s.readObject();
1551 throw new NullPointerException();
1554 int j = randomLevel();
1555 if (j > h.level) j = h.level + 1;
1556 Node<K,V> z = new Node<K,V>(key, val, null);
1560 Index<K,V> idx = null;
1561 for (int i = 1; i <= j; ++i) {
1562 idx = new Index<K,V>(z, idx, null);
1564 h = new HeadIndex<K,V>(h.node, h, idx, i);
1566 if (i < preds.size()) {
1567 preds.get(i).right = idx;
1577 /* ------ Map API methods ------ */
1580 * Returns <tt>true</tt> if this map contains a mapping for the specified
1583 * @param key key whose presence in this map is to be tested
1584 * @return <tt>true</tt> if this map contains a mapping for the specified key
1585 * @throws ClassCastException if the specified key cannot be compared
1586 * with the keys currently in the map
1587 * @throws NullPointerException if the specified key is null
1589 public boolean containsKey(Object key) {
1590 return doGet(key) != null;
1594 * Returns the value to which the specified key is mapped,
1595 * or {@code null} if this map contains no mapping for the key.
1597 * <p>More formally, if this map contains a mapping from a key
1598 * {@code k} to a value {@code v} such that {@code key} compares
1599 * equal to {@code k} according to the map's ordering, then this
1600 * method returns {@code v}; otherwise it returns {@code null}.
1601 * (There can be at most one such mapping.)
1603 * @throws ClassCastException if the specified key cannot be compared
1604 * with the keys currently in the map
1605 * @throws NullPointerException if the specified key is null
1607 public V get(Object key) {
1612 * Associates the specified value with the specified key in this map.
1613 * If the map previously contained a mapping for the key, the old
1614 * value is replaced.
1616 * @param key key with which the specified value is to be associated
1617 * @param value value to be associated with the specified key
1618 * @return the previous value associated with the specified key, or
1619 * <tt>null</tt> if there was no mapping for the key
1620 * @throws ClassCastException if the specified key cannot be compared
1621 * with the keys currently in the map
1622 * @throws NullPointerException if the specified key or value is null
1624 public V put(K key, V value) {
1626 throw new NullPointerException();
1627 return doPut(key, value, false);
1631 * Removes the mapping for the specified key from this map if present.
1633 * @param key key for which mapping should be removed
1634 * @return the previous value associated with the specified key, or
1635 * <tt>null</tt> if there was no mapping for the key
1636 * @throws ClassCastException if the specified key cannot be compared
1637 * with the keys currently in the map
1638 * @throws NullPointerException if the specified key is null
1640 public V remove(Object key) {
1641 return doRemove(key, null);
1645 * Returns <tt>true</tt> if this map maps one or more keys to the
1646 * specified value. This operation requires time linear in the
1647 * map size. Additionally, it is possible for the map to change
1648 * during execution of this method, in which case the returned
1649 * result may be inaccurate.
1651 * @param value value whose presence in this map is to be tested
1652 * @return <tt>true</tt> if a mapping to <tt>value</tt> exists;
1653 * <tt>false</tt> otherwise
1654 * @throws NullPointerException if the specified value is null
1656 public boolean containsValue(Object value) {
1658 throw new NullPointerException();
1659 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1660 V v = n.getValidValue();
1661 if (v != null && value.equals(v))
1668 * Returns the number of key-value mappings in this map. If this map
1669 * contains more than <tt>Integer.MAX_VALUE</tt> elements, it
1670 * returns <tt>Integer.MAX_VALUE</tt>.
1672 * <p>Beware that, unlike in most collections, this method is
1673 * <em>NOT</em> a constant-time operation. Because of the
1674 * asynchronous nature of these maps, determining the current
1675 * number of elements requires traversing them all to count them.
1676 * Additionally, it is possible for the size to change during
1677 * execution of this method, in which case the returned result
1678 * will be inaccurate. Thus, this method is typically not very
1679 * useful in concurrent applications.
1681 * @return the number of elements in this map
1685 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1686 if (n.getValidValue() != null)
1689 return (count >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) count;
1693 * Returns <tt>true</tt> if this map contains no key-value mappings.
1694 * @return <tt>true</tt> if this map contains no key-value mappings
1696 public boolean isEmpty() {
1697 return findFirst() == null;
1701 * Removes all of the mappings from this map.
1703 public void clear() {
1707 /* ---------------- View methods -------------- */
1710 * Note: Lazy initialization works for views because view classes
1711 * are stateless/immutable so it doesn't matter wrt correctness if
1712 * more than one is created (which will only rarely happen). Even
1713 * so, the following idiom conservatively ensures that the method
1714 * returns the one it created if it does so, not one created by
1715 * another racing thread.
1719 * Returns a {@link NavigableSet} view of the keys contained in this map.
1720 * The set's iterator returns the keys in ascending order.
1721 * The set is backed by the map, so changes to the map are
1722 * reflected in the set, and vice-versa. The set supports element
1723 * removal, which removes the corresponding mapping from the map,
1724 * via the {@code Iterator.remove}, {@code Set.remove},
1725 * {@code removeAll}, {@code retainAll}, and {@code clear}
1726 * operations. It does not support the {@code add} or {@code addAll}
1729 * <p>The view's {@code iterator} is a "weakly consistent" iterator
1730 * that will never throw {@link ConcurrentModificationException},
1731 * and guarantees to traverse elements as they existed upon
1732 * construction of the iterator, and may (but is not guaranteed to)
1733 * reflect any modifications subsequent to construction.
1735 * <p>This method is equivalent to method {@code navigableKeySet}.
1737 * @return a navigable set view of the keys in this map
1739 public NavigableSet<K> keySet() {
1741 return (ks != null) ? ks : (keySet = new KeySet(this));
1744 public NavigableSet<K> navigableKeySet() {
1746 return (ks != null) ? ks : (keySet = new KeySet(this));
1750 * Returns a {@link Collection} view of the values contained in this map.
1751 * The collection's iterator returns the values in ascending order
1752 * of the corresponding keys.
1753 * The collection is backed by the map, so changes to the map are
1754 * reflected in the collection, and vice-versa. The collection
1755 * supports element removal, which removes the corresponding
1756 * mapping from the map, via the <tt>Iterator.remove</tt>,
1757 * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1758 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
1759 * support the <tt>add</tt> or <tt>addAll</tt> operations.
1761 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1762 * that will never throw {@link ConcurrentModificationException},
1763 * and guarantees to traverse elements as they existed upon
1764 * construction of the iterator, and may (but is not guaranteed to)
1765 * reflect any modifications subsequent to construction.
1767 public Collection<V> values() {
1769 return (vs != null) ? vs : (values = new Values(this));
1773 * Returns a {@link Set} view of the mappings contained in this map.
1774 * The set's iterator returns the entries in ascending key order.
1775 * The set is backed by the map, so changes to the map are
1776 * reflected in the set, and vice-versa. The set supports element
1777 * removal, which removes the corresponding mapping from the map,
1778 * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1779 * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
1780 * operations. It does not support the <tt>add</tt> or
1781 * <tt>addAll</tt> operations.
1783 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1784 * that will never throw {@link ConcurrentModificationException},
1785 * and guarantees to traverse elements as they existed upon
1786 * construction of the iterator, and may (but is not guaranteed to)
1787 * reflect any modifications subsequent to construction.
1789 * <p>The <tt>Map.Entry</tt> elements returned by
1790 * <tt>iterator.next()</tt> do <em>not</em> support the
1791 * <tt>setValue</tt> operation.
1793 * @return a set view of the mappings contained in this map,
1794 * sorted in ascending key order
1796 public Set<Map.Entry<K,V>> entrySet() {
1797 EntrySet es = entrySet;
1798 return (es != null) ? es : (entrySet = new EntrySet(this));
1801 public ConcurrentNavigableMap<K,V> descendingMap() {
1802 ConcurrentNavigableMap<K,V> dm = descendingMap;
1803 return (dm != null) ? dm : (descendingMap = new SubMap<K,V>
1804 (this, null, false, null, false, true));
1807 public NavigableSet<K> descendingKeySet() {
1808 return descendingMap().navigableKeySet();
1811 /* ---------------- AbstractMap Overrides -------------- */
1814 * Compares the specified object with this map for equality.
1815 * Returns <tt>true</tt> if the given object is also a map and the
1816 * two maps represent the same mappings. More formally, two maps
1817 * <tt>m1</tt> and <tt>m2</tt> represent the same mappings if
1818 * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This
1819 * operation may return misleading results if either map is
1820 * concurrently modified during execution of this method.
1822 * @param o object to be compared for equality with this map
1823 * @return <tt>true</tt> if the specified object is equal to this map
1825 public boolean equals(Object o) {
1828 if (!(o instanceof Map))
1830 Map<?,?> m = (Map<?,?>) o;
1832 for (Map.Entry<K,V> e : this.entrySet())
1833 if (! e.getValue().equals(m.get(e.getKey())))
1835 for (Map.Entry<?,?> e : m.entrySet()) {
1836 Object k = e.getKey();
1837 Object v = e.getValue();
1838 if (k == null || v == null || !v.equals(get(k)))
1842 } catch (ClassCastException unused) {
1844 } catch (NullPointerException unused) {
1849 /* ------ ConcurrentMap API methods ------ */
1854 * @return the previous value associated with the specified key,
1855 * or <tt>null</tt> if there was no mapping for the key
1856 * @throws ClassCastException if the specified key cannot be compared
1857 * with the keys currently in the map
1858 * @throws NullPointerException if the specified key or value is null
1860 public V putIfAbsent(K key, V value) {
1862 throw new NullPointerException();
1863 return doPut(key, value, true);
1869 * @throws ClassCastException if the specified key cannot be compared
1870 * with the keys currently in the map
1871 * @throws NullPointerException if the specified key is null
1873 public boolean remove(Object key, Object value) {
1875 throw new NullPointerException();
1878 return doRemove(key, value) != null;
1884 * @throws ClassCastException if the specified key cannot be compared
1885 * with the keys currently in the map
1886 * @throws NullPointerException if any of the arguments are null
1888 public boolean replace(K key, V oldValue, V newValue) {
1889 if (oldValue == null || newValue == null)
1890 throw new NullPointerException();
1891 Comparable<? super K> k = comparable(key);
1893 Node<K,V> n = findNode(k);
1898 if (!oldValue.equals(v))
1900 if (n.casValue(v, newValue))
1909 * @return the previous value associated with the specified key,
1910 * or <tt>null</tt> if there was no mapping for the key
1911 * @throws ClassCastException if the specified key cannot be compared
1912 * with the keys currently in the map
1913 * @throws NullPointerException if the specified key or value is null
1915 public V replace(K key, V value) {
1917 throw new NullPointerException();
1918 Comparable<? super K> k = comparable(key);
1920 Node<K,V> n = findNode(k);
1924 if (v != null && n.casValue(v, value))
1929 /* ------ SortedMap API methods ------ */
1931 public Comparator<? super K> comparator() {
1936 * @throws NoSuchElementException {@inheritDoc}
1938 public K firstKey() {
1939 Node<K,V> n = findFirst();
1941 throw new NoSuchElementException();
1946 * @throws NoSuchElementException {@inheritDoc}
1948 public K lastKey() {
1949 Node<K,V> n = findLast();
1951 throw new NoSuchElementException();
1956 * @throws ClassCastException {@inheritDoc}
1957 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
1958 * @throws IllegalArgumentException {@inheritDoc}
1960 public ConcurrentNavigableMap<K,V> subMap(K fromKey,
1961 boolean fromInclusive,
1963 boolean toInclusive) {
1964 if (fromKey == null || toKey == null)
1965 throw new NullPointerException();
1966 return new SubMap<K,V>
1967 (this, fromKey, fromInclusive, toKey, toInclusive, false);
1971 * @throws ClassCastException {@inheritDoc}
1972 * @throws NullPointerException if {@code toKey} is null
1973 * @throws IllegalArgumentException {@inheritDoc}
1975 public ConcurrentNavigableMap<K,V> headMap(K toKey,
1976 boolean inclusive) {
1978 throw new NullPointerException();
1979 return new SubMap<K,V>
1980 (this, null, false, toKey, inclusive, false);
1984 * @throws ClassCastException {@inheritDoc}
1985 * @throws NullPointerException if {@code fromKey} is null
1986 * @throws IllegalArgumentException {@inheritDoc}
1988 public ConcurrentNavigableMap<K,V> tailMap(K fromKey,
1989 boolean inclusive) {
1990 if (fromKey == null)
1991 throw new NullPointerException();
1992 return new SubMap<K,V>
1993 (this, fromKey, inclusive, null, false, false);
1997 * @throws ClassCastException {@inheritDoc}
1998 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
1999 * @throws IllegalArgumentException {@inheritDoc}
2001 public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
2002 return subMap(fromKey, true, toKey, false);
2006 * @throws ClassCastException {@inheritDoc}
2007 * @throws NullPointerException if {@code toKey} is null
2008 * @throws IllegalArgumentException {@inheritDoc}
2010 public ConcurrentNavigableMap<K,V> headMap(K toKey) {
2011 return headMap(toKey, false);
2015 * @throws ClassCastException {@inheritDoc}
2016 * @throws NullPointerException if {@code fromKey} is null
2017 * @throws IllegalArgumentException {@inheritDoc}
2019 public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
2020 return tailMap(fromKey, true);
2023 /* ---------------- Relational operations -------------- */
2026 * Returns a key-value mapping associated with the greatest key
2027 * strictly less than the given key, or <tt>null</tt> if there is
2028 * no such key. The returned entry does <em>not</em> support the
2029 * <tt>Entry.setValue</tt> method.
2031 * @throws ClassCastException {@inheritDoc}
2032 * @throws NullPointerException if the specified key is null
2034 public Map.Entry<K,V> lowerEntry(K key) {
2035 return getNear(key, LT);
2039 * @throws ClassCastException {@inheritDoc}
2040 * @throws NullPointerException if the specified key is null
2042 public K lowerKey(K key) {
2043 Node<K,V> n = findNear(key, LT);
2044 return (n == null) ? null : n.key;
2048 * Returns a key-value mapping associated with the greatest key
2049 * less than or equal to the given key, or <tt>null</tt> if there
2050 * is no such key. The returned entry does <em>not</em> support
2051 * the <tt>Entry.setValue</tt> method.
2053 * @param key the key
2054 * @throws ClassCastException {@inheritDoc}
2055 * @throws NullPointerException if the specified key is null
2057 public Map.Entry<K,V> floorEntry(K key) {
2058 return getNear(key, LT|EQ);
2062 * @param key the key
2063 * @throws ClassCastException {@inheritDoc}
2064 * @throws NullPointerException if the specified key is null
2066 public K floorKey(K key) {
2067 Node<K,V> n = findNear(key, LT|EQ);
2068 return (n == null) ? null : n.key;
2072 * Returns a key-value mapping associated with the least key
2073 * greater than or equal to the given key, or <tt>null</tt> if
2074 * there is no such entry. The returned entry does <em>not</em>
2075 * support the <tt>Entry.setValue</tt> method.
2077 * @throws ClassCastException {@inheritDoc}
2078 * @throws NullPointerException if the specified key is null
2080 public Map.Entry<K,V> ceilingEntry(K key) {
2081 return getNear(key, GT|EQ);
2085 * @throws ClassCastException {@inheritDoc}
2086 * @throws NullPointerException if the specified key is null
2088 public K ceilingKey(K key) {
2089 Node<K,V> n = findNear(key, GT|EQ);
2090 return (n == null) ? null : n.key;
2094 * Returns a key-value mapping associated with the least key
2095 * strictly greater than the given key, or <tt>null</tt> if there
2096 * is no such key. The returned entry does <em>not</em> support
2097 * the <tt>Entry.setValue</tt> method.
2099 * @param key the key
2100 * @throws ClassCastException {@inheritDoc}
2101 * @throws NullPointerException if the specified key is null
2103 public Map.Entry<K,V> higherEntry(K key) {
2104 return getNear(key, GT);
2108 * @param key the key
2109 * @throws ClassCastException {@inheritDoc}
2110 * @throws NullPointerException if the specified key is null
2112 public K higherKey(K key) {
2113 Node<K,V> n = findNear(key, GT);
2114 return (n == null) ? null : n.key;
2118 * Returns a key-value mapping associated with the least
2119 * key in this map, or <tt>null</tt> if the map is empty.
2120 * The returned entry does <em>not</em> support
2121 * the <tt>Entry.setValue</tt> method.
2123 public Map.Entry<K,V> firstEntry() {
2125 Node<K,V> n = findFirst();
2128 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2135 * Returns a key-value mapping associated with the greatest
2136 * key in this map, or <tt>null</tt> if the map is empty.
2137 * The returned entry does <em>not</em> support
2138 * the <tt>Entry.setValue</tt> method.
2140 public Map.Entry<K,V> lastEntry() {
2142 Node<K,V> n = findLast();
2145 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2152 * Removes and returns a key-value mapping associated with
2153 * the least key in this map, or <tt>null</tt> if the map is empty.
2154 * The returned entry does <em>not</em> support
2155 * the <tt>Entry.setValue</tt> method.
2157 public Map.Entry<K,V> pollFirstEntry() {
2158 return doRemoveFirstEntry();
2162 * Removes and returns a key-value mapping associated with
2163 * the greatest key in this map, or <tt>null</tt> if the map is empty.
2164 * The returned entry does <em>not</em> support
2165 * the <tt>Entry.setValue</tt> method.
2167 public Map.Entry<K,V> pollLastEntry() {
2168 return doRemoveLastEntry();
2172 /* ---------------- Iterators -------------- */
2175 * Base of iterator classes:
2177 abstract class Iter<T> implements Iterator<T> {
2178 /** the last node returned by next() */
2179 Node<K,V> lastReturned;
2180 /** the next node to return from next(); */
2182 /** Cache of next value field to maintain weak consistency */
2185 /** Initializes ascending iterator for entire range. */
2191 Object x = next.value;
2192 if (x != null && x != next) {
2199 public final boolean hasNext() {
2200 return next != null;
2203 /** Advances next to higher entry. */
2204 final void advance() {
2206 throw new NoSuchElementException();
2207 lastReturned = next;
2212 Object x = next.value;
2213 if (x != null && x != next) {
2220 public void remove() {
2221 Node<K,V> l = lastReturned;
2223 throw new IllegalStateException();
2224 // It would not be worth all of the overhead to directly
2225 // unlink from here. Using remove is fast enough.
2226 ConcurrentSkipListMap.this.remove(l.key);
2227 lastReturned = null;
2232 final class ValueIterator extends Iter<V> {
2240 final class KeyIterator extends Iter<K> {
2248 final class EntryIterator extends Iter<Map.Entry<K,V>> {
2249 public Map.Entry<K,V> next() {
2253 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2257 // Factory methods for iterators needed by ConcurrentSkipListSet etc
2259 Iterator<K> keyIterator() {
2260 return new KeyIterator();
2263 Iterator<V> valueIterator() {
2264 return new ValueIterator();
2267 Iterator<Map.Entry<K,V>> entryIterator() {
2268 return new EntryIterator();
2271 /* ---------------- View Classes -------------- */
2274 * View classes are static, delegating to a ConcurrentNavigableMap
2275 * to allow use by SubMaps, which outweighs the ugliness of
2276 * needing type-tests for Iterator methods.
2279 static final <E> List<E> toList(Collection<E> c) {
2280 // Using size() here would be a pessimization.
2281 List<E> list = new ArrayList<E>();
2287 static final class KeySet<E>
2288 extends AbstractSet<E> implements NavigableSet<E> {
2289 private final ConcurrentNavigableMap<E,Object> m;
2290 KeySet(ConcurrentNavigableMap<E,Object> map) { m = map; }
2291 public int size() { return m.size(); }
2292 public boolean isEmpty() { return m.isEmpty(); }
2293 public boolean contains(Object o) { return m.containsKey(o); }
2294 public boolean remove(Object o) { return m.remove(o) != null; }
2295 public void clear() { m.clear(); }
2296 public E lower(E e) { return m.lowerKey(e); }
2297 public E floor(E e) { return m.floorKey(e); }
2298 public E ceiling(E e) { return m.ceilingKey(e); }
2299 public E higher(E e) { return m.higherKey(e); }
2300 public Comparator<? super E> comparator() { return m.comparator(); }
2301 public E first() { return m.firstKey(); }
2302 public E last() { return m.lastKey(); }
2303 public E pollFirst() {
2304 Map.Entry<E,Object> e = m.pollFirstEntry();
2305 return (e == null) ? null : e.getKey();
2307 public E pollLast() {
2308 Map.Entry<E,Object> e = m.pollLastEntry();
2309 return (e == null) ? null : e.getKey();
2311 public Iterator<E> iterator() {
2312 if (m instanceof ConcurrentSkipListMap)
2313 return ((ConcurrentSkipListMap<E,Object>)m).keyIterator();
2315 return ((ConcurrentSkipListMap.SubMap<E,Object>)m).keyIterator();
2317 public boolean equals(Object o) {
2320 if (!(o instanceof Set))
2322 Collection<?> c = (Collection<?>) o;
2324 return containsAll(c) && c.containsAll(this);
2325 } catch (ClassCastException unused) {
2327 } catch (NullPointerException unused) {
2331 public Object[] toArray() { return toList(this).toArray(); }
2332 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2333 public Iterator<E> descendingIterator() {
2334 return descendingSet().iterator();
2336 public NavigableSet<E> subSet(E fromElement,
2337 boolean fromInclusive,
2339 boolean toInclusive) {
2340 return new KeySet<E>(m.subMap(fromElement, fromInclusive,
2341 toElement, toInclusive));
2343 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
2344 return new KeySet<E>(m.headMap(toElement, inclusive));
2346 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
2347 return new KeySet<E>(m.tailMap(fromElement, inclusive));
2349 public NavigableSet<E> subSet(E fromElement, E toElement) {
2350 return subSet(fromElement, true, toElement, false);
2352 public NavigableSet<E> headSet(E toElement) {
2353 return headSet(toElement, false);
2355 public NavigableSet<E> tailSet(E fromElement) {
2356 return tailSet(fromElement, true);
2358 public NavigableSet<E> descendingSet() {
2359 return new KeySet(m.descendingMap());
2363 static final class Values<E> extends AbstractCollection<E> {
2364 private final ConcurrentNavigableMap<Object, E> m;
2365 Values(ConcurrentNavigableMap<Object, E> map) {
2368 public Iterator<E> iterator() {
2369 if (m instanceof ConcurrentSkipListMap)
2370 return ((ConcurrentSkipListMap<Object,E>)m).valueIterator();
2372 return ((SubMap<Object,E>)m).valueIterator();
2374 public boolean isEmpty() {
2380 public boolean contains(Object o) {
2381 return m.containsValue(o);
2383 public void clear() {
2386 public Object[] toArray() { return toList(this).toArray(); }
2387 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2390 static final class EntrySet<K1,V1> extends AbstractSet<Map.Entry<K1,V1>> {
2391 private final ConcurrentNavigableMap<K1, V1> m;
2392 EntrySet(ConcurrentNavigableMap<K1, V1> map) {
2396 public Iterator<Map.Entry<K1,V1>> iterator() {
2397 if (m instanceof ConcurrentSkipListMap)
2398 return ((ConcurrentSkipListMap<K1,V1>)m).entryIterator();
2400 return ((SubMap<K1,V1>)m).entryIterator();
2403 public boolean contains(Object o) {
2404 if (!(o instanceof Map.Entry))
2406 Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o;
2407 V1 v = m.get(e.getKey());
2408 return v != null && v.equals(e.getValue());
2410 public boolean remove(Object o) {
2411 if (!(o instanceof Map.Entry))
2413 Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o;
2414 return m.remove(e.getKey(),
2417 public boolean isEmpty() {
2423 public void clear() {
2426 public boolean equals(Object o) {
2429 if (!(o instanceof Set))
2431 Collection<?> c = (Collection<?>) o;
2433 return containsAll(c) && c.containsAll(this);
2434 } catch (ClassCastException unused) {
2436 } catch (NullPointerException unused) {
2440 public Object[] toArray() { return toList(this).toArray(); }
2441 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2445 * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2446 * represent a subrange of mappings of their underlying
2447 * maps. Instances of this class support all methods of their
2448 * underlying maps, differing in that mappings outside their range are
2449 * ignored, and attempts to add mappings outside their ranges result
2450 * in {@link IllegalArgumentException}. Instances of this class are
2451 * constructed only using the <tt>subMap</tt>, <tt>headMap</tt>, and
2452 * <tt>tailMap</tt> methods of their underlying maps.
2456 static final class SubMap<K,V> extends AbstractMap<K,V>
2457 implements ConcurrentNavigableMap<K,V>, Cloneable,
2458 java.io.Serializable {
2459 private static final long serialVersionUID = -7647078645895051609L;
2461 /** Underlying map */
2462 private final ConcurrentSkipListMap<K,V> m;
2463 /** lower bound key, or null if from start */
2465 /** upper bound key, or null if to end */
2467 /** inclusion flag for lo */
2468 private final boolean loInclusive;
2469 /** inclusion flag for hi */
2470 private final boolean hiInclusive;
2472 private final boolean isDescending;
2474 // Lazily initialized view holders
2475 private transient KeySet<K> keySetView;
2476 private transient Set<Map.Entry<K,V>> entrySetView;
2477 private transient Collection<V> valuesView;
2480 * Creates a new submap, initializing all fields
2482 SubMap(ConcurrentSkipListMap<K,V> map,
2483 K fromKey, boolean fromInclusive,
2484 K toKey, boolean toInclusive,
2485 boolean isDescending) {
2486 if (fromKey != null && toKey != null &&
2487 map.compare(fromKey, toKey) > 0)
2488 throw new IllegalArgumentException("inconsistent range");
2492 this.loInclusive = fromInclusive;
2493 this.hiInclusive = toInclusive;
2494 this.isDescending = isDescending;
2497 /* ---------------- Utilities -------------- */
2499 private boolean tooLow(K key) {
2501 int c = m.compare(key, lo);
2502 if (c < 0 || (c == 0 && !loInclusive))
2508 private boolean tooHigh(K key) {
2510 int c = m.compare(key, hi);
2511 if (c > 0 || (c == 0 && !hiInclusive))
2517 private boolean inBounds(K key) {
2518 return !tooLow(key) && !tooHigh(key);
2521 private void checkKeyBounds(K key) throws IllegalArgumentException {
2523 throw new NullPointerException();
2525 throw new IllegalArgumentException("key out of range");
2529 * Returns true if node key is less than upper bound of range
2531 private boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) {
2537 if (k == null) // pass by markers and headers
2539 int c = m.compare(k, hi);
2540 if (c > 0 || (c == 0 && !hiInclusive))
2546 * Returns lowest node. This node might not be in range, so
2547 * most usages need to check bounds
2549 private ConcurrentSkipListMap.Node<K,V> loNode() {
2551 return m.findFirst();
2552 else if (loInclusive)
2553 return m.findNear(lo, m.GT|m.EQ);
2555 return m.findNear(lo, m.GT);
2559 * Returns highest node. This node might not be in range, so
2560 * most usages need to check bounds
2562 private ConcurrentSkipListMap.Node<K,V> hiNode() {
2564 return m.findLast();
2565 else if (hiInclusive)
2566 return m.findNear(hi, m.LT|m.EQ);
2568 return m.findNear(hi, m.LT);
2572 * Returns lowest absolute key (ignoring directonality)
2574 private K lowestKey() {
2575 ConcurrentSkipListMap.Node<K,V> n = loNode();
2579 throw new NoSuchElementException();
2583 * Returns highest absolute key (ignoring directonality)
2585 private K highestKey() {
2586 ConcurrentSkipListMap.Node<K,V> n = hiNode();
2592 throw new NoSuchElementException();
2595 private Map.Entry<K,V> lowestEntry() {
2597 ConcurrentSkipListMap.Node<K,V> n = loNode();
2598 if (!isBeforeEnd(n))
2600 Map.Entry<K,V> e = n.createSnapshot();
2606 private Map.Entry<K,V> highestEntry() {
2608 ConcurrentSkipListMap.Node<K,V> n = hiNode();
2609 if (n == null || !inBounds(n.key))
2611 Map.Entry<K,V> e = n.createSnapshot();
2617 private Map.Entry<K,V> removeLowest() {
2619 Node<K,V> n = loNode();
2625 V v = m.doRemove(k, null);
2627 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2631 private Map.Entry<K,V> removeHighest() {
2633 Node<K,V> n = hiNode();
2639 V v = m.doRemove(k, null);
2641 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2646 * Submap version of ConcurrentSkipListMap.getNearEntry
2648 private Map.Entry<K,V> getNearEntry(K key, int rel) {
2649 if (isDescending) { // adjust relation for direction
2650 if ((rel & m.LT) == 0)
2656 return ((rel & m.LT) != 0) ? null : lowestEntry();
2658 return ((rel & m.LT) != 0) ? highestEntry() : null;
2660 Node<K,V> n = m.findNear(key, rel);
2661 if (n == null || !inBounds(n.key))
2664 V v = n.getValidValue();
2666 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2670 // Almost the same as getNearEntry, except for keys
2671 private K getNearKey(K key, int rel) {
2672 if (isDescending) { // adjust relation for direction
2673 if ((rel & m.LT) == 0)
2679 if ((rel & m.LT) == 0) {
2680 ConcurrentSkipListMap.Node<K,V> n = loNode();
2687 if ((rel & m.LT) != 0) {
2688 ConcurrentSkipListMap.Node<K,V> n = hiNode();
2698 Node<K,V> n = m.findNear(key, rel);
2699 if (n == null || !inBounds(n.key))
2702 V v = n.getValidValue();
2708 /* ---------------- Map API methods -------------- */
2710 public boolean containsKey(Object key) {
2711 if (key == null) throw new NullPointerException();
2713 return inBounds(k) && m.containsKey(k);
2716 public V get(Object key) {
2717 if (key == null) throw new NullPointerException();
2719 return ((!inBounds(k)) ? null : m.get(k));
2722 public V put(K key, V value) {
2723 checkKeyBounds(key);
2724 return m.put(key, value);
2727 public V remove(Object key) {
2729 return (!inBounds(k)) ? null : m.remove(k);
2734 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2737 if (n.getValidValue() != null)
2740 return count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)count;
2743 public boolean isEmpty() {
2744 return !isBeforeEnd(loNode());
2747 public boolean containsValue(Object value) {
2749 throw new NullPointerException();
2750 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2753 V v = n.getValidValue();
2754 if (v != null && value.equals(v))
2760 public void clear() {
2761 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2764 if (n.getValidValue() != null)
2769 /* ---------------- ConcurrentMap API methods -------------- */
2771 public V putIfAbsent(K key, V value) {
2772 checkKeyBounds(key);
2773 return m.putIfAbsent(key, value);
2776 public boolean remove(Object key, Object value) {
2778 return inBounds(k) && m.remove(k, value);
2781 public boolean replace(K key, V oldValue, V newValue) {
2782 checkKeyBounds(key);
2783 return m.replace(key, oldValue, newValue);
2786 public V replace(K key, V value) {
2787 checkKeyBounds(key);
2788 return m.replace(key, value);
2791 /* ---------------- SortedMap API methods -------------- */
2793 public Comparator<? super K> comparator() {
2794 Comparator<? super K> cmp = m.comparator();
2796 return Collections.reverseOrder(cmp);
2802 * Utility to create submaps, where given bounds override
2803 * unbounded(null) ones and/or are checked against bounded ones.
2805 private SubMap<K,V> newSubMap(K fromKey,
2806 boolean fromInclusive,
2808 boolean toInclusive) {
2809 if (isDescending) { // flip senses
2813 boolean ti = fromInclusive;
2814 fromInclusive = toInclusive;
2818 if (fromKey == null) {
2820 fromInclusive = loInclusive;
2823 int c = m.compare(fromKey, lo);
2824 if (c < 0 || (c == 0 && !loInclusive && fromInclusive))
2825 throw new IllegalArgumentException("key out of range");
2829 if (toKey == null) {
2831 toInclusive = hiInclusive;
2834 int c = m.compare(toKey, hi);
2835 if (c > 0 || (c == 0 && !hiInclusive && toInclusive))
2836 throw new IllegalArgumentException("key out of range");
2839 return new SubMap<K,V>(m, fromKey, fromInclusive,
2840 toKey, toInclusive, isDescending);
2843 public SubMap<K,V> subMap(K fromKey,
2844 boolean fromInclusive,
2846 boolean toInclusive) {
2847 if (fromKey == null || toKey == null)
2848 throw new NullPointerException();
2849 return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
2852 public SubMap<K,V> headMap(K toKey,
2853 boolean inclusive) {
2855 throw new NullPointerException();
2856 return newSubMap(null, false, toKey, inclusive);
2859 public SubMap<K,V> tailMap(K fromKey,
2860 boolean inclusive) {
2861 if (fromKey == null)
2862 throw new NullPointerException();
2863 return newSubMap(fromKey, inclusive, null, false);
2866 public SubMap<K,V> subMap(K fromKey, K toKey) {
2867 return subMap(fromKey, true, toKey, false);
2870 public SubMap<K,V> headMap(K toKey) {
2871 return headMap(toKey, false);
2874 public SubMap<K,V> tailMap(K fromKey) {
2875 return tailMap(fromKey, true);
2878 public SubMap<K,V> descendingMap() {
2879 return new SubMap<K,V>(m, lo, loInclusive,
2880 hi, hiInclusive, !isDescending);
2883 /* ---------------- Relational methods -------------- */
2885 public Map.Entry<K,V> ceilingEntry(K key) {
2886 return getNearEntry(key, (m.GT|m.EQ));
2889 public K ceilingKey(K key) {
2890 return getNearKey(key, (m.GT|m.EQ));
2893 public Map.Entry<K,V> lowerEntry(K key) {
2894 return getNearEntry(key, (m.LT));
2897 public K lowerKey(K key) {
2898 return getNearKey(key, (m.LT));
2901 public Map.Entry<K,V> floorEntry(K key) {
2902 return getNearEntry(key, (m.LT|m.EQ));
2905 public K floorKey(K key) {
2906 return getNearKey(key, (m.LT|m.EQ));
2909 public Map.Entry<K,V> higherEntry(K key) {
2910 return getNearEntry(key, (m.GT));
2913 public K higherKey(K key) {
2914 return getNearKey(key, (m.GT));
2917 public K firstKey() {
2918 return isDescending ? highestKey() : lowestKey();
2921 public K lastKey() {
2922 return isDescending ? lowestKey() : highestKey();
2925 public Map.Entry<K,V> firstEntry() {
2926 return isDescending ? highestEntry() : lowestEntry();
2929 public Map.Entry<K,V> lastEntry() {
2930 return isDescending ? lowestEntry() : highestEntry();
2933 public Map.Entry<K,V> pollFirstEntry() {
2934 return isDescending ? removeHighest() : removeLowest();
2937 public Map.Entry<K,V> pollLastEntry() {
2938 return isDescending ? removeLowest() : removeHighest();
2941 /* ---------------- Submap Views -------------- */
2943 public NavigableSet<K> keySet() {
2944 KeySet<K> ks = keySetView;
2945 return (ks != null) ? ks : (keySetView = new KeySet(this));
2948 public NavigableSet<K> navigableKeySet() {
2949 KeySet<K> ks = keySetView;
2950 return (ks != null) ? ks : (keySetView = new KeySet(this));
2953 public Collection<V> values() {
2954 Collection<V> vs = valuesView;
2955 return (vs != null) ? vs : (valuesView = new Values(this));
2958 public Set<Map.Entry<K,V>> entrySet() {
2959 Set<Map.Entry<K,V>> es = entrySetView;
2960 return (es != null) ? es : (entrySetView = new EntrySet(this));
2963 public NavigableSet<K> descendingKeySet() {
2964 return descendingMap().navigableKeySet();
2967 Iterator<K> keyIterator() {
2968 return new SubMapKeyIterator();
2971 Iterator<V> valueIterator() {
2972 return new SubMapValueIterator();
2975 Iterator<Map.Entry<K,V>> entryIterator() {
2976 return new SubMapEntryIterator();
2980 * Variant of main Iter class to traverse through submaps.
2982 abstract class SubMapIter<T> implements Iterator<T> {
2983 /** the last node returned by next() */
2984 Node<K,V> lastReturned;
2985 /** the next node to return from next(); */
2987 /** Cache of next value field to maintain weak consistency */
2992 next = isDescending ? hiNode() : loNode();
2995 Object x = next.value;
2996 if (x != null && x != next) {
2997 if (! inBounds(next.key))
3006 public final boolean hasNext() {
3007 return next != null;
3010 final void advance() {
3012 throw new NoSuchElementException();
3013 lastReturned = next;
3020 private void ascend() {
3025 Object x = next.value;
3026 if (x != null && x != next) {
3027 if (tooHigh(next.key))
3036 private void descend() {
3038 next = m.findNear(lastReturned.key, LT);
3041 Object x = next.value;
3042 if (x != null && x != next) {
3043 if (tooLow(next.key))
3052 public void remove() {
3053 Node<K,V> l = lastReturned;
3055 throw new IllegalStateException();
3057 lastReturned = null;
3062 final class SubMapValueIterator extends SubMapIter<V> {
3070 final class SubMapKeyIterator extends SubMapIter<K> {
3078 final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> {
3079 public Map.Entry<K,V> next() {
3083 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);