0001 /*
0002 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0003 *
0004 * This code is free software; you can redistribute it and/or modify it
0005 * under the terms of the GNU General Public License version 2 only, as
0006 * published by the Free Software Foundation. Sun designates this
0007 * particular file as subject to the "Classpath" exception as provided
0008 * by Sun in the LICENSE file that accompanied this code.
0009 *
0010 * This code is distributed in the hope that it will be useful, but WITHOUT
0011 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0012 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0013 * version 2 for more details (a copy is included in the LICENSE file that
0014 * accompanied this code).
0015 *
0016 * You should have received a copy of the GNU General Public License version
0017 * 2 along with this work; if not, write to the Free Software Foundation,
0018 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0019 *
0020 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0021 * CA 95054 USA or visit www.sun.com if you need additional information or
0022 * have any questions.
0023 */
0024
0025 /*
0026 * This file is available under and governed by the GNU General Public
0027 * License version 2 only, as published by the Free Software Foundation.
0028 * However, the following notice accompanied the original version of this
0029 * file:
0030 *
0031 * Written by Doug Lea with assistance from members of JCP JSR-166
0032 * Expert Group and released to the public domain, as explained at
0033 * http://creativecommons.org/licenses/publicdomain
0034 */
0035
0036 package java.util.concurrent;
0037
0038 import java.util.*;
0039 import java.util.concurrent.atomic.*;
0040
0041 /**
0042 * A scalable concurrent {@link ConcurrentNavigableMap} implementation.
0043 * The map is sorted according to the {@linkplain Comparable natural
0044 * ordering} of its keys, or by a {@link Comparator} provided at map
0045 * creation time, depending on which constructor is used.
0046 *
0047 * <p>This class implements a concurrent variant of <a
0048 * href="http://www.cs.umd.edu/~pugh/">SkipLists</a> providing
0049 * expected average <i>log(n)</i> time cost for the
0050 * <tt>containsKey</tt>, <tt>get</tt>, <tt>put</tt> and
0051 * <tt>remove</tt> operations and their variants. Insertion, removal,
0052 * update, and access operations safely execute concurrently by
0053 * multiple threads. Iterators are <i>weakly consistent</i>, returning
0054 * elements reflecting the state of the map at some point at or since
0055 * the creation of the iterator. They do <em>not</em> throw {@link
0056 * ConcurrentModificationException}, and may proceed concurrently with
0057 * other operations. Ascending key ordered views and their iterators
0058 * are faster than descending ones.
0059 *
0060 * <p>All <tt>Map.Entry</tt> pairs returned by methods in this class
0061 * and its views represent snapshots of mappings at the time they were
0062 * produced. They do <em>not</em> support the <tt>Entry.setValue</tt>
0063 * method. (Note however that it is possible to change mappings in the
0064 * associated map using <tt>put</tt>, <tt>putIfAbsent</tt>, or
0065 * <tt>replace</tt>, depending on exactly which effect you need.)
0066 *
0067 * <p>Beware that, unlike in most collections, the <tt>size</tt>
0068 * method is <em>not</em> a constant-time operation. Because of the
0069 * asynchronous nature of these maps, determining the current number
0070 * of elements requires a traversal of the elements. Additionally,
0071 * the bulk operations <tt>putAll</tt>, <tt>equals</tt>, and
0072 * <tt>clear</tt> are <em>not</em> guaranteed to be performed
0073 * atomically. For example, an iterator operating concurrently with a
0074 * <tt>putAll</tt> operation might view only some of the added
0075 * elements.
0076 *
0077 * <p>This class and its views and iterators implement all of the
0078 * <em>optional</em> methods of the {@link Map} and {@link Iterator}
0079 * interfaces. Like most other concurrent collections, this class does
0080 * <em>not</em> permit the use of <tt>null</tt> keys or values because some
0081 * null return values cannot be reliably distinguished from the absence of
0082 * elements.
0083 *
0084 * <p>This class is a member of the
0085 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
0086 * Java Collections Framework</a>.
0087 *
0088 * @author Doug Lea
0089 * @param <K> the type of keys maintained by this map
0090 * @param <V> the type of mapped values
0091 * @since 1.6
0092 */
0093 public class ConcurrentSkipListMap<K, V> extends AbstractMap<K, V>
0094 implements ConcurrentNavigableMap<K, V>, Cloneable,
0095 java.io.Serializable {
0096 /*
0097 * This class implements a tree-like two-dimensionally linked skip
0098 * list in which the index levels are represented in separate
0099 * nodes from the base nodes holding data. There are two reasons
0100 * for taking this approach instead of the usual array-based
0101 * structure: 1) Array based implementations seem to encounter
0102 * more complexity and overhead 2) We can use cheaper algorithms
0103 * for the heavily-traversed index lists than can be used for the
0104 * base lists. Here's a picture of some of the basics for a
0105 * possible list with 2 levels of index:
0106 *
0107 * Head nodes Index nodes
0108 * +-+ right +-+ +-+
0109 * |2|---------------->| |--------------------->| |->null
0110 * +-+ +-+ +-+
0111 * | down | |
0112 * v v v
0113 * +-+ +-+ +-+ +-+ +-+ +-+
0114 * |1|----------->| |->| |------>| |----------->| |------>| |->null
0115 * +-+ +-+ +-+ +-+ +-+ +-+
0116 * v | | | | |
0117 * Nodes next v v v v v
0118 * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
0119 * | |->|A|->|B|->|C|->|D|->|E|->|F|->|G|->|H|->|I|->|J|->|K|->null
0120 * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
0121 *
0122 * The base lists use a variant of the HM linked ordered set
0123 * algorithm. See Tim Harris, "A pragmatic implementation of
0124 * non-blocking linked lists"
0125 * http://www.cl.cam.ac.uk/~tlh20/publications.html and Maged
0126 * Michael "High Performance Dynamic Lock-Free Hash Tables and
0127 * List-Based Sets"
0128 * http://www.research.ibm.com/people/m/michael/pubs.htm. The
0129 * basic idea in these lists is to mark the "next" pointers of
0130 * deleted nodes when deleting to avoid conflicts with concurrent
0131 * insertions, and when traversing to keep track of triples
0132 * (predecessor, node, successor) in order to detect when and how
0133 * to unlink these deleted nodes.
0134 *
0135 * Rather than using mark-bits to mark list deletions (which can
0136 * be slow and space-intensive using AtomicMarkedReference), nodes
0137 * use direct CAS'able next pointers. On deletion, instead of
0138 * marking a pointer, they splice in another node that can be
0139 * thought of as standing for a marked pointer (indicating this by
0140 * using otherwise impossible field values). Using plain nodes
0141 * acts roughly like "boxed" implementations of marked pointers,
0142 * but uses new nodes only when nodes are deleted, not for every
0143 * link. This requires less space and supports faster
0144 * traversal. Even if marked references were better supported by
0145 * JVMs, traversal using this technique might still be faster
0146 * because any search need only read ahead one more node than
0147 * otherwise required (to check for trailing marker) rather than
0148 * unmasking mark bits or whatever on each read.
0149 *
0150 * This approach maintains the essential property needed in the HM
0151 * algorithm of changing the next-pointer of a deleted node so
0152 * that any other CAS of it will fail, but implements the idea by
0153 * changing the pointer to point to a different node, not by
0154 * marking it. While it would be possible to further squeeze
0155 * space by defining marker nodes not to have key/value fields, it
0156 * isn't worth the extra type-testing overhead. The deletion
0157 * markers are rarely encountered during traversal and are
0158 * normally quickly garbage collected. (Note that this technique
0159 * would not work well in systems without garbage collection.)
0160 *
0161 * In addition to using deletion markers, the lists also use
0162 * nullness of value fields to indicate deletion, in a style
0163 * similar to typical lazy-deletion schemes. If a node's value is
0164 * null, then it is considered logically deleted and ignored even
0165 * though it is still reachable. This maintains proper control of
0166 * concurrent replace vs delete operations -- an attempted replace
0167 * must fail if a delete beat it by nulling field, and a delete
0168 * must return the last non-null value held in the field. (Note:
0169 * Null, rather than some special marker, is used for value fields
0170 * here because it just so happens to mesh with the Map API
0171 * requirement that method get returns null if there is no
0172 * mapping, which allows nodes to remain concurrently readable
0173 * even when deleted. Using any other marker value here would be
0174 * messy at best.)
0175 *
0176 * Here's the sequence of events for a deletion of node n with
0177 * predecessor b and successor f, initially:
0178 *
0179 * +------+ +------+ +------+
0180 * ... | b |------>| n |----->| f | ...
0181 * +------+ +------+ +------+
0182 *
0183 * 1. CAS n's value field from non-null to null.
0184 * From this point on, no public operations encountering
0185 * the node consider this mapping to exist. However, other
0186 * ongoing insertions and deletions might still modify
0187 * n's next pointer.
0188 *
0189 * 2. CAS n's next pointer to point to a new marker node.
0190 * From this point on, no other nodes can be appended to n.
0191 * which avoids deletion errors in CAS-based linked lists.
0192 *
0193 * +------+ +------+ +------+ +------+
0194 * ... | b |------>| n |----->|marker|------>| f | ...
0195 * +------+ +------+ +------+ +------+
0196 *
0197 * 3. CAS b's next pointer over both n and its marker.
0198 * From this point on, no new traversals will encounter n,
0199 * and it can eventually be GCed.
0200 * +------+ +------+
0201 * ... | b |----------------------------------->| f | ...
0202 * +------+ +------+
0203 *
0204 * A failure at step 1 leads to simple retry due to a lost race
0205 * with another operation. Steps 2-3 can fail because some other
0206 * thread noticed during a traversal a node with null value and
0207 * helped out by marking and/or unlinking. This helping-out
0208 * ensures that no thread can become stuck waiting for progress of
0209 * the deleting thread. The use of marker nodes slightly
0210 * complicates helping-out code because traversals must track
0211 * consistent reads of up to four nodes (b, n, marker, f), not
0212 * just (b, n, f), although the next field of a marker is
0213 * immutable, and once a next field is CAS'ed to point to a
0214 * marker, it never again changes, so this requires less care.
0215 *
0216 * Skip lists add indexing to this scheme, so that the base-level
0217 * traversals start close to the locations being found, inserted
0218 * or deleted -- usually base level traversals only traverse a few
0219 * nodes. This doesn't change the basic algorithm except for the
0220 * need to make sure base traversals start at predecessors (here,
0221 * b) that are not (structurally) deleted, otherwise retrying
0222 * after processing the deletion.
0223 *
0224 * Index levels are maintained as lists with volatile next fields,
0225 * using CAS to link and unlink. Races are allowed in index-list
0226 * operations that can (rarely) fail to link in a new index node
0227 * or delete one. (We can't do this of course for data nodes.)
0228 * However, even when this happens, the index lists remain sorted,
0229 * so correctly serve as indices. This can impact performance,
0230 * but since skip lists are probabilistic anyway, the net result
0231 * is that under contention, the effective "p" value may be lower
0232 * than its nominal value. And race windows are kept small enough
0233 * that in practice these failures are rare, even under a lot of
0234 * contention.
0235 *
0236 * The fact that retries (for both base and index lists) are
0237 * relatively cheap due to indexing allows some minor
0238 * simplifications of retry logic. Traversal restarts are
0239 * performed after most "helping-out" CASes. This isn't always
0240 * strictly necessary, but the implicit backoffs tend to help
0241 * reduce other downstream failed CAS's enough to outweigh restart
0242 * cost. This worsens the worst case, but seems to improve even
0243 * highly contended cases.
0244 *
0245 * Unlike most skip-list implementations, index insertion and
0246 * deletion here require a separate traversal pass occuring after
0247 * the base-level action, to add or remove index nodes. This adds
0248 * to single-threaded overhead, but improves contended
0249 * multithreaded performance by narrowing interference windows,
0250 * and allows deletion to ensure that all index nodes will be made
0251 * unreachable upon return from a public remove operation, thus
0252 * avoiding unwanted garbage retention. This is more important
0253 * here than in some other data structures because we cannot null
0254 * out node fields referencing user keys since they might still be
0255 * read by other ongoing traversals.
0256 *
0257 * Indexing uses skip list parameters that maintain good search
0258 * performance while using sparser-than-usual indices: The
0259 * hardwired parameters k=1, p=0.5 (see method randomLevel) mean
0260 * that about one-quarter of the nodes have indices. Of those that
0261 * do, half have one level, a quarter have two, and so on (see
0262 * Pugh's Skip List Cookbook, sec 3.4). The expected total space
0263 * requirement for a map is slightly less than for the current
0264 * implementation of java.util.TreeMap.
0265 *
0266 * Changing the level of the index (i.e, the height of the
0267 * tree-like structure) also uses CAS. The head index has initial
0268 * level/height of one. Creation of an index with height greater
0269 * than the current level adds a level to the head index by
0270 * CAS'ing on a new top-most head. To maintain good performance
0271 * after a lot of removals, deletion methods heuristically try to
0272 * reduce the height if the topmost levels appear to be empty.
0273 * This may encounter races in which it possible (but rare) to
0274 * reduce and "lose" a level just as it is about to contain an
0275 * index (that will then never be encountered). This does no
0276 * structural harm, and in practice appears to be a better option
0277 * than allowing unrestrained growth of levels.
0278 *
0279 * The code for all this is more verbose than you'd like. Most
0280 * operations entail locating an element (or position to insert an
0281 * element). The code to do this can't be nicely factored out
0282 * because subsequent uses require a snapshot of predecessor
0283 * and/or successor and/or value fields which can't be returned
0284 * all at once, at least not without creating yet another object
0285 * to hold them -- creating such little objects is an especially
0286 * bad idea for basic internal search operations because it adds
0287 * to GC overhead. (This is one of the few times I've wished Java
0288 * had macros.) Instead, some traversal code is interleaved within
0289 * insertion and removal operations. The control logic to handle
0290 * all the retry conditions is sometimes twisty. Most search is
0291 * broken into 2 parts. findPredecessor() searches index nodes
0292 * only, returning a base-level predecessor of the key. findNode()
0293 * finishes out the base-level search. Even with this factoring,
0294 * there is a fair amount of near-duplication of code to handle
0295 * variants.
0296 *
0297 * For explanation of algorithms sharing at least a couple of
0298 * features with this one, see Mikhail Fomitchev's thesis
0299 * (http://www.cs.yorku.ca/~mikhail/), Keir Fraser's thesis
0300 * (http://www.cl.cam.ac.uk/users/kaf24/), and Hakan Sundell's
0301 * thesis (http://www.cs.chalmers.se/~phs/).
0302 *
0303 * Given the use of tree-like index nodes, you might wonder why
0304 * this doesn't use some kind of search tree instead, which would
0305 * support somewhat faster search operations. The reason is that
0306 * there are no known efficient lock-free insertion and deletion
0307 * algorithms for search trees. The immutability of the "down"
0308 * links of index nodes (as opposed to mutable "left" fields in
0309 * true trees) makes this tractable using only CAS operations.
0310 *
0311 * Notation guide for local variables
0312 * Node: b, n, f for predecessor, node, successor
0313 * Index: q, r, d for index node, right, down.
0314 * t for another index node
0315 * Head: h
0316 * Levels: j
0317 * Keys: k, key
0318 * Values: v, value
0319 * Comparisons: c
0320 */
0321
0322 private static final long serialVersionUID = -8627078645895051609L;
0323
0324 /**
0325 * Generates the initial random seed for the cheaper per-instance
0326 * random number generators used in randomLevel.
0327 */
0328 private static final Random seedGenerator = new Random();
0329
0330 /**
0331 * Special value used to identify base-level header
0332 */
0333 private static final Object BASE_HEADER = new Object();
0334
0335 /**
0336 * The topmost head index of the skiplist.
0337 */
0338 private transient volatile HeadIndex<K, V> head;
0339
0340 /**
0341 * The comparator used to maintain order in this map, or null
0342 * if using natural ordering.
0343 * @serial
0344 */
0345 private final Comparator<? super K> comparator;
0346
0347 /**
0348 * Seed for simple random number generator. Not volatile since it
0349 * doesn't matter too much if different threads don't see updates.
0350 */
0351 private transient int randomSeed;
0352
0353 /** Lazily initialized key set */
0354 private transient KeySet keySet;
0355 /** Lazily initialized entry set */
0356 private transient EntrySet entrySet;
0357 /** Lazily initialized values collection */
0358 private transient Values values;
0359 /** Lazily initialized descending key set */
0360 private transient ConcurrentNavigableMap<K, V> descendingMap;
0361
0362 /**
0363 * Initializes or resets state. Needed by constructors, clone,
0364 * clear, readObject. and ConcurrentSkipListSet.clone.
0365 * (Note that comparator must be separately initialized.)
0366 */
0367 final void initialize() {
0368 keySet = null;
0369 entrySet = null;
0370 values = null;
0371 descendingMap = null;
0372 randomSeed = seedGenerator.nextInt() | 0x0100; // ensure nonzero
0373 head = new HeadIndex<K, V>(new Node<K, V>(null, BASE_HEADER,
0374 null), null, null, 1);
0375 }
0376
0377 /** Updater for casHead */
0378 private static final AtomicReferenceFieldUpdater<ConcurrentSkipListMap, HeadIndex> headUpdater = AtomicReferenceFieldUpdater
0379 .newUpdater(ConcurrentSkipListMap.class, HeadIndex.class,
0380 "head");
0381
0382 /**
0383 * compareAndSet head node
0384 */
0385 private boolean casHead(HeadIndex<K, V> cmp, HeadIndex<K, V> val) {
0386 return headUpdater.compareAndSet(this , cmp, val);
0387 }
0388
0389 /* ---------------- Nodes -------------- */
0390
0391 /**
0392 * Nodes hold keys and values, and are singly linked in sorted
0393 * order, possibly with some intervening marker nodes. The list is
0394 * headed by a dummy node accessible as head.node. The value field
0395 * is declared only as Object because it takes special non-V
0396 * values for marker and header nodes.
0397 */
0398 static final class Node<K, V> {
0399 final K key;
0400 volatile Object value;
0401 volatile Node<K, V> next;
0402
0403 /**
0404 * Creates a new regular node.
0405 */
0406 Node(K key, Object value, Node<K, V> next) {
0407 this .key = key;
0408 this .value = value;
0409 this .next = next;
0410 }
0411
0412 /**
0413 * Creates a new marker node. A marker is distinguished by
0414 * having its value field point to itself. Marker nodes also
0415 * have null keys, a fact that is exploited in a few places,
0416 * but this doesn't distinguish markers from the base-level
0417 * header node (head.node), which also has a null key.
0418 */
0419 Node(Node<K, V> next) {
0420 this .key = null;
0421 this .value = this ;
0422 this .next = next;
0423 }
0424
0425 /** Updater for casNext */
0426 static final AtomicReferenceFieldUpdater<Node, Node> nextUpdater = AtomicReferenceFieldUpdater
0427 .newUpdater(Node.class, Node.class, "next");
0428
0429 /** Updater for casValue */
0430 static final AtomicReferenceFieldUpdater<Node, Object> valueUpdater = AtomicReferenceFieldUpdater
0431 .newUpdater(Node.class, Object.class, "value");
0432
0433 /**
0434 * compareAndSet value field
0435 */
0436 boolean casValue(Object cmp, Object val) {
0437 return valueUpdater.compareAndSet(this , cmp, val);
0438 }
0439
0440 /**
0441 * compareAndSet next field
0442 */
0443 boolean casNext(Node<K, V> cmp, Node<K, V> val) {
0444 return nextUpdater.compareAndSet(this , cmp, val);
0445 }
0446
0447 /**
0448 * Returns true if this node is a marker. This method isn't
0449 * actually called in any current code checking for markers
0450 * because callers will have already read value field and need
0451 * to use that read (not another done here) and so directly
0452 * test if value points to node.
0453 * @param n a possibly null reference to a node
0454 * @return true if this node is a marker node
0455 */
0456 boolean isMarker() {
0457 return value == this ;
0458 }
0459
0460 /**
0461 * Returns true if this node is the header of base-level list.
0462 * @return true if this node is header node
0463 */
0464 boolean isBaseHeader() {
0465 return value == BASE_HEADER;
0466 }
0467
0468 /**
0469 * Tries to append a deletion marker to this node.
0470 * @param f the assumed current successor of this node
0471 * @return true if successful
0472 */
0473 boolean appendMarker(Node<K, V> f) {
0474 return casNext(f, new Node<K, V>(f));
0475 }
0476
0477 /**
0478 * Helps out a deletion by appending marker or unlinking from
0479 * predecessor. This is called during traversals when value
0480 * field seen to be null.
0481 * @param b predecessor
0482 * @param f successor
0483 */
0484 void helpDelete(Node<K, V> b, Node<K, V> f) {
0485 /*
0486 * Rechecking links and then doing only one of the
0487 * help-out stages per call tends to minimize CAS
0488 * interference among helping threads.
0489 */
0490 if (f == next && this == b.next) {
0491 if (f == null || f.value != f) // not already marked
0492 appendMarker(f);
0493 else
0494 b.casNext(this , f.next);
0495 }
0496 }
0497
0498 /**
0499 * Returns value if this node contains a valid key-value pair,
0500 * else null.
0501 * @return this node's value if it isn't a marker or header or
0502 * is deleted, else null.
0503 */
0504 V getValidValue() {
0505 Object v = value;
0506 if (v == this || v == BASE_HEADER)
0507 return null;
0508 return (V) v;
0509 }
0510
0511 /**
0512 * Creates and returns a new SimpleImmutableEntry holding current
0513 * mapping if this node holds a valid value, else null.
0514 * @return new entry or null
0515 */
0516 AbstractMap.SimpleImmutableEntry<K, V> createSnapshot() {
0517 V v = getValidValue();
0518 if (v == null)
0519 return null;
0520 return new AbstractMap.SimpleImmutableEntry<K, V>(key, v);
0521 }
0522 }
0523
0524 /* ---------------- Indexing -------------- */
0525
0526 /**
0527 * Index nodes represent the levels of the skip list. Note that
0528 * even though both Nodes and Indexes have forward-pointing
0529 * fields, they have different types and are handled in different
0530 * ways, that can't nicely be captured by placing field in a
0531 * shared abstract class.
0532 */
0533 static class Index<K, V> {
0534 final Node<K, V> node;
0535 final Index<K, V> down;
0536 volatile Index<K, V> right;
0537
0538 /**
0539 * Creates index node with given values.
0540 */
0541 Index(Node<K, V> node, Index<K, V> down, Index<K, V> right) {
0542 this .node = node;
0543 this .down = down;
0544 this .right = right;
0545 }
0546
0547 /** Updater for casRight */
0548 static final AtomicReferenceFieldUpdater<Index, Index> rightUpdater = AtomicReferenceFieldUpdater
0549 .newUpdater(Index.class, Index.class, "right");
0550
0551 /**
0552 * compareAndSet right field
0553 */
0554 final boolean casRight(Index<K, V> cmp, Index<K, V> val) {
0555 return rightUpdater.compareAndSet(this , cmp, val);
0556 }
0557
0558 /**
0559 * Returns true if the node this indexes has been deleted.
0560 * @return true if indexed node is known to be deleted
0561 */
0562 final boolean indexesDeletedNode() {
0563 return node.value == null;
0564 }
0565
0566 /**
0567 * Tries to CAS newSucc as successor. To minimize races with
0568 * unlink that may lose this index node, if the node being
0569 * indexed is known to be deleted, it doesn't try to link in.
0570 * @param succ the expected current successor
0571 * @param newSucc the new successor
0572 * @return true if successful
0573 */
0574 final boolean link(Index<K, V> succ, Index<K, V> newSucc) {
0575 Node<K, V> n = node;
0576 newSucc.right = succ;
0577 return n.value != null && casRight(succ, newSucc);
0578 }
0579
0580 /**
0581 * Tries to CAS right field to skip over apparent successor
0582 * succ. Fails (forcing a retraversal by caller) if this node
0583 * is known to be deleted.
0584 * @param succ the expected current successor
0585 * @return true if successful
0586 */
0587 final boolean unlink(Index<K, V> succ) {
0588 return !indexesDeletedNode() && casRight(succ, succ.right);
0589 }
0590 }
0591
0592 /* ---------------- Head nodes -------------- */
0593
0594 /**
0595 * Nodes heading each level keep track of their level.
0596 */
0597 static final class HeadIndex<K, V> extends Index<K, V> {
0598 final int level;
0599
0600 HeadIndex(Node<K, V> node, Index<K, V> down, Index<K, V> right,
0601 int level) {
0602 super (node, down, right);
0603 this .level = level;
0604 }
0605 }
0606
0607 /* ---------------- Comparison utilities -------------- */
0608
0609 /**
0610 * Represents a key with a comparator as a Comparable.
0611 *
0612 * Because most sorted collections seem to use natural ordering on
0613 * Comparables (Strings, Integers, etc), most internal methods are
0614 * geared to use them. This is generally faster than checking
0615 * per-comparison whether to use comparator or comparable because
0616 * it doesn't require a (Comparable) cast for each comparison.
0617 * (Optimizers can only sometimes remove such redundant checks
0618 * themselves.) When Comparators are used,
0619 * ComparableUsingComparators are created so that they act in the
0620 * same way as natural orderings. This penalizes use of
0621 * Comparators vs Comparables, which seems like the right
0622 * tradeoff.
0623 */
0624 static final class ComparableUsingComparator<K> implements
0625 Comparable<K> {
0626 final K actualKey;
0627 final Comparator<? super K> cmp;
0628
0629 ComparableUsingComparator(K key, Comparator<? super K> cmp) {
0630 this .actualKey = key;
0631 this .cmp = cmp;
0632 }
0633
0634 public int compareTo(K k2) {
0635 return cmp.compare(actualKey, k2);
0636 }
0637 }
0638
0639 /**
0640 * If using comparator, return a ComparableUsingComparator, else
0641 * cast key as Comparable, which may cause ClassCastException,
0642 * which is propagated back to caller.
0643 */
0644 private Comparable<? super K> comparable(Object key)
0645 throws ClassCastException {
0646 if (key == null)
0647 throw new NullPointerException();
0648 if (comparator != null)
0649 return new ComparableUsingComparator<K>((K) key, comparator);
0650 else
0651 return (Comparable<? super K>) key;
0652 }
0653
0654 /**
0655 * Compares using comparator or natural ordering. Used when the
0656 * ComparableUsingComparator approach doesn't apply.
0657 */
0658 int compare(K k1, K k2) throws ClassCastException {
0659 Comparator<? super K> cmp = comparator;
0660 if (cmp != null)
0661 return cmp.compare(k1, k2);
0662 else
0663 return ((Comparable<? super K>) k1).compareTo(k2);
0664 }
0665
0666 /**
0667 * Returns true if given key greater than or equal to least and
0668 * strictly less than fence, bypassing either test if least or
0669 * fence are null. Needed mainly in submap operations.
0670 */
0671 boolean inHalfOpenRange(K key, K least, K fence) {
0672 if (key == null)
0673 throw new NullPointerException();
0674 return ((least == null || compare(key, least) >= 0) && (fence == null || compare(
0675 key, fence) < 0));
0676 }
0677
0678 /**
0679 * Returns true if given key greater than or equal to least and less
0680 * or equal to fence. Needed mainly in submap operations.
0681 */
0682 boolean inOpenRange(K key, K least, K fence) {
0683 if (key == null)
0684 throw new NullPointerException();
0685 return ((least == null || compare(key, least) >= 0) && (fence == null || compare(
0686 key, fence) <= 0));
0687 }
0688
0689 /* ---------------- Traversal -------------- */
0690
0691 /**
0692 * Returns a base-level node with key strictly less than given key,
0693 * or the base-level header if there is no such node. Also
0694 * unlinks indexes to deleted nodes found along the way. Callers
0695 * rely on this side-effect of clearing indices to deleted nodes.
0696 * @param key the key
0697 * @return a predecessor of key
0698 */
0699 private Node<K, V> findPredecessor(Comparable<? super K> key) {
0700 if (key == null)
0701 throw new NullPointerException(); // don't postpone errors
0702 for (;;) {
0703 Index<K, V> q = head;
0704 Index<K, V> r = q.right;
0705 for (;;) {
0706 if (r != null) {
0707 Node<K, V> n = r.node;
0708 K k = n.key;
0709 if (n.value == null) {
0710 if (!q.unlink(r))
0711 break; // restart
0712 r = q.right; // reread r
0713 continue;
0714 }
0715 if (key.compareTo(k) > 0) {
0716 q = r;
0717 r = r.right;
0718 continue;
0719 }
0720 }
0721 Index<K, V> d = q.down;
0722 if (d != null) {
0723 q = d;
0724 r = d.right;
0725 } else
0726 return q.node;
0727 }
0728 }
0729 }
0730
0731 /**
0732 * Returns node holding key or null if no such, clearing out any
0733 * deleted nodes seen along the way. Repeatedly traverses at
0734 * base-level looking for key starting at predecessor returned
0735 * from findPredecessor, processing base-level deletions as
0736 * encountered. Some callers rely on this side-effect of clearing
0737 * deleted nodes.
0738 *
0739 * Restarts occur, at traversal step centered on node n, if:
0740 *
0741 * (1) After reading n's next field, n is no longer assumed
0742 * predecessor b's current successor, which means that
0743 * we don't have a consistent 3-node snapshot and so cannot
0744 * unlink any subsequent deleted nodes encountered.
0745 *
0746 * (2) n's value field is null, indicating n is deleted, in
0747 * which case we help out an ongoing structural deletion
0748 * before retrying. Even though there are cases where such
0749 * unlinking doesn't require restart, they aren't sorted out
0750 * here because doing so would not usually outweigh cost of
0751 * restarting.
0752 *
0753 * (3) n is a marker or n's predecessor's value field is null,
0754 * indicating (among other possibilities) that
0755 * findPredecessor returned a deleted node. We can't unlink
0756 * the node because we don't know its predecessor, so rely
0757 * on another call to findPredecessor to notice and return
0758 * some earlier predecessor, which it will do. This check is
0759 * only strictly needed at beginning of loop, (and the
0760 * b.value check isn't strictly needed at all) but is done
0761 * each iteration to help avoid contention with other
0762 * threads by callers that will fail to be able to change
0763 * links, and so will retry anyway.
0764 *
0765 * The traversal loops in doPut, doRemove, and findNear all
0766 * include the same three kinds of checks. And specialized
0767 * versions appear in findFirst, and findLast and their
0768 * variants. They can't easily share code because each uses the
0769 * reads of fields held in locals occurring in the orders they
0770 * were performed.
0771 *
0772 * @param key the key
0773 * @return node holding key, or null if no such
0774 */
0775 private Node<K, V> findNode(Comparable<? super K> key) {
0776 for (;;) {
0777 Node<K, V> b = findPredecessor(key);
0778 Node<K, V> n = b.next;
0779 for (;;) {
0780 if (n == null)
0781 return null;
0782 Node<K, V> f = n.next;
0783 if (n != b.next) // inconsistent read
0784 break;
0785 Object v = n.value;
0786 if (v == null) { // n is deleted
0787 n.helpDelete(b, f);
0788 break;
0789 }
0790 if (v == n || b.value == null) // b is deleted
0791 break;
0792 int c = key.compareTo(n.key);
0793 if (c == 0)
0794 return n;
0795 if (c < 0)
0796 return null;
0797 b = n;
0798 n = f;
0799 }
0800 }
0801 }
0802
0803 /**
0804 * Specialized variant of findNode to perform Map.get. Does a weak
0805 * traversal, not bothering to fix any deleted index nodes,
0806 * returning early if it happens to see key in index, and passing
0807 * over any deleted base nodes, falling back to getUsingFindNode
0808 * only if it would otherwise return value from an ongoing
0809 * deletion. Also uses "bound" to eliminate need for some
0810 * comparisons (see Pugh Cookbook). Also folds uses of null checks
0811 * and node-skipping because markers have null keys.
0812 * @param okey the key
0813 * @return the value, or null if absent
0814 */
0815 private V doGet(Object okey) {
0816 Comparable<? super K> key = comparable(okey);
0817 Node<K, V> bound = null;
0818 Index<K, V> q = head;
0819 Index<K, V> r = q.right;
0820 Node<K, V> n;
0821 K k;
0822 int c;
0823 for (;;) {
0824 Index<K, V> d;
0825 // Traverse rights
0826 if (r != null && (n = r.node) != bound
0827 && (k = n.key) != null) {
0828 if ((c = key.compareTo(k)) > 0) {
0829 q = r;
0830 r = r.right;
0831 continue;
0832 } else if (c == 0) {
0833 Object v = n.value;
0834 return (v != null) ? (V) v : getUsingFindNode(key);
0835 } else
0836 bound = n;
0837 }
0838
0839 // Traverse down
0840 if ((d = q.down) != null) {
0841 q = d;
0842 r = d.right;
0843 } else
0844 break;
0845 }
0846
0847 // Traverse nexts
0848 for (n = q.node.next; n != null; n = n.next) {
0849 if ((k = n.key) != null) {
0850 if ((c = key.compareTo(k)) == 0) {
0851 Object v = n.value;
0852 return (v != null) ? (V) v : getUsingFindNode(key);
0853 } else if (c < 0)
0854 break;
0855 }
0856 }
0857 return null;
0858 }
0859
0860 /**
0861 * Performs map.get via findNode. Used as a backup if doGet
0862 * encounters an in-progress deletion.
0863 * @param key the key
0864 * @return the value, or null if absent
0865 */
0866 private V getUsingFindNode(Comparable<? super K> key) {
0867 /*
0868 * Loop needed here and elsewhere in case value field goes
0869 * null just as it is about to be returned, in which case we
0870 * lost a race with a deletion, so must retry.
0871 */
0872 for (;;) {
0873 Node<K, V> n = findNode(key);
0874 if (n == null)
0875 return null;
0876 Object v = n.value;
0877 if (v != null)
0878 return (V) v;
0879 }
0880 }
0881
0882 /* ---------------- Insertion -------------- */
0883
0884 /**
0885 * Main insertion method. Adds element if not present, or
0886 * replaces value if present and onlyIfAbsent is false.
0887 * @param kkey the key
0888 * @param value the value that must be associated with key
0889 * @param onlyIfAbsent if should not insert if already present
0890 * @return the old value, or null if newly inserted
0891 */
0892 private V doPut(K kkey, V value, boolean onlyIfAbsent) {
0893 Comparable<? super K> key = comparable(kkey);
0894 for (;;) {
0895 Node<K, V> b = findPredecessor(key);
0896 Node<K, V> n = b.next;
0897 for (;;) {
0898 if (n != null) {
0899 Node<K, V> f = n.next;
0900 if (n != b.next) // inconsistent read
0901 break;
0902 ;
0903 Object v = n.value;
0904 if (v == null) { // n is deleted
0905 n.helpDelete(b, f);
0906 break;
0907 }
0908 if (v == n || b.value == null) // b is deleted
0909 break;
0910 int c = key.compareTo(n.key);
0911 if (c > 0) {
0912 b = n;
0913 n = f;
0914 continue;
0915 }
0916 if (c == 0) {
0917 if (onlyIfAbsent || n.casValue(v, value))
0918 return (V) v;
0919 else
0920 break; // restart if lost race to replace value
0921 }
0922 // else c < 0; fall through
0923 }
0924
0925 Node<K, V> z = new Node<K, V>(kkey, value, n);
0926 if (!b.casNext(n, z))
0927 break; // restart if lost race to append to b
0928 int level = randomLevel();
0929 if (level > 0)
0930 insertIndex(z, level);
0931 return null;
0932 }
0933 }
0934 }
0935
0936 /**
0937 * Returns a random level for inserting a new node.
0938 * Hardwired to k=1, p=0.5, max 31 (see above and
0939 * Pugh's "Skip List Cookbook", sec 3.4).
0940 *
0941 * This uses the simplest of the generators described in George
0942 * Marsaglia's "Xorshift RNGs" paper. This is not a high-quality
0943 * generator but is acceptable here.
0944 */
0945 private int randomLevel() {
0946 int x = randomSeed;
0947 x ^= x << 13;
0948 x ^= x >>> 17;
0949 randomSeed = x ^= x << 5;
0950 if ((x & 0x8001) != 0) // test highest and lowest bits
0951 return 0;
0952 int level = 1;
0953 while (((x >>>= 1) & 1) != 0)
0954 ++level;
0955 return level;
0956 }
0957
0958 /**
0959 * Creates and adds index nodes for the given node.
0960 * @param z the node
0961 * @param level the level of the index
0962 */
0963 private void insertIndex(Node<K, V> z, int level) {
0964 HeadIndex<K, V> h = head;
0965 int max = h.level;
0966
0967 if (level <= max) {
0968 Index<K, V> idx = null;
0969 for (int i = 1; i <= level; ++i)
0970 idx = new Index<K, V>(z, idx, null);
0971 addIndex(idx, h, level);
0972
0973 } else { // Add a new level
0974 /*
0975 * To reduce interference by other threads checking for
0976 * empty levels in tryReduceLevel, new levels are added
0977 * with initialized right pointers. Which in turn requires
0978 * keeping levels in an array to access them while
0979 * creating new head index nodes from the opposite
0980 * direction.
0981 */
0982 level = max + 1;
0983 Index<K, V>[] idxs = (Index<K, V>[]) new Index[level + 1];
0984 Index<K, V> idx = null;
0985 for (int i = 1; i <= level; ++i)
0986 idxs[i] = idx = new Index<K, V>(z, idx, null);
0987
0988 HeadIndex<K, V> oldh;
0989 int k;
0990 for (;;) {
0991 oldh = head;
0992 int oldLevel = oldh.level;
0993 if (level <= oldLevel) { // lost race to add level
0994 k = level;
0995 break;
0996 }
0997 HeadIndex<K, V> newh = oldh;
0998 Node<K, V> oldbase = oldh.node;
0999 for (int j = oldLevel + 1; j <= level; ++j)
1000 newh = new HeadIndex<K, V>(oldbase, newh, idxs[j],
1001 j);
1002 if (casHead(oldh, newh)) {
1003 k = oldLevel;
1004 break;
1005 }
1006 }
1007 addIndex(idxs[k], oldh, k);
1008 }
1009 }
1010
1011 /**
1012 * Adds given index nodes from given level down to 1.
1013 * @param idx the topmost index node being inserted
1014 * @param h the value of head to use to insert. This must be
1015 * snapshotted by callers to provide correct insertion level
1016 * @param indexLevel the level of the index
1017 */
1018 private void addIndex(Index<K, V> idx, HeadIndex<K, V> h,
1019 int indexLevel) {
1020 // Track next level to insert in case of retries
1021 int insertionLevel = indexLevel;
1022 Comparable<? super K> key = comparable(idx.node.key);
1023 if (key == null)
1024 throw new NullPointerException();
1025
1026 // Similar to findPredecessor, but adding index nodes along
1027 // path to key.
1028 for (;;) {
1029 int j = h.level;
1030 Index<K, V> q = h;
1031 Index<K, V> r = q.right;
1032 Index<K, V> t = idx;
1033 for (;;) {
1034 if (r != null) {
1035 Node<K, V> n = r.node;
1036 // compare before deletion check avoids needing recheck
1037 int c = key.compareTo(n.key);
1038 if (n.value == null) {
1039 if (!q.unlink(r))
1040 break;
1041 r = q.right;
1042 continue;
1043 }
1044 if (c > 0) {
1045 q = r;
1046 r = r.right;
1047 continue;
1048 }
1049 }
1050
1051 if (j == insertionLevel) {
1052 // Don't insert index if node already deleted
1053 if (t.indexesDeletedNode()) {
1054 findNode(key); // cleans up
1055 return;
1056 }
1057 if (!q.link(r, t))
1058 break; // restart
1059 if (--insertionLevel == 0) {
1060 // need final deletion check before return
1061 if (t.indexesDeletedNode())
1062 findNode(key);
1063 return;
1064 }
1065 }
1066
1067 if (--j >= insertionLevel && j < indexLevel)
1068 t = t.down;
1069 q = q.down;
1070 r = q.right;
1071 }
1072 }
1073 }
1074
1075 /* ---------------- Deletion -------------- */
1076
1077 /**
1078 * Main deletion method. Locates node, nulls value, appends a
1079 * deletion marker, unlinks predecessor, removes associated index
1080 * nodes, and possibly reduces head index level.
1081 *
1082 * Index nodes are cleared out simply by calling findPredecessor.
1083 * which unlinks indexes to deleted nodes found along path to key,
1084 * which will include the indexes to this node. This is done
1085 * unconditionally. We can't check beforehand whether there are
1086 * index nodes because it might be the case that some or all
1087 * indexes hadn't been inserted yet for this node during initial
1088 * search for it, and we'd like to ensure lack of garbage
1089 * retention, so must call to be sure.
1090 *
1091 * @param okey the key
1092 * @param value if non-null, the value that must be
1093 * associated with key
1094 * @return the node, or null if not found
1095 */
1096 final V doRemove(Object okey, Object value) {
1097 Comparable<? super K> key = comparable(okey);
1098 for (;;) {
1099 Node<K, V> b = findPredecessor(key);
1100 Node<K, V> n = b.next;
1101 for (;;) {
1102 if (n == null)
1103 return null;
1104 Node<K, V> f = n.next;
1105 if (n != b.next) // inconsistent read
1106 break;
1107 Object v = n.value;
1108 if (v == null) { // n is deleted
1109 n.helpDelete(b, f);
1110 break;
1111 }
1112 if (v == n || b.value == null) // b is deleted
1113 break;
1114 int c = key.compareTo(n.key);
1115 if (c < 0)
1116 return null;
1117 if (c > 0) {
1118 b = n;
1119 n = f;
1120 continue;
1121 }
1122 if (value != null && !value.equals(v))
1123 return null;
1124 if (!n.casValue(v, null))
1125 break;
1126 if (!n.appendMarker(f) || !b.casNext(n, f))
1127 findNode(key); // Retry via findNode
1128 else {
1129 findPredecessor(key); // Clean index
1130 if (head.right == null)
1131 tryReduceLevel();
1132 }
1133 return (V) v;
1134 }
1135 }
1136 }
1137
1138 /**
1139 * Possibly reduce head level if it has no nodes. This method can
1140 * (rarely) make mistakes, in which case levels can disappear even
1141 * though they are about to contain index nodes. This impacts
1142 * performance, not correctness. To minimize mistakes as well as
1143 * to reduce hysteresis, the level is reduced by one only if the
1144 * topmost three levels look empty. Also, if the removed level
1145 * looks non-empty after CAS, we try to change it back quick
1146 * before anyone notices our mistake! (This trick works pretty
1147 * well because this method will practically never make mistakes
1148 * unless current thread stalls immediately before first CAS, in
1149 * which case it is very unlikely to stall again immediately
1150 * afterwards, so will recover.)
1151 *
1152 * We put up with all this rather than just let levels grow
1153 * because otherwise, even a small map that has undergone a large
1154 * number of insertions and removals will have a lot of levels,
1155 * slowing down access more than would an occasional unwanted
1156 * reduction.
1157 */
1158 private void tryReduceLevel() {
1159 HeadIndex<K, V> h = head;
1160 HeadIndex<K, V> d;
1161 HeadIndex<K, V> e;
1162 if (h.level > 3 && (d = (HeadIndex<K, V>) h.down) != null
1163 && (e = (HeadIndex<K, V>) d.down) != null
1164 && e.right == null && d.right == null
1165 && h.right == null && casHead(h, d) && // try to set
1166 h.right != null) // recheck
1167 casHead(d, h); // try to backout
1168 }
1169
1170 /* ---------------- Finding and removing first element -------------- */
1171
1172 /**
1173 * Specialized variant of findNode to get first valid node.
1174 * @return first node or null if empty
1175 */
1176 Node<K, V> findFirst() {
1177 for (;;) {
1178 Node<K, V> b = head.node;
1179 Node<K, V> n = b.next;
1180 if (n == null)
1181 return null;
1182 if (n.value != null)
1183 return n;
1184 n.helpDelete(b, n.next);
1185 }
1186 }
1187
1188 /**
1189 * Removes first entry; returns its snapshot.
1190 * @return null if empty, else snapshot of first entry
1191 */
1192 Map.Entry<K, V> doRemoveFirstEntry() {
1193 for (;;) {
1194 Node<K, V> b = head.node;
1195 Node<K, V> n = b.next;
1196 if (n == null)
1197 return null;
1198 Node<K, V> f = n.next;
1199 if (n != b.next)
1200 continue;
1201 Object v = n.value;
1202 if (v == null) {
1203 n.helpDelete(b, f);
1204 continue;
1205 }
1206 if (!n.casValue(v, null))
1207 continue;
1208 if (!n.appendMarker(f) || !b.casNext(n, f))
1209 findFirst(); // retry
1210 clearIndexToFirst();
1211 return new AbstractMap.SimpleImmutableEntry<K, V>(n.key,
1212 (V) v);
1213 }
1214 }
1215
1216 /**
1217 * Clears out index nodes associated with deleted first entry.
1218 */
1219 private void clearIndexToFirst() {
1220 for (;;) {
1221 Index<K, V> q = head;
1222 for (;;) {
1223 Index<K, V> r = q.right;
1224 if (r != null && r.indexesDeletedNode() && !q.unlink(r))
1225 break;
1226 if ((q = q.down) == null) {
1227 if (head.right == null)
1228 tryReduceLevel();
1229 return;
1230 }
1231 }
1232 }
1233 }
1234
1235 /* ---------------- Finding and removing last element -------------- */
1236
1237 /**
1238 * Specialized version of find to get last valid node.
1239 * @return last node or null if empty
1240 */
1241 Node<K, V> findLast() {
1242 /*
1243 * findPredecessor can't be used to traverse index level
1244 * because this doesn't use comparisons. So traversals of
1245 * both levels are folded together.
1246 */
1247 Index<K, V> q = head;
1248 for (;;) {
1249 Index<K, V> d, r;
1250 if ((r = q.right) != null) {
1251 if (r.indexesDeletedNode()) {
1252 q.unlink(r);
1253 q = head; // restart
1254 } else
1255 q = r;
1256 } else if ((d = q.down) != null) {
1257 q = d;
1258 } else {
1259 Node<K, V> b = q.node;
1260 Node<K, V> n = b.next;
1261 for (;;) {
1262 if (n == null)
1263 return (b.isBaseHeader()) ? null : b;
1264 Node<K, V> f = n.next; // inconsistent read
1265 if (n != b.next)
1266 break;
1267 Object v = n.value;
1268 if (v == null) { // n is deleted
1269 n.helpDelete(b, f);
1270 break;
1271 }
1272 if (v == n || b.value == null) // b is deleted
1273 break;
1274 b = n;
1275 n = f;
1276 }
1277 q = head; // restart
1278 }
1279 }
1280 }
1281
1282 /**
1283 * Specialized variant of findPredecessor to get predecessor of last
1284 * valid node. Needed when removing the last entry. It is possible
1285 * that all successors of returned node will have been deleted upon
1286 * return, in which case this method can be retried.
1287 * @return likely predecessor of last node
1288 */
1289 private Node<K, V> findPredecessorOfLast() {
1290 for (;;) {
1291 Index<K, V> q = head;
1292 for (;;) {
1293 Index<K, V> d, r;
1294 if ((r = q.right) != null) {
1295 if (r.indexesDeletedNode()) {
1296 q.unlink(r);
1297 break; // must restart
1298 }
1299 // proceed as far across as possible without overshooting
1300 if (r.node.next != null) {
1301 q = r;
1302 continue;
1303 }
1304 }
1305 if ((d = q.down) != null)
1306 q = d;
1307 else
1308 return q.node;
1309 }
1310 }
1311 }
1312
1313 /**
1314 * Removes last entry; returns its snapshot.
1315 * Specialized variant of doRemove.
1316 * @return null if empty, else snapshot of last entry
1317 */
1318 Map.Entry<K, V> doRemoveLastEntry() {
1319 for (;;) {
1320 Node<K, V> b = findPredecessorOfLast();
1321 Node<K, V> n = b.next;
1322 if (n == null) {
1323 if (b.isBaseHeader()) // empty
1324 return null;
1325 else
1326 continue; // all b's successors are deleted; retry
1327 }
1328 for (;;) {
1329 Node<K, V> f = n.next;
1330 if (n != b.next) // inconsistent read
1331 break;
1332 Object v = n.value;
1333 if (v == null) { // n is deleted
1334 n.helpDelete(b, f);
1335 break;
1336 }
1337 if (v == n || b.value == null) // b is deleted
1338 break;
1339 if (f != null) {
1340 b = n;
1341 n = f;
1342 continue;
1343 }
1344 if (!n.casValue(v, null))
1345 break;
1346 K key = n.key;
1347 Comparable<? super K> ck = comparable(key);
1348 if (!n.appendMarker(f) || !b.casNext(n, f))
1349 findNode(ck); // Retry via findNode
1350 else {
1351 findPredecessor(ck); // Clean index
1352 if (head.right == null)
1353 tryReduceLevel();
1354 }
1355 return new AbstractMap.SimpleImmutableEntry<K, V>(key,
1356 (V) v);
1357 }
1358 }
1359 }
1360
1361 /* ---------------- Relational operations -------------- */
1362
1363 // Control values OR'ed as arguments to findNear
1364 private static final int EQ = 1;
1365 private static final int LT = 2;
1366 private static final int GT = 0; // Actually checked as !LT
1367
1368 /**
1369 * Utility for ceiling, floor, lower, higher methods.
1370 * @param kkey the key
1371 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1372 * @return nearest node fitting relation, or null if no such
1373 */
1374 Node<K, V> findNear(K kkey, int rel) {
1375 Comparable<? super K> key = comparable(kkey);
1376 for (;;) {
1377 Node<K, V> b = findPredecessor(key);
1378 Node<K, V> n = b.next;
1379 for (;;) {
1380 if (n == null)
1381 return ((rel & LT) == 0 || b.isBaseHeader()) ? null
1382 : b;
1383 Node<K, V> f = n.next;
1384 if (n != b.next) // inconsistent read
1385 break;
1386 Object v = n.value;
1387 if (v == null) { // n is deleted
1388 n.helpDelete(b, f);
1389 break;
1390 }
1391 if (v == n || b.value == null) // b is deleted
1392 break;
1393 int c = key.compareTo(n.key);
1394 if ((c == 0 && (rel & EQ) != 0)
1395 || (c < 0 && (rel & LT) == 0))
1396 return n;
1397 if (c <= 0 && (rel & LT) != 0)
1398 return (b.isBaseHeader()) ? null : b;
1399 b = n;
1400 n = f;
1401 }
1402 }
1403 }
1404
1405 /**
1406 * Returns SimpleImmutableEntry for results of findNear.
1407 * @param key the key
1408 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1409 * @return Entry fitting relation, or null if no such
1410 */
1411 AbstractMap.SimpleImmutableEntry<K, V> getNear(K key, int rel) {
1412 for (;;) {
1413 Node<K, V> n = findNear(key, rel);
1414 if (n == null)
1415 return null;
1416 AbstractMap.SimpleImmutableEntry<K, V> e = n
1417 .createSnapshot();
1418 if (e != null)
1419 return e;
1420 }
1421 }
1422
1423 /* ---------------- Constructors -------------- */
1424
1425 /**
1426 * Constructs a new, empty map, sorted according to the
1427 * {@linkplain Comparable natural ordering} of the keys.
1428 */
1429 public ConcurrentSkipListMap() {
1430 this .comparator = null;
1431 initialize();
1432 }
1433
1434 /**
1435 * Constructs a new, empty map, sorted according to the specified
1436 * comparator.
1437 *
1438 * @param comparator the comparator that will be used to order this map.
1439 * If <tt>null</tt>, the {@linkplain Comparable natural
1440 * ordering} of the keys will be used.
1441 */
1442 public ConcurrentSkipListMap(Comparator<? super K> comparator) {
1443 this .comparator = comparator;
1444 initialize();
1445 }
1446
1447 /**
1448 * Constructs a new map containing the same mappings as the given map,
1449 * sorted according to the {@linkplain Comparable natural ordering} of
1450 * the keys.
1451 *
1452 * @param m the map whose mappings are to be placed in this map
1453 * @throws ClassCastException if the keys in <tt>m</tt> are not
1454 * {@link Comparable}, or are not mutually comparable
1455 * @throws NullPointerException if the specified map or any of its keys
1456 * or values are null
1457 */
1458 public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {
1459 this .comparator = null;
1460 initialize();
1461 putAll(m);
1462 }
1463
1464 /**
1465 * Constructs a new map containing the same mappings and using the
1466 * same ordering as the specified sorted map.
1467 *
1468 * @param m the sorted map whose mappings are to be placed in this
1469 * map, and whose comparator is to be used to sort this map
1470 * @throws NullPointerException if the specified sorted map or any of
1471 * its keys or values are null
1472 */
1473 public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {
1474 this .comparator = m.comparator();
1475 initialize();
1476 buildFromSorted(m);
1477 }
1478
1479 /**
1480 * Returns a shallow copy of this <tt>ConcurrentSkipListMap</tt>
1481 * instance. (The keys and values themselves are not cloned.)
1482 *
1483 * @return a shallow copy of this map
1484 */
1485 public ConcurrentSkipListMap<K, V> clone() {
1486 ConcurrentSkipListMap<K, V> clone = null;
1487 try {
1488 clone = (ConcurrentSkipListMap<K, V>) super .clone();
1489 } catch (CloneNotSupportedException e) {
1490 throw new InternalError();
1491 }
1492
1493 clone.initialize();
1494 clone.buildFromSorted(this );
1495 return clone;
1496 }
1497
1498 /**
1499 * Streamlined bulk insertion to initialize from elements of
1500 * given sorted map. Call only from constructor or clone
1501 * method.
1502 */
1503 private void buildFromSorted(SortedMap<K, ? extends V> map) {
1504 if (map == null)
1505 throw new NullPointerException();
1506
1507 HeadIndex<K, V> h = head;
1508 Node<K, V> basepred = h.node;
1509
1510 // Track the current rightmost node at each level. Uses an
1511 // ArrayList to avoid committing to initial or maximum level.
1512 ArrayList<Index<K, V>> preds = new ArrayList<Index<K, V>>();
1513
1514 // initialize
1515 for (int i = 0; i <= h.level; ++i)
1516 preds.add(null);
1517 Index<K, V> q = h;
1518 for (int i = h.level; i > 0; --i) {
1519 preds.set(i, q);
1520 q = q.down;
1521 }
1522
1523 Iterator<? extends Map.Entry<? extends K, ? extends V>> it = map
1524 .entrySet().iterator();
1525 while (it.hasNext()) {
1526 Map.Entry<? extends K, ? extends V> e = it.next();
1527 int j = randomLevel();
1528 if (j > h.level)
1529 j = h.level + 1;
1530 K k = e.getKey();
1531 V v = e.getValue();
1532 if (k == null || v == null)
1533 throw new NullPointerException();
1534 Node<K, V> z = new Node<K, V>(k, v, null);
1535 basepred.next = z;
1536 basepred = z;
1537 if (j > 0) {
1538 Index<K, V> idx = null;
1539 for (int i = 1; i <= j; ++i) {
1540 idx = new Index<K, V>(z, idx, null);
1541 if (i > h.level)
1542 h = new HeadIndex<K, V>(h.node, h, idx, i);
1543
1544 if (i < preds.size()) {
1545 preds.get(i).right = idx;
1546 preds.set(i, idx);
1547 } else
1548 preds.add(idx);
1549 }
1550 }
1551 }
1552 head = h;
1553 }
1554
1555 /* ---------------- Serialization -------------- */
1556
1557 /**
1558 * Save the state of this map to a stream.
1559 *
1560 * @serialData The key (Object) and value (Object) for each
1561 * key-value mapping represented by the map, followed by
1562 * <tt>null</tt>. The key-value mappings are emitted in key-order
1563 * (as determined by the Comparator, or by the keys' natural
1564 * ordering if no Comparator).
1565 */
1566 private void writeObject(java.io.ObjectOutputStream s)
1567 throws java.io.IOException {
1568 // Write out the Comparator and any hidden stuff
1569 s.defaultWriteObject();
1570
1571 // Write out keys and values (alternating)
1572 for (Node<K, V> n = findFirst(); n != null; n = n.next) {
1573 V v = n.getValidValue();
1574 if (v != null) {
1575 s.writeObject(n.key);
1576 s.writeObject(v);
1577 }
1578 }
1579 s.writeObject(null);
1580 }
1581
1582 /**
1583 * Reconstitute the map from a stream.
1584 */
1585 private void readObject(final java.io.ObjectInputStream s)
1586 throws java.io.IOException, ClassNotFoundException {
1587 // Read in the Comparator and any hidden stuff
1588 s.defaultReadObject();
1589 // Reset transients
1590 initialize();
1591
1592 /*
1593 * This is nearly identical to buildFromSorted, but is
1594 * distinct because readObject calls can't be nicely adapted
1595 * as the kind of iterator needed by buildFromSorted. (They
1596 * can be, but doing so requires type cheats and/or creation
1597 * of adaptor classes.) It is simpler to just adapt the code.
1598 */
1599
1600 HeadIndex<K, V> h = head;
1601 Node<K, V> basepred = h.node;
1602 ArrayList<Index<K, V>> preds = new ArrayList<Index<K, V>>();
1603 for (int i = 0; i <= h.level; ++i)
1604 preds.add(null);
1605 Index<K, V> q = h;
1606 for (int i = h.level; i > 0; --i) {
1607 preds.set(i, q);
1608 q = q.down;
1609 }
1610
1611 for (;;) {
1612 Object k = s.readObject();
1613 if (k == null)
1614 break;
1615 Object v = s.readObject();
1616 if (v == null)
1617 throw new NullPointerException();
1618 K key = (K) k;
1619 V val = (V) v;
1620 int j = randomLevel();
1621 if (j > h.level)
1622 j = h.level + 1;
1623 Node<K, V> z = new Node<K, V>(key, val, null);
1624 basepred.next = z;
1625 basepred = z;
1626 if (j > 0) {
1627 Index<K, V> idx = null;
1628 for (int i = 1; i <= j; ++i) {
1629 idx = new Index<K, V>(z, idx, null);
1630 if (i > h.level)
1631 h = new HeadIndex<K, V>(h.node, h, idx, i);
1632
1633 if (i < preds.size()) {
1634 preds.get(i).right = idx;
1635 preds.set(i, idx);
1636 } else
1637 preds.add(idx);
1638 }
1639 }
1640 }
1641 head = h;
1642 }
1643
1644 /* ------ Map API methods ------ */
1645
1646 /**
1647 * Returns <tt>true</tt> if this map contains a mapping for the specified
1648 * key.
1649 *
1650 * @param key key whose presence in this map is to be tested
1651 * @return <tt>true</tt> if this map contains a mapping for the specified key
1652 * @throws ClassCastException if the specified key cannot be compared
1653 * with the keys currently in the map
1654 * @throws NullPointerException if the specified key is null
1655 */
1656 public boolean containsKey(Object key) {
1657 return doGet(key) != null;
1658 }
1659
1660 /**
1661 * Returns the value to which the specified key is mapped,
1662 * or {@code null} if this map contains no mapping for the key.
1663 *
1664 * <p>More formally, if this map contains a mapping from a key
1665 * {@code k} to a value {@code v} such that {@code key} compares
1666 * equal to {@code k} according to the map's ordering, then this
1667 * method returns {@code v}; otherwise it returns {@code null}.
1668 * (There can be at most one such mapping.)
1669 *
1670 * @throws ClassCastException if the specified key cannot be compared
1671 * with the keys currently in the map
1672 * @throws NullPointerException if the specified key is null
1673 */
1674 public V get(Object key) {
1675 return doGet(key);
1676 }
1677
1678 /**
1679 * Associates the specified value with the specified key in this map.
1680 * If the map previously contained a mapping for the key, the old
1681 * value is replaced.
1682 *
1683 * @param key key with which the specified value is to be associated
1684 * @param value value to be associated with the specified key
1685 * @return the previous value associated with the specified key, or
1686 * <tt>null</tt> if there was no mapping for the key
1687 * @throws ClassCastException if the specified key cannot be compared
1688 * with the keys currently in the map
1689 * @throws NullPointerException if the specified key or value is null
1690 */
1691 public V put(K key, V value) {
1692 if (value == null)
1693 throw new NullPointerException();
1694 return doPut(key, value, false);
1695 }
1696
1697 /**
1698 * Removes the mapping for the specified key from this map if present.
1699 *
1700 * @param key key for which mapping should be removed
1701 * @return the previous value associated with the specified key, or
1702 * <tt>null</tt> if there was no mapping for the key
1703 * @throws ClassCastException if the specified key cannot be compared
1704 * with the keys currently in the map
1705 * @throws NullPointerException if the specified key is null
1706 */
1707 public V remove(Object key) {
1708 return doRemove(key, null);
1709 }
1710
1711 /**
1712 * Returns <tt>true</tt> if this map maps one or more keys to the
1713 * specified value. This operation requires time linear in the
1714 * map size.
1715 *
1716 * @param value value whose presence in this map is to be tested
1717 * @return <tt>true</tt> if a mapping to <tt>value</tt> exists;
1718 * <tt>false</tt> otherwise
1719 * @throws NullPointerException if the specified value is null
1720 */
1721 public boolean containsValue(Object value) {
1722 if (value == null)
1723 throw new NullPointerException();
1724 for (Node<K, V> n = findFirst(); n != null; n = n.next) {
1725 V v = n.getValidValue();
1726 if (v != null && value.equals(v))
1727 return true;
1728 }
1729 return false;
1730 }
1731
1732 /**
1733 * Returns the number of key-value mappings in this map. If this map
1734 * contains more than <tt>Integer.MAX_VALUE</tt> elements, it
1735 * returns <tt>Integer.MAX_VALUE</tt>.
1736 *
1737 * <p>Beware that, unlike in most collections, this method is
1738 * <em>NOT</em> a constant-time operation. Because of the
1739 * asynchronous nature of these maps, determining the current
1740 * number of elements requires traversing them all to count them.
1741 * Additionally, it is possible for the size to change during
1742 * execution of this method, in which case the returned result
1743 * will be inaccurate. Thus, this method is typically not very
1744 * useful in concurrent applications.
1745 *
1746 * @return the number of elements in this map
1747 */
1748 public int size() {
1749 long count = 0;
1750 for (Node<K, V> n = findFirst(); n != null; n = n.next) {
1751 if (n.getValidValue() != null)
1752 ++count;
1753 }
1754 return (count >= Integer.MAX_VALUE) ? Integer.MAX_VALUE
1755 : (int) count;
1756 }
1757
1758 /**
1759 * Returns <tt>true</tt> if this map contains no key-value mappings.
1760 * @return <tt>true</tt> if this map contains no key-value mappings
1761 */
1762 public boolean isEmpty() {
1763 return findFirst() == null;
1764 }
1765
1766 /**
1767 * Removes all of the mappings from this map.
1768 */
1769 public void clear() {
1770 initialize();
1771 }
1772
1773 /* ---------------- View methods -------------- */
1774
1775 /*
1776 * Note: Lazy initialization works for views because view classes
1777 * are stateless/immutable so it doesn't matter wrt correctness if
1778 * more than one is created (which will only rarely happen). Even
1779 * so, the following idiom conservatively ensures that the method
1780 * returns the one it created if it does so, not one created by
1781 * another racing thread.
1782 */
1783
1784 /**
1785 * Returns a {@link NavigableSet} view of the keys contained in this map.
1786 * The set's iterator returns the keys in ascending order.
1787 * The set is backed by the map, so changes to the map are
1788 * reflected in the set, and vice-versa. The set supports element
1789 * removal, which removes the corresponding mapping from the map,
1790 * via the {@code Iterator.remove}, {@code Set.remove},
1791 * {@code removeAll}, {@code retainAll}, and {@code clear}
1792 * operations. It does not support the {@code add} or {@code addAll}
1793 * operations.
1794 *
1795 * <p>The view's {@code iterator} is a "weakly consistent" iterator
1796 * that will never throw {@link ConcurrentModificationException},
1797 * and guarantees to traverse elements as they existed upon
1798 * construction of the iterator, and may (but is not guaranteed to)
1799 * reflect any modifications subsequent to construction.
1800 *
1801 * <p>This method is equivalent to method {@code navigableKeySet}.
1802 *
1803 * @return a navigable set view of the keys in this map
1804 */
1805 public NavigableSet<K> keySet() {
1806 KeySet ks = keySet;
1807 return (ks != null) ? ks : (keySet = new KeySet(this ));
1808 }
1809
1810 public NavigableSet<K> navigableKeySet() {
1811 KeySet ks = keySet;
1812 return (ks != null) ? ks : (keySet = new KeySet(this ));
1813 }
1814
1815 /**
1816 * Returns a {@link Collection} view of the values contained in this map.
1817 * The collection's iterator returns the values in ascending order
1818 * of the corresponding keys.
1819 * The collection is backed by the map, so changes to the map are
1820 * reflected in the collection, and vice-versa. The collection
1821 * supports element removal, which removes the corresponding
1822 * mapping from the map, via the <tt>Iterator.remove</tt>,
1823 * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1824 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
1825 * support the <tt>add</tt> or <tt>addAll</tt> operations.
1826 *
1827 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1828 * that will never throw {@link ConcurrentModificationException},
1829 * and guarantees to traverse elements as they existed upon
1830 * construction of the iterator, and may (but is not guaranteed to)
1831 * reflect any modifications subsequent to construction.
1832 */
1833 public Collection<V> values() {
1834 Values vs = values;
1835 return (vs != null) ? vs : (values = new Values(this ));
1836 }
1837
1838 /**
1839 * Returns a {@link Set} view of the mappings contained in this map.
1840 * The set's iterator returns the entries in ascending key order.
1841 * The set is backed by the map, so changes to the map are
1842 * reflected in the set, and vice-versa. The set supports element
1843 * removal, which removes the corresponding mapping from the map,
1844 * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1845 * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
1846 * operations. It does not support the <tt>add</tt> or
1847 * <tt>addAll</tt> operations.
1848 *
1849 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1850 * that will never throw {@link ConcurrentModificationException},
1851 * and guarantees to traverse elements as they existed upon
1852 * construction of the iterator, and may (but is not guaranteed to)
1853 * reflect any modifications subsequent to construction.
1854 *
1855 * <p>The <tt>Map.Entry</tt> elements returned by
1856 * <tt>iterator.next()</tt> do <em>not</em> support the
1857 * <tt>setValue</tt> operation.
1858 *
1859 * @return a set view of the mappings contained in this map,
1860 * sorted in ascending key order
1861 */
1862 public Set<Map.Entry<K, V>> entrySet() {
1863 EntrySet es = entrySet;
1864 return (es != null) ? es : (entrySet = new EntrySet(this ));
1865 }
1866
1867 public ConcurrentNavigableMap<K, V> descendingMap() {
1868 ConcurrentNavigableMap<K, V> dm = descendingMap;
1869 return (dm != null) ? dm : (descendingMap = new SubMap<K, V>(
1870 this , null, false, null, false, true));
1871 }
1872
1873 public NavigableSet<K> descendingKeySet() {
1874 return descendingMap().navigableKeySet();
1875 }
1876
1877 /* ---------------- AbstractMap Overrides -------------- */
1878
1879 /**
1880 * Compares the specified object with this map for equality.
1881 * Returns <tt>true</tt> if the given object is also a map and the
1882 * two maps represent the same mappings. More formally, two maps
1883 * <tt>m1</tt> and <tt>m2</tt> represent the same mappings if
1884 * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This
1885 * operation may return misleading results if either map is
1886 * concurrently modified during execution of this method.
1887 *
1888 * @param o object to be compared for equality with this map
1889 * @return <tt>true</tt> if the specified object is equal to this map
1890 */
1891 public boolean equals(Object o) {
1892 if (o == this )
1893 return true;
1894 if (!(o instanceof Map))
1895 return false;
1896 Map<?, ?> m = (Map<?, ?>) o;
1897 try {
1898 for (Map.Entry<K, V> e : this .entrySet())
1899 if (!e.getValue().equals(m.get(e.getKey())))
1900 return false;
1901 for (Map.Entry<?, ?> e : m.entrySet()) {
1902 Object k = e.getKey();
1903 Object v = e.getValue();
1904 if (k == null || v == null || !v.equals(get(k)))
1905 return false;
1906 }
1907 return true;
1908 } catch (ClassCastException unused) {
1909 return false;
1910 } catch (NullPointerException unused) {
1911 return false;
1912 }
1913 }
1914
1915 /* ------ ConcurrentMap API methods ------ */
1916
1917 /**
1918 * {@inheritDoc}
1919 *
1920 * @return the previous value associated with the specified key,
1921 * or <tt>null</tt> if there was no mapping for the key
1922 * @throws ClassCastException if the specified key cannot be compared
1923 * with the keys currently in the map
1924 * @throws NullPointerException if the specified key or value is null
1925 */
1926 public V putIfAbsent(K key, V value) {
1927 if (value == null)
1928 throw new NullPointerException();
1929 return doPut(key, value, true);
1930 }
1931
1932 /**
1933 * {@inheritDoc}
1934 *
1935 * @throws ClassCastException if the specified key cannot be compared
1936 * with the keys currently in the map
1937 * @throws NullPointerException if the specified key is null
1938 */
1939 public boolean remove(Object key, Object value) {
1940 if (key == null)
1941 throw new NullPointerException();
1942 if (value == null)
1943 return false;
1944 return doRemove(key, value) != null;
1945 }
1946
1947 /**
1948 * {@inheritDoc}
1949 *
1950 * @throws ClassCastException if the specified key cannot be compared
1951 * with the keys currently in the map
1952 * @throws NullPointerException if any of the arguments are null
1953 */
1954 public boolean replace(K key, V oldValue, V newValue) {
1955 if (oldValue == null || newValue == null)
1956 throw new NullPointerException();
1957 Comparable<? super K> k = comparable(key);
1958 for (;;) {
1959 Node<K, V> n = findNode(k);
1960 if (n == null)
1961 return false;
1962 Object v = n.value;
1963 if (v != null) {
1964 if (!oldValue.equals(v))
1965 return false;
1966 if (n.casValue(v, newValue))
1967 return true;
1968 }
1969 }
1970 }
1971
1972 /**
1973 * {@inheritDoc}
1974 *
1975 * @return the previous value associated with the specified key,
1976 * or <tt>null</tt> if there was no mapping for the key
1977 * @throws ClassCastException if the specified key cannot be compared
1978 * with the keys currently in the map
1979 * @throws NullPointerException if the specified key or value is null
1980 */
1981 public V replace(K key, V value) {
1982 if (value == null)
1983 throw new NullPointerException();
1984 Comparable<? super K> k = comparable(key);
1985 for (;;) {
1986 Node<K, V> n = findNode(k);
1987 if (n == null)
1988 return null;
1989 Object v = n.value;
1990 if (v != null && n.casValue(v, value))
1991 return (V) v;
1992 }
1993 }
1994
1995 /* ------ SortedMap API methods ------ */
1996
1997 public Comparator<? super K> comparator() {
1998 return comparator;
1999 }
2000
2001 /**
2002 * @throws NoSuchElementException {@inheritDoc}
2003 */
2004 public K firstKey() {
2005 Node<K, V> n = findFirst();
2006 if (n == null)
2007 throw new NoSuchElementException();
2008 return n.key;
2009 }
2010
2011 /**
2012 * @throws NoSuchElementException {@inheritDoc}
2013 */
2014 public K lastKey() {
2015 Node<K, V> n = findLast();
2016 if (n == null)
2017 throw new NoSuchElementException();
2018 return n.key;
2019 }
2020
2021 /**
2022 * @throws ClassCastException {@inheritDoc}
2023 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2024 * @throws IllegalArgumentException {@inheritDoc}
2025 */
2026 public ConcurrentNavigableMap<K, V> subMap(K fromKey,
2027 boolean fromInclusive, K toKey, boolean toInclusive) {
2028 if (fromKey == null || toKey == null)
2029 throw new NullPointerException();
2030 return new SubMap<K, V>(this , fromKey, fromInclusive, toKey,
2031 toInclusive, false);
2032 }
2033
2034 /**
2035 * @throws ClassCastException {@inheritDoc}
2036 * @throws NullPointerException if {@code toKey} is null
2037 * @throws IllegalArgumentException {@inheritDoc}
2038 */
2039 public ConcurrentNavigableMap<K, V> headMap(K toKey,
2040 boolean inclusive) {
2041 if (toKey == null)
2042 throw new NullPointerException();
2043 return new SubMap<K, V>(this , null, false, toKey, inclusive,
2044 false);
2045 }
2046
2047 /**
2048 * @throws ClassCastException {@inheritDoc}
2049 * @throws NullPointerException if {@code fromKey} is null
2050 * @throws IllegalArgumentException {@inheritDoc}
2051 */
2052 public ConcurrentNavigableMap<K, V> tailMap(K fromKey,
2053 boolean inclusive) {
2054 if (fromKey == null)
2055 throw new NullPointerException();
2056 return new SubMap<K, V>(this , fromKey, inclusive, null, false,
2057 false);
2058 }
2059
2060 /**
2061 * @throws ClassCastException {@inheritDoc}
2062 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2063 * @throws IllegalArgumentException {@inheritDoc}
2064 */
2065 public ConcurrentNavigableMap<K, V> subMap(K fromKey, K toKey) {
2066 return subMap(fromKey, true, toKey, false);
2067 }
2068
2069 /**
2070 * @throws ClassCastException {@inheritDoc}
2071 * @throws NullPointerException if {@code toKey} is null
2072 * @throws IllegalArgumentException {@inheritDoc}
2073 */
2074 public ConcurrentNavigableMap<K, V> headMap(K toKey) {
2075 return headMap(toKey, false);
2076 }
2077
2078 /**
2079 * @throws ClassCastException {@inheritDoc}
2080 * @throws NullPointerException if {@code fromKey} is null
2081 * @throws IllegalArgumentException {@inheritDoc}
2082 */
2083 public ConcurrentNavigableMap<K, V> tailMap(K fromKey) {
2084 return tailMap(fromKey, true);
2085 }
2086
2087 /* ---------------- Relational operations -------------- */
2088
2089 /**
2090 * Returns a key-value mapping associated with the greatest key
2091 * strictly less than the given key, or <tt>null</tt> if there is
2092 * no such key. The returned entry does <em>not</em> support the
2093 * <tt>Entry.setValue</tt> method.
2094 *
2095 * @throws ClassCastException {@inheritDoc}
2096 * @throws NullPointerException if the specified key is null
2097 */
2098 public Map.Entry<K, V> lowerEntry(K key) {
2099 return getNear(key, LT);
2100 }
2101
2102 /**
2103 * @throws ClassCastException {@inheritDoc}
2104 * @throws NullPointerException if the specified key is null
2105 */
2106 public K lowerKey(K key) {
2107 Node<K, V> n = findNear(key, LT);
2108 return (n == null) ? null : n.key;
2109 }
2110
2111 /**
2112 * Returns a key-value mapping associated with the greatest key
2113 * less than or equal to the given key, or <tt>null</tt> if there
2114 * is no such key. The returned entry does <em>not</em> support
2115 * the <tt>Entry.setValue</tt> method.
2116 *
2117 * @param key the key
2118 * @throws ClassCastException {@inheritDoc}
2119 * @throws NullPointerException if the specified key is null
2120 */
2121 public Map.Entry<K, V> floorEntry(K key) {
2122 return getNear(key, LT | EQ);
2123 }
2124
2125 /**
2126 * @param key the key
2127 * @throws ClassCastException {@inheritDoc}
2128 * @throws NullPointerException if the specified key is null
2129 */
2130 public K floorKey(K key) {
2131 Node<K, V> n = findNear(key, LT | EQ);
2132 return (n == null) ? null : n.key;
2133 }
2134
2135 /**
2136 * Returns a key-value mapping associated with the least key
2137 * greater than or equal to the given key, or <tt>null</tt> if
2138 * there is no such entry. The returned entry does <em>not</em>
2139 * support the <tt>Entry.setValue</tt> method.
2140 *
2141 * @throws ClassCastException {@inheritDoc}
2142 * @throws NullPointerException if the specified key is null
2143 */
2144 public Map.Entry<K, V> ceilingEntry(K key) {
2145 return getNear(key, GT | EQ);
2146 }
2147
2148 /**
2149 * @throws ClassCastException {@inheritDoc}
2150 * @throws NullPointerException if the specified key is null
2151 */
2152 public K ceilingKey(K key) {
2153 Node<K, V> n = findNear(key, GT | EQ);
2154 return (n == null) ? null : n.key;
2155 }
2156
2157 /**
2158 * Returns a key-value mapping associated with the least key
2159 * strictly greater than the given key, or <tt>null</tt> if there
2160 * is no such key. The returned entry does <em>not</em> support
2161 * the <tt>Entry.setValue</tt> method.
2162 *
2163 * @param key the key
2164 * @throws ClassCastException {@inheritDoc}
2165 * @throws NullPointerException if the specified key is null
2166 */
2167 public Map.Entry<K, V> higherEntry(K key) {
2168 return getNear(key, GT);
2169 }
2170
2171 /**
2172 * @param key the key
2173 * @throws ClassCastException {@inheritDoc}
2174 * @throws NullPointerException if the specified key is null
2175 */
2176 public K higherKey(K key) {
2177 Node<K, V> n = findNear(key, GT);
2178 return (n == null) ? null : n.key;
2179 }
2180
2181 /**
2182 * Returns a key-value mapping associated with the least
2183 * key in this map, or <tt>null</tt> if the map is empty.
2184 * The returned entry does <em>not</em> support
2185 * the <tt>Entry.setValue</tt> method.
2186 */
2187 public Map.Entry<K, V> firstEntry() {
2188 for (;;) {
2189 Node<K, V> n = findFirst();
2190 if (n == null)
2191 return null;
2192 AbstractMap.SimpleImmutableEntry<K, V> e = n
2193 .createSnapshot();
2194 if (e != null)
2195 return e;
2196 }
2197 }
2198
2199 /**
2200 * Returns a key-value mapping associated with the greatest
2201 * key in this map, or <tt>null</tt> if the map is empty.
2202 * The returned entry does <em>not</em> support
2203 * the <tt>Entry.setValue</tt> method.
2204 */
2205 public Map.Entry<K, V> lastEntry() {
2206 for (;;) {
2207 Node<K, V> n = findLast();
2208 if (n == null)
2209 return null;
2210 AbstractMap.SimpleImmutableEntry<K, V> e = n
2211 .createSnapshot();
2212 if (e != null)
2213 return e;
2214 }
2215 }
2216
2217 /**
2218 * Removes and returns a key-value mapping associated with
2219 * the least key in this map, or <tt>null</tt> if the map is empty.
2220 * The returned entry does <em>not</em> support
2221 * the <tt>Entry.setValue</tt> method.
2222 */
2223 public Map.Entry<K, V> pollFirstEntry() {
2224 return doRemoveFirstEntry();
2225 }
2226
2227 /**
2228 * Removes and returns a key-value mapping associated with
2229 * the greatest key in this map, or <tt>null</tt> if the map is empty.
2230 * The returned entry does <em>not</em> support
2231 * the <tt>Entry.setValue</tt> method.
2232 */
2233 public Map.Entry<K, V> pollLastEntry() {
2234 return doRemoveLastEntry();
2235 }
2236
2237 /* ---------------- Iterators -------------- */
2238
2239 /**
2240 * Base of iterator classes:
2241 */
2242 abstract class Iter<T> implements Iterator<T> {
2243 /** the last node returned by next() */
2244 Node<K, V> lastReturned;
2245 /** the next node to return from next(); */
2246 Node<K, V> next;
2247 /** Cache of next value field to maintain weak consistency */
2248 V nextValue;
2249
2250 /** Initializes ascending iterator for entire range. */
2251 Iter() {
2252 for (;;) {
2253 next = findFirst();
2254 if (next == null)
2255 break;
2256 Object x = next.value;
2257 if (x != null && x != next) {
2258 nextValue = (V) x;
2259 break;
2260 }
2261 }
2262 }
2263
2264 public final boolean hasNext() {
2265 return next != null;
2266 }
2267
2268 /** Advances next to higher entry. */
2269 final void advance() {
2270 if (next == null)
2271 throw new NoSuchElementException();
2272 lastReturned = next;
2273 for (;;) {
2274 next = next.next;
2275 if (next == null)
2276 break;
2277 Object x = next.value;
2278 if (x != null && x != next) {
2279 nextValue = (V) x;
2280 break;
2281 }
2282 }
2283 }
2284
2285 public void remove() {
2286 Node<K, V> l = lastReturned;
2287 if (l == null)
2288 throw new IllegalStateException();
2289 // It would not be worth all of the overhead to directly
2290 // unlink from here. Using remove is fast enough.
2291 ConcurrentSkipListMap.this .remove(l.key);
2292 lastReturned = null;
2293 }
2294
2295 }
2296
2297 final class ValueIterator extends Iter<V> {
2298 public V next() {
2299 V v = nextValue;
2300 advance();
2301 return v;
2302 }
2303 }
2304
2305 final class KeyIterator extends Iter<K> {
2306 public K next() {
2307 Node<K, V> n = next;
2308 advance();
2309 return n.key;
2310 }
2311 }
2312
2313 final class EntryIterator extends Iter<Map.Entry<K, V>> {
2314 public Map.Entry<K, V> next() {
2315 Node<K, V> n = next;
2316 V v = nextValue;
2317 advance();
2318 return new AbstractMap.SimpleImmutableEntry<K, V>(n.key, v);
2319 }
2320 }
2321
2322 // Factory methods for iterators needed by ConcurrentSkipListSet etc
2323
2324 Iterator<K> keyIterator() {
2325 return new KeyIterator();
2326 }
2327
2328 Iterator<V> valueIterator() {
2329 return new ValueIterator();
2330 }
2331
2332 Iterator<Map.Entry<K, V>> entryIterator() {
2333 return new EntryIterator();
2334 }
2335
2336 /* ---------------- View Classes -------------- */
2337
2338 /*
2339 * View classes are static, delegating to a ConcurrentNavigableMap
2340 * to allow use by SubMaps, which outweighs the ugliness of
2341 * needing type-tests for Iterator methods.
2342 */
2343
2344 static final <E> List<E> toList(Collection<E> c) {
2345 // Using size() here would be a pessimization.
2346 List<E> list = new ArrayList<E>();
2347 for (E e : c)
2348 list.add(e);
2349 return list;
2350 }
2351
2352 static final class KeySet<E> extends AbstractSet<E> implements
2353 NavigableSet<E> {
2354 private final ConcurrentNavigableMap<E, Object> m;
2355
2356 KeySet(ConcurrentNavigableMap<E, Object> map) {
2357 m = map;
2358 }
2359
2360 public int size() {
2361 return m.size();
2362 }
2363
2364 public boolean isEmpty() {
2365 return m.isEmpty();
2366 }
2367
2368 public boolean contains(Object o) {
2369 return m.containsKey(o);
2370 }
2371
2372 public boolean remove(Object o) {
2373 return m.remove(o) != null;
2374 }
2375
2376 public void clear() {
2377 m.clear();
2378 }
2379
2380 public E lower(E e) {
2381 return m.lowerKey(e);
2382 }
2383
2384 public E floor(E e) {
2385 return m.floorKey(e);
2386 }
2387
2388 public E ceiling(E e) {
2389 return m.ceilingKey(e);
2390 }
2391
2392 public E higher(E e) {
2393 return m.higherKey(e);
2394 }
2395
2396 public Comparator<? super E> comparator() {
2397 return m.comparator();
2398 }
2399
2400 public E first() {
2401 return m.firstKey();
2402 }
2403
2404 public E last() {
2405 return m.lastKey();
2406 }
2407
2408 public E pollFirst() {
2409 Map.Entry<E, Object> e = m.pollFirstEntry();
2410 return e == null ? null : e.getKey();
2411 }
2412
2413 public E pollLast() {
2414 Map.Entry<E, Object> e = m.pollLastEntry();
2415 return e == null ? null : e.getKey();
2416 }
2417
2418 public Iterator<E> iterator() {
2419 if (m instanceof ConcurrentSkipListMap)
2420 return ((ConcurrentSkipListMap<E, Object>) m)
2421 .keyIterator();
2422 else
2423 return ((ConcurrentSkipListMap.SubMap<E, Object>) m)
2424 .keyIterator();
2425 }
2426
2427 public boolean equals(Object o) {
2428 if (o == this )
2429 return true;
2430 if (!(o instanceof Set))
2431 return false;
2432 Collection<?> c = (Collection<?>) o;
2433 try {
2434 return containsAll(c) && c.containsAll(this );
2435 } catch (ClassCastException unused) {
2436 return false;
2437 } catch (NullPointerException unused) {
2438 return false;
2439 }
2440 }
2441
2442 public Object[] toArray() {
2443 return toList(this ).toArray();
2444 }
2445
2446 public <T> T[] toArray(T[] a) {
2447 return toList(this ).toArray(a);
2448 }
2449
2450 public Iterator<E> descendingIterator() {
2451 return descendingSet().iterator();
2452 }
2453
2454 public NavigableSet<E> subSet(E fromElement,
2455 boolean fromInclusive, E toElement, boolean toInclusive) {
2456 return new ConcurrentSkipListSet<E>(m.subMap(fromElement,
2457 fromInclusive, toElement, toInclusive));
2458 }
2459
2460 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
2461 return new ConcurrentSkipListSet<E>(m.headMap(toElement,
2462 inclusive));
2463 }
2464
2465 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
2466 return new ConcurrentSkipListSet<E>(m.tailMap(fromElement,
2467 inclusive));
2468 }
2469
2470 public NavigableSet<E> subSet(E fromElement, E toElement) {
2471 return subSet(fromElement, true, toElement, false);
2472 }
2473
2474 public NavigableSet<E> headSet(E toElement) {
2475 return headSet(toElement, false);
2476 }
2477
2478 public NavigableSet<E> tailSet(E fromElement) {
2479 return tailSet(fromElement, true);
2480 }
2481
2482 public NavigableSet<E> descendingSet() {
2483 return new ConcurrentSkipListSet(m.descendingMap());
2484 }
2485 }
2486
2487 static final class Values<E> extends AbstractCollection<E> {
2488 private final ConcurrentNavigableMap<Object, E> m;
2489
2490 Values(ConcurrentNavigableMap<Object, E> map) {
2491 m = map;
2492 }
2493
2494 public Iterator<E> iterator() {
2495 if (m instanceof ConcurrentSkipListMap)
2496 return ((ConcurrentSkipListMap<Object, E>) m)
2497 .valueIterator();
2498 else
2499 return ((SubMap<Object, E>) m).valueIterator();
2500 }
2501
2502 public boolean isEmpty() {
2503 return m.isEmpty();
2504 }
2505
2506 public int size() {
2507 return m.size();
2508 }
2509
2510 public boolean contains(Object o) {
2511 return m.containsValue(o);
2512 }
2513
2514 public void clear() {
2515 m.clear();
2516 }
2517
2518 public Object[] toArray() {
2519 return toList(this ).toArray();
2520 }
2521
2522 public <T> T[] toArray(T[] a) {
2523 return toList(this ).toArray(a);
2524 }
2525 }
2526
2527 static final class EntrySet<K1, V1> extends
2528 AbstractSet<Map.Entry<K1, V1>> {
2529 private final ConcurrentNavigableMap<K1, V1> m;
2530
2531 EntrySet(ConcurrentNavigableMap<K1, V1> map) {
2532 m = map;
2533 }
2534
2535 public Iterator<Map.Entry<K1, V1>> iterator() {
2536 if (m instanceof ConcurrentSkipListMap)
2537 return ((ConcurrentSkipListMap<K1, V1>) m)
2538 .entryIterator();
2539 else
2540 return ((SubMap<K1, V1>) m).entryIterator();
2541 }
2542
2543 public boolean contains(Object o) {
2544 if (!(o instanceof Map.Entry))
2545 return false;
2546 Map.Entry<K1, V1> e = (Map.Entry<K1, V1>) o;
2547 V1 v = m.get(e.getKey());
2548 return v != null && v.equals(e.getValue());
2549 }
2550
2551 public boolean remove(Object o) {
2552 if (!(o instanceof Map.Entry))
2553 return false;
2554 Map.Entry<K1, V1> e = (Map.Entry<K1, V1>) o;
2555 return m.remove(e.getKey(), e.getValue());
2556 }
2557
2558 public boolean isEmpty() {
2559 return m.isEmpty();
2560 }
2561
2562 public int size() {
2563 return m.size();
2564 }
2565
2566 public void clear() {
2567 m.clear();
2568 }
2569
2570 public boolean equals(Object o) {
2571 if (o == this )
2572 return true;
2573 if (!(o instanceof Set))
2574 return false;
2575 Collection<?> c = (Collection<?>) o;
2576 try {
2577 return containsAll(c) && c.containsAll(this );
2578 } catch (ClassCastException unused) {
2579 return false;
2580 } catch (NullPointerException unused) {
2581 return false;
2582 }
2583 }
2584
2585 public Object[] toArray() {
2586 return toList(this ).toArray();
2587 }
2588
2589 public <T> T[] toArray(T[] a) {
2590 return toList(this ).toArray(a);
2591 }
2592 }
2593
2594 /**
2595 * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2596 * represent a subrange of mappings of their underlying
2597 * maps. Instances of this class support all methods of their
2598 * underlying maps, differing in that mappings outside their range are
2599 * ignored, and attempts to add mappings outside their ranges result
2600 * in {@link IllegalArgumentException}. Instances of this class are
2601 * constructed only using the <tt>subMap</tt>, <tt>headMap</tt>, and
2602 * <tt>tailMap</tt> methods of their underlying maps.
2603 *
2604 * @serial include
2605 */
2606 static final class SubMap<K, V> extends AbstractMap<K, V> implements
2607 ConcurrentNavigableMap<K, V>, Cloneable,
2608 java.io.Serializable {
2609 private static final long serialVersionUID = -7647078645895051609L;
2610
2611 /** Underlying map */
2612 private final ConcurrentSkipListMap<K, V> m;
2613 /** lower bound key, or null if from start */
2614 private final K lo;
2615 /** upper bound key, or null if to end */
2616 private final K hi;
2617 /** inclusion flag for lo */
2618 private final boolean loInclusive;
2619 /** inclusion flag for hi */
2620 private final boolean hiInclusive;
2621 /** direction */
2622 private final boolean isDescending;
2623
2624 // Lazily initialized view holders
2625 private transient KeySet<K> keySetView;
2626 private transient Set<Map.Entry<K, V>> entrySetView;
2627 private transient Collection<V> valuesView;
2628
2629 /**
2630 * Creates a new submap, initializing all fields
2631 */
2632 SubMap(ConcurrentSkipListMap<K, V> map, K fromKey,
2633 boolean fromInclusive, K toKey, boolean toInclusive,
2634 boolean isDescending) {
2635 if (fromKey != null && toKey != null
2636 && map.compare(fromKey, toKey) > 0)
2637 throw new IllegalArgumentException("inconsistent range");
2638 this .m = map;
2639 this .lo = fromKey;
2640 this .hi = toKey;
2641 this .loInclusive = fromInclusive;
2642 this .hiInclusive = toInclusive;
2643 this .isDescending = isDescending;
2644 }
2645
2646 /* ---------------- Utilities -------------- */
2647
2648 private boolean tooLow(K key) {
2649 if (lo != null) {
2650 int c = m.compare(key, lo);
2651 if (c < 0 || (c == 0 && !loInclusive))
2652 return true;
2653 }
2654 return false;
2655 }
2656
2657 private boolean tooHigh(K key) {
2658 if (hi != null) {
2659 int c = m.compare(key, hi);
2660 if (c > 0 || (c == 0 && !hiInclusive))
2661 return true;
2662 }
2663 return false;
2664 }
2665
2666 private boolean inBounds(K key) {
2667 return !tooLow(key) && !tooHigh(key);
2668 }
2669
2670 private void checkKeyBounds(K key)
2671 throws IllegalArgumentException {
2672 if (key == null)
2673 throw new NullPointerException();
2674 if (!inBounds(key))
2675 throw new IllegalArgumentException("key out of range");
2676 }
2677
2678 /**
2679 * Returns true if node key is less than upper bound of range
2680 */
2681 private boolean isBeforeEnd(ConcurrentSkipListMap.Node<K, V> n) {
2682 if (n == null)
2683 return false;
2684 if (hi == null)
2685 return true;
2686 K k = n.key;
2687 if (k == null) // pass by markers and headers
2688 return true;
2689 int c = m.compare(k, hi);
2690 if (c > 0 || (c == 0 && !hiInclusive))
2691 return false;
2692 return true;
2693 }
2694
2695 /**
2696 * Returns lowest node. This node might not be in range, so
2697 * most usages need to check bounds
2698 */
2699 private ConcurrentSkipListMap.Node<K, V> loNode() {
2700 if (lo == null)
2701 return m.findFirst();
2702 else if (loInclusive)
2703 return m.findNear(lo, m.GT | m.EQ);
2704 else
2705 return m.findNear(lo, m.GT);
2706 }
2707
2708 /**
2709 * Returns highest node. This node might not be in range, so
2710 * most usages need to check bounds
2711 */
2712 private ConcurrentSkipListMap.Node<K, V> hiNode() {
2713 if (hi == null)
2714 return m.findLast();
2715 else if (hiInclusive)
2716 return m.findNear(hi, m.LT | m.EQ);
2717 else
2718 return m.findNear(hi, m.LT);
2719 }
2720
2721 /**
2722 * Returns lowest absolute key (ignoring directonality)
2723 */
2724 private K lowestKey() {
2725 ConcurrentSkipListMap.Node<K, V> n = loNode();
2726 if (isBeforeEnd(n))
2727 return n.key;
2728 else
2729 throw new NoSuchElementException();
2730 }
2731
2732 /**
2733 * Returns highest absolute key (ignoring directonality)
2734 */
2735 private K highestKey() {
2736 ConcurrentSkipListMap.Node<K, V> n = hiNode();
2737 if (n != null) {
2738 K last = n.key;
2739 if (inBounds(last))
2740 return last;
2741 }
2742 throw new NoSuchElementException();
2743 }
2744
2745 private Map.Entry<K, V> lowestEntry() {
2746 for (;;) {
2747 ConcurrentSkipListMap.Node<K, V> n = loNode();
2748 if (!isBeforeEnd(n))
2749 return null;
2750 Map.Entry<K, V> e = n.createSnapshot();
2751 if (e != null)
2752 return e;
2753 }
2754 }
2755
2756 private Map.Entry<K, V> highestEntry() {
2757 for (;;) {
2758 ConcurrentSkipListMap.Node<K, V> n = hiNode();
2759 if (n == null || !inBounds(n.key))
2760 return null;
2761 Map.Entry<K, V> e = n.createSnapshot();
2762 if (e != null)
2763 return e;
2764 }
2765 }
2766
2767 private Map.Entry<K, V> removeLowest() {
2768 for (;;) {
2769 Node<K, V> n = loNode();
2770 if (n == null)
2771 return null;
2772 K k = n.key;
2773 if (!inBounds(k))
2774 return null;
2775 V v = m.doRemove(k, null);
2776 if (v != null)
2777 return new AbstractMap.SimpleImmutableEntry<K, V>(
2778 k, v);
2779 }
2780 }
2781
2782 private Map.Entry<K, V> removeHighest() {
2783 for (;;) {
2784 Node<K, V> n = hiNode();
2785 if (n == null)
2786 return null;
2787 K k = n.key;
2788 if (!inBounds(k))
2789 return null;
2790 V v = m.doRemove(k, null);
2791 if (v != null)
2792 return new AbstractMap.SimpleImmutableEntry<K, V>(
2793 k, v);
2794 }
2795 }
2796
2797 /**
2798 * Submap version of ConcurrentSkipListMap.getNearEntry
2799 */
2800 private Map.Entry<K, V> getNearEntry(K key, int rel) {
2801 if (isDescending) { // adjust relation for direction
2802 if ((rel & m.LT) == 0)
2803 rel |= m.LT;
2804 else
2805 rel &= ~m.LT;
2806 }
2807 if (tooLow(key))
2808 return ((rel & m.LT) != 0) ? null : lowestEntry();
2809 if (tooHigh(key))
2810 return ((rel & m.LT) != 0) ? highestEntry() : null;
2811 for (;;) {
2812 Node<K, V> n = m.findNear(key, rel);
2813 if (n == null || !inBounds(n.key))
2814 return null;
2815 K k = n.key;
2816 V v = n.getValidValue();
2817 if (v != null)
2818 return new AbstractMap.SimpleImmutableEntry<K, V>(
2819 k, v);
2820 }
2821 }
2822
2823 // Almost the same as getNearEntry, except for keys
2824 private K getNearKey(K key, int rel) {
2825 if (isDescending) { // adjust relation for direction
2826 if ((rel & m.LT) == 0)
2827 rel |= m.LT;
2828 else
2829 rel &= ~m.LT;
2830 }
2831 if (tooLow(key)) {
2832 if ((rel & m.LT) == 0) {
2833 ConcurrentSkipListMap.Node<K, V> n = loNode();
2834 if (isBeforeEnd(n))
2835 return n.key;
2836 }
2837 return null;
2838 }
2839 if (tooHigh(key)) {
2840 if ((rel & m.LT) != 0) {
2841 ConcurrentSkipListMap.Node<K, V> n = hiNode();
2842 if (n != null) {
2843 K last = n.key;
2844 if (inBounds(last))
2845 return last;
2846 }
2847 }
2848 return null;
2849 }
2850 for (;;) {
2851 Node<K, V> n = m.findNear(key, rel);
2852 if (n == null || !inBounds(n.key))
2853 return null;
2854 K k = n.key;
2855 V v = n.getValidValue();
2856 if (v != null)
2857 return k;
2858 }
2859 }
2860
2861 /* ---------------- Map API methods -------------- */
2862
2863 public boolean containsKey(Object key) {
2864 if (key == null)
2865 throw new NullPointerException();
2866 K k = (K) key;
2867 return inBounds(k) && m.containsKey(k);
2868 }
2869
2870 public V get(Object key) {
2871 if (key == null)
2872 throw new NullPointerException();
2873 K k = (K) key;
2874 return ((!inBounds(k)) ? null : m.get(k));
2875 }
2876
2877 public V put(K key, V value) {
2878 checkKeyBounds(key);
2879 return m.put(key, value);
2880 }
2881
2882 public V remove(Object key) {
2883 K k = (K) key;
2884 return (!inBounds(k)) ? null : m.remove(k);
2885 }
2886
2887 public int size() {
2888 long count = 0;
2889 for (ConcurrentSkipListMap.Node<K, V> n = loNode(); isBeforeEnd(n); n = n.next) {
2890 if (n.getValidValue() != null)
2891 ++count;
2892 }
2893 return count >= Integer.MAX_VALUE ? Integer.MAX_VALUE
2894 : (int) count;
2895 }
2896
2897 public boolean isEmpty() {
2898 return !isBeforeEnd(loNode());
2899 }
2900
2901 public boolean containsValue(Object value) {
2902 if (value == null)
2903 throw new NullPointerException();
2904 for (ConcurrentSkipListMap.Node<K, V> n = loNode(); isBeforeEnd(n); n = n.next) {
2905 V v = n.getValidValue();
2906 if (v != null && value.equals(v))
2907 return true;
2908 }
2909 return false;
2910 }
2911
2912 public void clear() {
2913 for (ConcurrentSkipListMap.Node<K, V> n = loNode(); isBeforeEnd(n); n = n.next) {
2914 if (n.getValidValue() != null)
2915 m.remove(n.key);
2916 }
2917 }
2918
2919 /* ---------------- ConcurrentMap API methods -------------- */
2920
2921 public V putIfAbsent(K key, V value) {
2922 checkKeyBounds(key);
2923 return m.putIfAbsent(key, value);
2924 }
2925
2926 public boolean remove(Object key, Object value) {
2927 K k = (K) key;
2928 return inBounds(k) && m.remove(k, value);
2929 }
2930
2931 public boolean replace(K key, V oldValue, V newValue) {
2932 checkKeyBounds(key);
2933 return m.replace(key, oldValue, newValue);
2934 }
2935
2936 public V replace(K key, V value) {
2937 checkKeyBounds(key);
2938 return m.replace(key, value);
2939 }
2940
2941 /* ---------------- SortedMap API methods -------------- */
2942
2943 public Comparator<? super K> comparator() {
2944 Comparator<? super K> cmp = m.comparator();
2945 if (isDescending)
2946 return Collections.reverseOrder(cmp);
2947 else
2948 return cmp;
2949 }
2950
2951 /**
2952 * Utility to create submaps, where given bounds override
2953 * unbounded(null) ones and/or are checked against bounded ones.
2954 */
2955 private SubMap<K, V> newSubMap(K fromKey,
2956 boolean fromInclusive, K toKey, boolean toInclusive) {
2957 if (isDescending) { // flip senses
2958 K tk = fromKey;
2959 fromKey = toKey;
2960 toKey = tk;
2961 boolean ti = fromInclusive;
2962 fromInclusive = toInclusive;
2963 toInclusive = ti;
2964 }
2965 if (lo != null) {
2966 if (fromKey == null) {
2967 fromKey = lo;
2968 fromInclusive = loInclusive;
2969 } else {
2970 int c = m.compare(fromKey, lo);
2971 if (c < 0
2972 || (c == 0 && !loInclusive && fromInclusive))
2973 throw new IllegalArgumentException(
2974 "key out of range");
2975 }
2976 }
2977 if (hi != null) {
2978 if (toKey == null) {
2979 toKey = hi;
2980 toInclusive = hiInclusive;
2981 } else {
2982 int c = m.compare(toKey, hi);
2983 if (c > 0
2984 || (c == 0 && !hiInclusive && toInclusive))
2985 throw new IllegalArgumentException(
2986 "key out of range");
2987 }
2988 }
2989 return new SubMap<K, V>(m, fromKey, fromInclusive, toKey,
2990 toInclusive, isDescending);
2991 }
2992
2993 public SubMap<K, V> subMap(K fromKey, boolean fromInclusive,
2994 K toKey, boolean toInclusive) {
2995 if (fromKey == null || toKey == null)
2996 throw new NullPointerException();
2997 return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
2998 }
2999
3000 public SubMap<K, V> headMap(K toKey, boolean inclusive) {
3001 if (toKey == null)
3002 throw new NullPointerException();
3003 return newSubMap(null, false, toKey, inclusive);
3004 }
3005
3006 public SubMap<K, V> tailMap(K fromKey, boolean inclusive) {
3007 if (fromKey == null)
3008 throw new NullPointerException();
3009 return newSubMap(fromKey, inclusive, null, false);
3010 }
3011
3012 public SubMap<K, V> subMap(K fromKey, K toKey) {
3013 return subMap(fromKey, true, toKey, false);
3014 }
3015
3016 public SubMap<K, V> headMap(K toKey) {
3017 return headMap(toKey, false);
3018 }
3019
3020 public SubMap<K, V> tailMap(K fromKey) {
3021 return tailMap(fromKey, true);
3022 }
3023
3024 public SubMap<K, V> descendingMap() {
3025 return new SubMap<K, V>(m, lo, loInclusive, hi,
3026 hiInclusive, !isDescending);
3027 }
3028
3029 /* ---------------- Relational methods -------------- */
3030
3031 public Map.Entry<K, V> ceilingEntry(K key) {
3032 return getNearEntry(key, (m.GT | m.EQ));
3033 }
3034
3035 public K ceilingKey(K key) {
3036 return getNearKey(key, (m.GT | m.EQ));
3037 }
3038
3039 public Map.Entry<K, V> lowerEntry(K key) {
3040 return getNearEntry(key, (m.LT));
3041 }
3042
3043 public K lowerKey(K key) {
3044 return getNearKey(key, (m.LT));
3045 }
3046
3047 public Map.Entry<K, V> floorEntry(K key) {
3048 return getNearEntry(key, (m.LT | m.EQ));
3049 }
3050
3051 public K floorKey(K key) {
3052 return getNearKey(key, (m.LT | m.EQ));
3053 }
3054
3055 public Map.Entry<K, V> higherEntry(K key) {
3056 return getNearEntry(key, (m.GT));
3057 }
3058
3059 public K higherKey(K key) {
3060 return getNearKey(key, (m.GT));
3061 }
3062
3063 public K firstKey() {
3064 return isDescending ? highestKey() : lowestKey();
3065 }
3066
3067 public K lastKey() {
3068 return isDescending ? lowestKey() : highestKey();
3069 }
3070
3071 public Map.Entry<K, V> firstEntry() {
3072 return isDescending ? highestEntry() : lowestEntry();
3073 }
3074
3075 public Map.Entry<K, V> lastEntry() {
3076 return isDescending ? lowestEntry() : highestEntry();
3077 }
3078
3079 public Map.Entry<K, V> pollFirstEntry() {
3080 return isDescending ? removeHighest() : removeLowest();
3081 }
3082
3083 public Map.Entry<K, V> pollLastEntry() {
3084 return isDescending ? removeLowest() : removeHighest();
3085 }
3086
3087 /* ---------------- Submap Views -------------- */
3088
3089 public NavigableSet<K> keySet() {
3090 KeySet<K> ks = keySetView;
3091 return (ks != null) ? ks : (keySetView = new KeySet(this ));
3092 }
3093
3094 public NavigableSet<K> navigableKeySet() {
3095 KeySet<K> ks = keySetView;
3096 return (ks != null) ? ks : (keySetView = new KeySet(this ));
3097 }
3098
3099 public Collection<V> values() {
3100 Collection<V> vs = valuesView;
3101 return (vs != null) ? vs : (valuesView = new Values(this ));
3102 }
3103
3104 public Set<Map.Entry<K, V>> entrySet() {
3105 Set<Map.Entry<K, V>> es = entrySetView;
3106 return (es != null) ? es : (entrySetView = new EntrySet(
3107 this ));
3108 }
3109
3110 public NavigableSet<K> descendingKeySet() {
3111 return descendingMap().navigableKeySet();
3112 }
3113
3114 Iterator<K> keyIterator() {
3115 return new SubMapKeyIterator();
3116 }
3117
3118 Iterator<V> valueIterator() {
3119 return new SubMapValueIterator();
3120 }
3121
3122 Iterator<Map.Entry<K, V>> entryIterator() {
3123 return new SubMapEntryIterator();
3124 }
3125
3126 /**
3127 * Variant of main Iter class to traverse through submaps.
3128 */
3129 abstract class SubMapIter<T> implements Iterator<T> {
3130 /** the last node returned by next() */
3131 Node<K, V> lastReturned;
3132 /** the next node to return from next(); */
3133 Node<K, V> next;
3134 /** Cache of next value field to maintain weak consistency */
3135 V nextValue;
3136
3137 SubMapIter() {
3138 for (;;) {
3139 next = isDescending ? hiNode() : loNode();
3140 if (next == null)
3141 break;
3142 Object x = next.value;
3143 if (x != null && x != next) {
3144 if (!inBounds(next.key))
3145 next = null;
3146 else
3147 nextValue = (V) x;
3148 break;
3149 }
3150 }
3151 }
3152
3153 public final boolean hasNext() {
3154 return next != null;
3155 }
3156
3157 final void advance() {
3158 if (next == null)
3159 throw new NoSuchElementException();
3160 lastReturned = next;
3161 if (isDescending)
3162 descend();
3163 else
3164 ascend();
3165 }
3166
3167 private void ascend() {
3168 for (;;) {
3169 next = next.next;
3170 if (next == null)
3171 break;
3172 Object x = next.value;
3173 if (x != null && x != next) {
3174 if (tooHigh(next.key))
3175 next = null;
3176 else
3177 nextValue = (V) x;
3178 break;
3179 }
3180 }
3181 }
3182
3183 private void descend() {
3184 for (;;) {
3185 next = m.findNear(lastReturned.key, LT);
3186 if (next == null)
3187 break;
3188 Object x = next.value;
3189 if (x != null && x != next) {
3190 if (tooLow(next.key))
3191 next = null;
3192 else
3193 nextValue = (V) x;
3194 break;
3195 }
3196 }
3197 }
3198
3199 public void remove() {
3200 Node<K, V> l = lastReturned;
3201 if (l == null)
3202 throw new IllegalStateException();
3203 m.remove(l.key);
3204 lastReturned = null;
3205 }
3206
3207 }
3208
3209 final class SubMapValueIterator extends SubMapIter<V> {
3210 public V next() {
3211 V v = nextValue;
3212 advance();
3213 return v;
3214 }
3215 }
3216
3217 final class SubMapKeyIterator extends SubMapIter<K> {
3218 public K next() {
3219 Node<K, V> n = next;
3220 advance();
3221 return n.key;
3222 }
3223 }
3224
3225 final class SubMapEntryIterator extends
3226 SubMapIter<Map.Entry<K, V>> {
3227 public Map.Entry<K, V> next() {
3228 Node<K, V> n = next;
3229 V v = nextValue;
3230 advance();
3231 return new AbstractMap.SimpleImmutableEntry<K, V>(
3232 n.key, v);
3233 }
3234 }
3235 }
3236 }
|