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