-
Notifications
You must be signed in to change notification settings - Fork 668
/
ConcurrentSkipListMap.java
4277 lines (3656 loc) · 152 KB
/
ConcurrentSkipListMap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent;
import java.io.IOException;
import java.io.Serializable;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.Spliterator;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* A scalable concurrent {@link ConcurrentNavigableMap} implementation.
* The map is sorted according to the {@linkplain Comparable natural
* ordering} of its keys, or by a {@link Comparator} provided at map
* creation time, depending on which constructor is used.
*
* <p>This class implements a concurrent variant of <a
* href="http://en.wikipedia.org/wiki/Skip_list" target="_top">SkipLists</a>
* providing expected average <i>log(n)</i> time cost for the
* {@code containsKey}, {@code get}, {@code put} and
* {@code remove} operations and their variants. Insertion, removal,
* update, and access operations safely execute concurrently by
* multiple threads.
*
* <p>Iterators and spliterators are
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>Ascending key ordered views and their iterators are faster than
* descending ones.
*
* <p>All {@code Map.Entry} pairs returned by methods in this class
* and its views represent snapshots of mappings at the time they were
* produced. They do <em>not</em> support the {@code Entry.setValue}
* method. (Note however that it is possible to change mappings in the
* associated map using {@code put}, {@code putIfAbsent}, or
* {@code replace}, depending on exactly which effect you need.)
*
* <p>Beware that bulk operations {@code putAll}, {@code equals},
* {@code toArray}, {@code containsValue}, and {@code clear} are
* <em>not</em> guaranteed to be performed atomically. For example, an
* iterator operating concurrently with a {@code putAll} operation
* might view only some of the added elements.
*
* <p>This class and its views and iterators implement all of the
* <em>optional</em> methods of the {@link Map} and {@link Iterator}
* interfaces. Like most other concurrent collections, this class does
* <em>not</em> permit the use of {@code null} keys or values because some
* null return values cannot be reliably distinguished from the absence of
* elements.
*
* <p>This class is a member of the
* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
* Java Collections Framework</a>.
*
* @author Doug Lea
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
* @since 1.6
*/
/*
* 跳表-映射,利用跳表来存储键值对集合。key与value均不能为null
*
* 跳表首先是一种有序链表,至于是升序还是降序,则取决于应用的外部比较器comparator
* 与一般的有序链表相比,跳表会在有序链表之上建立多级索引,这使得其查找过程类似于二叉树的查找
*
* ConcurrentSkipListMap是线程安全的Map,但大多数时候,应该使用HashMap或者ConcurrentHashMap
* 但如果需要使用导航功能,则需要使用ConcurrentSkipListMap
*/
public class ConcurrentSkipListMap<K, V> extends AbstractMap<K, V> implements ConcurrentNavigableMap<K, V>, Cloneable, Serializable {
/*
* This class implements a tree-like two-dimensionally linked skip
* list in which the index levels are represented in separate
* nodes from the base nodes holding data. There are two reasons
* for taking this approach instead of the usual array-based
* structure: 1) Array based implementations seem to encounter
* more complexity and overhead 2) We can use cheaper algorithms
* for the heavily-traversed index lists than can be used for the
* base lists. Here's a picture of some of the basics for a
* possible list with 2 levels of index:
*
* Head nodes Index nodes
* +-+ right +-+ +-+
* |2|---------------->| |--------------------->| |->null
* +-+ +-+ +-+
* | down | |
* v v v
* +-+ +-+ +-+ +-+ +-+ +-+
* |1|----------->| |->| |------>| |----------->| |------>| |->null
* +-+ +-+ +-+ +-+ +-+ +-+
* v | | | | |
* Nodes next v v v v v
* +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
* | |->|A|->|B|->|C|->|D|->|E|->|F|->|G|->|H|->|I|->|J|->|K|->null
* +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
*
* The base lists use a variant of the HM linked ordered set
* algorithm. See Tim Harris, "A pragmatic implementation of
* non-blocking linked lists"
* http://www.cl.cam.ac.uk/~tlh20/publications.html and Maged
* Michael "High Performance Dynamic Lock-Free Hash Tables and
* List-Based Sets"
* http://www.research.ibm.com/people/m/michael/pubs.htm. The
* basic idea in these lists is to mark the "next" pointers of
* deleted nodes when deleting to avoid conflicts with concurrent
* insertions, and when traversing to keep track of triples
* (predecessor, node, successor) in order to detect when and how
* to unlink these deleted nodes.
*
* Rather than using mark-bits to mark list deletions (which can
* be slow and space-intensive using AtomicMarkedReference), nodes
* use direct CAS'able next pointers. On deletion, instead of
* marking a pointer, they splice in another node that can be
* thought of as standing for a marked pointer (see method
* unlinkNode). Using plain nodes acts roughly like "boxed"
* implementations of marked pointers, but uses new nodes only
* when nodes are deleted, not for every link. This requires less
* space and supports faster traversal. Even if marked references
* were better supported by JVMs, traversal using this technique
* might still be faster because any search need only read ahead
* one more node than otherwise required (to check for trailing
* marker) rather than unmasking mark bits or whatever on each
* read.
*
* This approach maintains the essential property needed in the HM
* algorithm of changing the next-pointer of a deleted node so
* that any other CAS of it will fail, but implements the idea by
* changing the pointer to point to a different node (with
* otherwise illegal null fields), not by marking it. While it
* would be possible to further squeeze space by defining marker
* nodes not to have key/value fields, it isn't worth the extra
* type-testing overhead. The deletion markers are rarely
* encountered during traversal, are easily detected via null
* checks that are needed anyway, and are normally quickly garbage
* collected. (Note that this technique would not work well in
* systems without garbage collection.)
*
* In addition to using deletion markers, the lists also use
* nullness of value fields to indicate deletion, in a style
* similar to typical lazy-deletion schemes. If a node's value is
* null, then it is considered logically deleted and ignored even
* though it is still reachable.
*
* Here's the sequence of events for a deletion of node n with
* predecessor b and successor f, initially:
*
* +------+ +------+ +------+
* ... | b |------>| n |----->| f | ...
* +------+ +------+ +------+
*
* 1. CAS n's value field from non-null to null.
* Traversals encountering a node with null value ignore it.
* However, ongoing insertions and deletions might still modify
* n's next pointer.
*
* 2. CAS n's next pointer to point to a new marker node.
* From this point on, no other nodes can be appended to n.
* which avoids deletion errors in CAS-based linked lists.
*
* +------+ +------+ +------+ +------+
* ... | b |------>| n |----->|marker|------>| f | ...
* +------+ +------+ +------+ +------+
*
* 3. CAS b's next pointer over both n and its marker.
* From this point on, no new traversals will encounter n,
* and it can eventually be GCed.
* +------+ +------+
* ... | b |----------------------------------->| f | ...
* +------+ +------+
*
* A failure at step 1 leads to simple retry due to a lost race
* with another operation. Steps 2-3 can fail because some other
* thread noticed during a traversal a node with null value and
* helped out by marking and/or unlinking. This helping-out
* ensures that no thread can become stuck waiting for progress of
* the deleting thread.
*
* Skip lists add indexing to this scheme, so that the base-level
* traversals start close to the locations being found, inserted
* or deleted -- usually base level traversals only traverse a few
* nodes. This doesn't change the basic algorithm except for the
* need to make sure base traversals start at predecessors (here,
* b) that are not (structurally) deleted, otherwise retrying
* after processing the deletion.
*
* Index levels are maintained using CAS to link and unlink
* successors ("right" fields). Races are allowed in index-list
* operations that can (rarely) fail to link in a new index node.
* (We can't do this of course for data nodes.) However, even
* when this happens, the index lists correctly guide search.
* This can impact performance, but since skip lists are
* probabilistic anyway, the net result is that under contention,
* the effective "p" value may be lower than its nominal value.
*
* Index insertion and deletion sometimes require a separate
* traversal pass occurring after the base-level action, to add or
* remove index nodes. This adds to single-threaded overhead, but
* improves contended multithreaded performance by narrowing
* interference windows, and allows deletion to ensure that all
* index nodes will be made unreachable upon return from a public
* remove operation, thus avoiding unwanted garbage retention.
*
* Indexing uses skip list parameters that maintain good search
* performance while using sparser-than-usual indices: The
* hardwired parameters k=1, p=0.5 (see method doPut) mean that
* about one-quarter of the nodes have indices. Of those that do,
* half have one level, a quarter have two, and so on (see Pugh's
* Skip List Cookbook, sec 3.4), up to a maximum of 62 levels
* (appropriate for up to 2^63 elements). The expected total
* space requirement for a map is slightly less than for the
* current implementation of java.util.TreeMap.
*
* Changing the level of the index (i.e, the height of the
* tree-like structure) also uses CAS. Creation of an index with
* height greater than the current level adds a level to the head
* index by CAS'ing on a new top-most head. To maintain good
* performance after a lot of removals, deletion methods
* heuristically try to reduce the height if the topmost levels
* appear to be empty. This may encounter races in which it is
* possible (but rare) to reduce and "lose" a level just as it is
* about to contain an index (that will then never be
* encountered). This does no structural harm, and in practice
* appears to be a better option than allowing unrestrained growth
* of levels.
*
* This class provides concurrent-reader-style memory consistency,
* ensuring that read-only methods report status and/or values no
* staler than those holding at method entry. This is done by
* performing all publication and structural updates using
* (volatile) CAS, placing an acquireFence in a few access
* methods, and ensuring that linked objects are transitively
* acquired via dependent reads (normally once) unless performing
* a volatile-mode CAS operation (that also acts as an acquire and
* release). This form of fence-hoisting is similar to RCU and
* related techniques (see McKenney's online book
* https://www.kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html)
* It minimizes overhead that may otherwise occur when using so
* many volatile-mode reads. Using explicit acquireFences is
* logistically easier than targeting particular fields to be read
* in acquire mode: fences are just hoisted up as far as possible,
* to the entry points or loop headers of a few methods. A
* potential disadvantage is that these few remaining fences are
* not easily optimized away by compilers under exclusively
* single-thread use. It requires some care to avoid volatile
* mode reads of other fields. (Note that the memory semantics of
* a reference dependently read in plain mode exactly once are
* equivalent to those for atomic opaque mode.) Iterators and
* other traversals encounter each node and value exactly once.
* Other operations locate an element (or position to insert an
* element) via a sequence of dereferences. This search is broken
* into two parts. Method findPredecessor (and its specialized
* embeddings) searches index nodes only, returning a base-level
* predecessor of the key. Callers carry out the base-level
* search, restarting if encountering a marker preventing link
* modification. In some cases, it is possible to encounter a
* node multiple times while descending levels. For mutative
* operations, the reported value is validated using CAS (else
* retrying), preserving linearizability with respect to each
* other. Others may return any (non-null) value holding in the
* course of the method call. (Search-based methods also include
* some useless-looking explicit null checks designed to allow
* more fields to be nulled out upon removal, to reduce floating
* garbage, but which is not currently done, pending discovery of
* a way to do this with less impact on other operations.)
*
* To produce random values without interference across threads,
* we use within-JDK thread local random support (via the
* "secondary seed", to avoid interference with user-level
* ThreadLocalRandom.)
*
* For explanation of algorithms sharing at least a couple of
* features with this one, see Mikhail Fomitchev's thesis
* (http://www.cs.yorku.ca/~mikhail/), Keir Fraser's thesis
* (http://www.cl.cam.ac.uk/users/kaf24/), and Hakan Sundell's
* thesis (http://www.cs.chalmers.se/~phs/).
*
* Notation guide for local variables
* Node: b, n, f, p for predecessor, node, successor, aux
* Index: q, r, d for index node, right, down.
* Head: h
* Keys: k, key
* Values: v, value
* Comparisons: c
*/
private static final int EQ = 1;
private static final int LT = 2;
private static final int GT = 0; // Actually checked as !LT
/**
* The comparator used to maintain order in this map, or null if
* using natural ordering. (Non-private to simplify access in
* nested classes.)
* @serial
*/
final Comparator<? super K> comparator; // 外部比较器
/** Lazily initialized topmost index of the skiplist. */
private transient Index<K,V> head; // 跳表索引起点,需要从这里开始搜索元素
/** Lazily initialized element count */
private transient LongAdder adder; // 元素计数
/** Lazily initialized key set */
private transient KeySet<K,V> keySet;
/** Lazily initialized values collection */
private transient Values<K,V> values;
/** Lazily initialized entry set */
private transient EntrySet<K,V> entrySet;
/** Lazily initialized descending map */
private transient SubMap<K,V> descendingMap; // 【逆序】Map
// VarHandle mechanics
private static final VarHandle HEAD;
private static final VarHandle ADDER;
private static final VarHandle NEXT;
private static final VarHandle VAL;
private static final VarHandle RIGHT;
static {
try {
MethodHandles.Lookup l = MethodHandles.lookup();
HEAD = l.findVarHandle(ConcurrentSkipListMap.class, "head", Index.class);
ADDER = l.findVarHandle(ConcurrentSkipListMap.class, "adder", LongAdder.class);
NEXT = l.findVarHandle(Node.class, "next", Node.class);
VAL = l.findVarHandle(Node.class, "val", Object.class);
RIGHT = l.findVarHandle(Index.class, "right", Index.class);
} catch(ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Constructs a new, empty map, sorted according to the
* {@linkplain Comparable natural ordering} of the keys.
*/
public ConcurrentSkipListMap() {
this.comparator = null;
}
/**
* Constructs a new, empty map, sorted according to the specified
* comparator.
*
* @param comparator the comparator that will be used to order this map.
* If {@code null}, the {@linkplain Comparable natural
* ordering} of the keys will be used.
*/
public ConcurrentSkipListMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
/**
* Constructs a new map containing the same mappings as the given map,
* sorted according to the {@linkplain Comparable natural ordering} of
* the keys.
*
* @param m the map whose mappings are to be placed in this map
* @throws ClassCastException if the keys in {@code m} are not
* {@link Comparable}, or are not mutually comparable
* @throws NullPointerException if the specified map or any of its keys
* or values are null
*/
public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {
this.comparator = null;
putAll(m);
}
/**
* Constructs a new map containing the same mappings and using the
* same ordering as the specified sorted map.
*
* @param m the sorted map whose mappings are to be placed in this
* map, and whose comparator is to be used to sort this map
* @throws NullPointerException if the specified sorted map or any of
* its keys or values are null
*/
public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {
this.comparator = m.comparator();
buildFromSorted(m); // initializes transients
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 存值 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
*
* @return the previous value associated with the specified key, or
* {@code null} if there was no mapping for the key
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key or value is null
*/
// 将指定的元素(key-value)存入Map,并返回旧值,允许覆盖
public V put(K key, V value) {
if(value == null) {
throw new NullPointerException();
}
return doPut(key, value, false);
}
/**
* {@inheritDoc}
*
* @return the previous value associated with the specified key,
* or {@code null} if there was no mapping for the key
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key or value is null
*/
// 将指定的元素(key-value)存入Map,并返回旧值,不允许覆盖
public V putIfAbsent(K key, V value) {
if(value == null) {
throw new NullPointerException();
}
return doPut(key, value, true);
}
/*▲ 存值 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 取值 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code key} compares
* equal to {@code k} according to the map's ordering, then this
* method returns {@code v}; otherwise it returns {@code null}.
* (There can be at most one such mapping.)
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
*/
// 根据指定的key获取对应的value,如果不存在,则返回null
public V get(Object key) {
return doGet(key);
}
/**
* Returns the value to which the specified key is mapped,
* or the given defaultValue if this map contains no mapping for the key.
*
* @param key the key
* @param defaultValue the value to return if this map contains
* no mapping for the given key
*
* @return the mapping for the key, if present; else the defaultValue
*
* @throws NullPointerException if the specified key is null
* @since 1.8
*/
// 根据指定的key获取对应的value,如果不存在,则返回指定的默认值defaultValue
public V getOrDefault(Object key, V defaultValue) {
V v = doGet(key);
return v != null ? v : defaultValue;
}
/*▲ 取值 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 移除 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key key for which mapping should be removed
*
* @return the previous value associated with the specified key, or
* {@code null} if there was no mapping for the key
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
*/
// 移除拥有指定key的元素,并返回刚刚移除的元素的值
public V remove(Object key) {
return doRemove(key, null);
}
/**
* {@inheritDoc}
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
*/
// 移除拥有指定key和value的元素,返回值表示是否移除成功
public boolean remove(Object key, Object value) {
if(key == null) {
throw new NullPointerException();
}
return value != null && doRemove(key, value) != null;
}
/**
* Removes all of the mappings from this map.
*/
// 清空当前Map中所有元素
public void clear() {
Index<K, V> h, r, d;
VarHandle.acquireFence();
while((h = head) != null) {
// remove indices
if((r = h.right) != null) {
RIGHT.compareAndSet(h, r, null);
// remove levels
} else if((d = h.down) != null) {
HEAD.compareAndSet(this, h, d);
// 移除完索引后,需要移除元素
} else {
long count = 0L;
Node<K, V> b = h.node;
// remove nodes
if(b != null) {
Node<K, V> n;
while((n = b.next) != null) {
V v = n.val;
if(v != null && VAL.compareAndSet(n, v, null)) {
--count;
v = null;
}
if(v == null) {
unlinkNode(b, n);
}
}
}
if(count != 0L) {
addCount(count);
} else {
break;
}
}
}
}
/*▲ 移除 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 替换 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* {@inheritDoc}
*
* @return the previous value associated with the specified key,
* or {@code null} if there was no mapping for the key
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key or value is null
*/
// 将拥有指定key的元素的值替换为newValue,并返回刚刚替换的元素的值(替换失败返回null)
public V replace(K key, V newValue) {
if(key == null || newValue == null) {
throw new NullPointerException();
}
for(; ; ) {
// 返回包含key的元素,如果不存在则返回null
Node<K, V> n = findNode(key);
if(n== null) {
return null;
}
V v = n.val;
if(v != null && VAL.compareAndSet(n, v, newValue)) {
return v;
}
}
}
/**
* {@inheritDoc}
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if any of the arguments are null
*/
// 将拥有指定key和oldValue的元素的值替换为newValue,返回值表示是否成功替换
public boolean replace(K key, V oldValue, V newValue) {
if(key == null || oldValue == null || newValue == null) {
throw new NullPointerException();
}
for(; ; ) {
Node<K, V> n = findNode(key);
if(n == null) {
return false;
}
V v = n.val;
if(v != null) {
if(!oldValue.equals(v)) {
return false;
}
if(VAL.compareAndSet(n, v, newValue)) {
return true;
}
}
}
}
// 替换当前Map中的所有元素,替换策略由function决定,function的入参是元素的key和value,出参作为新值
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
if(function == null) {
throw new NullPointerException();
}
// 获取跳表(链表)元素的头结点
Node<K, V> b = baseHead();
if(b == null) {
return;
}
Node<K, V> n;
while((n = b.next) != null) {
V v;
while((v = n.val) != null) {
V r = function.apply(n.key, v);
if(r == null) {
throw new NullPointerException();
}
if(VAL.compareAndSet(n, v, r)) {
break;
}
}
b = n;
}
}
/*▲ 替换 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 包含查询 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns {@code true} if this map contains a mapping for the specified
* key.
*
* @param key key whose presence in this map is to be tested
*
* @return {@code true} if this map contains a mapping for the specified key
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
*/
// 判断Map中是否存在指定key的元素
public boolean containsKey(Object key) {
return doGet(key) != null;
}
/**
* Returns {@code true} if this map maps one or more keys to the
* specified value. This operation requires time linear in the
* map size. Additionally, it is possible for the map to change
* during execution of this method, in which case the returned
* result may be inaccurate.
*
* @param value value whose presence in this map is to be tested
*
* @return {@code true} if a mapping to {@code value} exists;
* {@code false} otherwise
*
* @throws NullPointerException if the specified value is null
*/
// 判断Map中是否存在指定value的元素
public boolean containsValue(Object value) {
if(value == null) {
throw new NullPointerException();
}
// 获取跳表(链表)元素的头结点
Node<K, V> b = baseHead();
if(b == null) {
return false;
}
Node<K, V> n;
// 直接遍历所有元素
while((n = b.next) != null) {
V v = n.val;
if(v != null && value.equals(v)) {
return true;
} else {
b = n;
}
}
return false;
}
/*▲ 包含查询 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 视图 ████████████████████████████████████████████████████████████████████████████████┓ */
/*
* Note: Lazy initialization works for views because view classes
* are stateless/immutable so it doesn't matter wrt correctness if
* more than one is created (which will only rarely happen). Even
* so, the following idiom conservatively ensures that the method
* returns the one it created if it does so, not one created by
* another racing thread.
*/
/**
* Returns a {@link NavigableSet} view of the keys contained in this map.
*
* <p>The set's iterator returns the keys in ascending order.
* The set's spliterator additionally reports {@link Spliterator#CONCURRENT},
* {@link Spliterator#NONNULL}, {@link Spliterator#SORTED} and
* {@link Spliterator#ORDERED}, with an encounter order that is ascending
* key order.
*
* <p>The {@linkplain Spliterator#getComparator() spliterator's comparator}
* is {@code null} if the {@linkplain #comparator() map's comparator}
* is {@code null}.
* Otherwise, the spliterator's comparator is the same as or imposes the
* same total ordering as the map's comparator.
*
* <p>The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. The set supports element
* removal, which removes the corresponding mapping from the map,
* via the {@code Iterator.remove}, {@code Set.remove},
* {@code removeAll}, {@code retainAll}, and {@code clear}
* operations. It does not support the {@code add} or {@code addAll}
* operations.
*
* <p>The view's iterators and spliterators are
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>This method is equivalent to method {@code navigableKeySet}.
*
* @return a navigable set view of the keys in this map
*/
// 获取Map中key的集合
public NavigableSet<K> keySet() {
KeySet<K, V> ks = keySet;
if(ks != null) {
return ks;
}
return keySet = new KeySet<>(this);
}
/**
* Returns a {@link Collection} view of the values contained in this map.
* <p>The collection's iterator returns the values in ascending order
* of the corresponding keys. The collections's spliterator additionally
* reports {@link Spliterator#CONCURRENT}, {@link Spliterator#NONNULL} and
* {@link Spliterator#ORDERED}, with an encounter order that is ascending
* order of the corresponding keys.
*
* <p>The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the {@code Iterator.remove},
* {@code Collection.remove}, {@code removeAll},
* {@code retainAll} and {@code clear} operations. It does not
* support the {@code add} or {@code addAll} operations.
*
* <p>The view's iterators and spliterators are
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*/
// 获取Map中value的集合
public Collection<V> values() {
Values<K, V> vs = values;
if(vs != null) {
return vs;
}
return values = new Values<>(this);
}
/**
* Returns a {@link Set} view of the mappings contained in this map.
*
* <p>The set's iterator returns the entries in ascending key order. The
* set's spliterator additionally reports {@link Spliterator#CONCURRENT},
* {@link Spliterator#NONNULL}, {@link Spliterator#SORTED} and
* {@link Spliterator#ORDERED}, with an encounter order that is ascending
* key order.
*
* <p>The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. The set supports element
* removal, which removes the corresponding mapping from the map,
* via the {@code Iterator.remove}, {@code Set.remove},
* {@code removeAll}, {@code retainAll} and {@code clear}
* operations. It does not support the {@code add} or
* {@code addAll} operations.
*
* <p>The view's iterators and spliterators are
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>The {@code Map.Entry} elements traversed by the {@code iterator}
* or {@code spliterator} do <em>not</em> support the {@code setValue}
* operation.
*
* @return a set view of the mappings contained in this map,
* sorted in ascending key order
*/
// 获取Map中key-value对的集合
public Set<Map.Entry<K, V>> entrySet() {
EntrySet<K, V> es = entrySet;
if(es != null) {
return es;
}
return entrySet = new EntrySet<K, V>(this);
}
/*▲ 视图 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 遍历 ████████████████████████████████████████████████████████████████████████████████┓ */
// 遍历当前Map中的元素,并对其应用action操作,action的入参是元素的key和value
public void forEach(BiConsumer<? super K, ? super V> action) {
if(action == null) {
throw new NullPointerException();
}
// 返回跳表(链表)元素的头结点
Node<K, V> b = baseHead();
if(b == null) {
return;
}
Node<K, V> n;
while((n = b.next) != null) {
V v = n.val;
if(v != null) {
action.accept(n.key, v);
}
b = n;
}
}
/*▲ 遍历 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 重新映射 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* If the specified key is not already associated with a value,
* associates it with the given value. Otherwise, replaces the
* value with the results of the given remapping function, or
* removes if {@code null}. The function is <em>NOT</em>
* guaranteed to be applied once atomically.
*
* @param key key with which the specified value is to be associated
* @param value the value to use if absent
* @param remappingFunction the function to recompute a value if present
*
* @return the new value associated with the specified key, or null if none
*
* @throws NullPointerException if the specified key or value is null
* or the remappingFunction is null
* @since 1.8
*/
// 插入/删除/替换操作,主要意图:使用备用value和旧value创造的新value来更新旧value
public V merge(K key, V bakValue, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
if(key == null || bakValue == null || remappingFunction == null) {
throw new NullPointerException();
}
for(; ; ) {
// 获取包含指定key的元素,如果不存在则返回null
Node<K, V> n = findNode(key);
V oldValue;
// 如果不存在包含指定key的元素
if(n == null) {
// 插入新元素
if(doPut(key, bakValue, true) == null) {
return bakValue;
}
} else if((oldValue = n.val) != null) {
// 计算新值
V newValue = remappingFunction.apply(oldValue, bakValue);
// 如果新值不为null
if(newValue != null) {
// 更新元素
if(VAL.compareAndSet(n, oldValue, newValue)) {
return newValue;
}
// 如果新值为空,则尝试移除该元素
} else if(doRemove(key, oldValue) != null) {
return null;