-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopyOnWriteTreeMap.java
More file actions
3812 lines (3370 loc) · 125 KB
/
Copy pathCopyOnWriteTreeMap.java
File metadata and controls
3812 lines (3370 loc) · 125 KB
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
/*
* MIT License
*
* Copyright (c) 2026 Casper Kuethe
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.casperswebsites.util.concurrent;
import java.io.Serial;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* A 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 Copy-on-Write (CoW) variant of a <a
* href="https://en.wikipedia.org/wiki/Red%E2%80%93black_tree" target="_top">
* Red-black Tree</a>, the same algorithm used in {@link TreeMap}, providing
* expected <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>
* <p>
*
* <p>
* Unlike other CoW implementations that copy all underlying
* nodes, {@code CopyOnWriteTreeMap} is implemented by copying only the nodes
* that are necessary to be copied, then atomically swapping the root.
* </p>
*
* <p>
* Iterators and spliterators are <i>strongly consistent</i>.
*
* <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>
* This class and its views and iterators implement most 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>
*
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
* @author Casper Kuethe
*/
public class CopyOnWriteTreeMap<K, V> extends AbstractMap<K, V>
implements ConcurrentNavigableMap<K, V>, Cloneable, Serializable {
@Serial
private static final long serialVersionUID = -8079617966180616297L;
/**
* The comparator used to maintain order in this map, or null if using
* natural ordering. (Non-private to simplify access in nested classes.)
*
* @serial
*/
@SuppressWarnings("serial") // Conditionally serializable
final Comparator<? super K> comparator;
/**
* Root element
*/
private transient AtomicReference<Node<K, V>> root;
/**
* Element count
*/
private transient AtomicInteger size;
/**
* 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;
private static final int MAX_TREE_HEIGHT = 64;
private static final int SPIN_THRESHOLD = 10;
private int backoff(int spins) {
if (spins < SPIN_THRESHOLD) {
Thread.onSpinWait();
return spins + 1;
} else {
// spin failed, use the nuclear option
synchronized (root) {
}
return 0; // reset after blocking
}
}
// @SuppressWarnings("unchecked")
// private static <K, V> PathBuffer<K, V> createPathBuffer() {
// return new PathBuffer<>(MAX_TREE_HEIGHT);
// }
// private static final ThreadLocal<ArrayDeque<Node<K,V>>> STACK_POOL =
// ThreadLocal.withInitial(ArrayDeque::new);
@SuppressWarnings({ "rawtypes", "unchecked" })
private static final ThreadLocal<PathBuffer<?, ?>> PATH_BUFFER_CACHE = ThreadLocal
.withInitial(() -> new PathBuffer(MAX_TREE_HEIGHT * 2));
@SuppressWarnings("unchecked")
private static <K, V> PathBuffer<K, V> getPathBuffer() {
PathBuffer<K, V> pb = (PathBuffer<K, V>) PATH_BUFFER_CACHE.get();
pb.clear();
return pb;
}
private static <K, V> PathBuffer<K, V> createPathBuffer() {
return new PathBuffer<>(MAX_TREE_HEIGHT * 2);
}
private static final boolean RED = false;
private static final boolean BLACK = true;
/**
* A node in a Red-black tree holds a key and a value and can have a color,
* either red or black.
*/
static final class Node<K, V> implements Map.Entry<K, V> {
final K key;
V value;
Node<K, V> left;
Node<K, V> right;
boolean color;
Node(K key, V value) {
this.key = key;
this.value = value;
this.color = RED;
}
Node(K key, V value, boolean color, Node<K, V> left, Node<K, V> right) {
this.key = key;
this.value = value;
this.color = color;
this.left = left;
this.right = right;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
/**
* Copies the current node with a different value
*
* @param newValue
* @return the new node
*/
Node<K, V> withValue(V newValue) {
return new Node<>(key, newValue, color, left, right);
}
/**
* Copies the current node with a different color
*
* @param newColor
* @return the new node
*/
Node<K, V> withColor(boolean newColor) {
return new Node<>(key, value, newColor, left, right);
}
/**
* Copies the current node with a different left node
*
* @param newLeft
* @return the new node
*/
Node<K, V> withLeft(Node<K, V> newLeft) {
return new Node<>(key, value, color, newLeft, right);
}
/**
* Copies the current node with a different right node
*
* @param newRight
* @return the new node
*/
Node<K, V> withRight(Node<K, V> newRight) {
return new Node<>(key, value, color, left, newRight);
}
/**
* @return a copy of the current node
*/
Node<K, V> copy() {
return new Node<K, V>(key, value, color, left, right);
}
public boolean equals(Object o) {
return o instanceof Node<?, ?> e && key.equals(e.key) && value.equals(e.value);
}
}
private static <K, V> boolean colorOf(Node<K, V> node) {
return node == null ? BLACK : node.color;
}
private static <K, V> Node<K, V> leftOf(Node<K, V> node) {
return node == null ? null : node.left;
}
private static <K, V> Node<K, V> rightOf(Node<K, V> node) {
return node == null ? null : node.right;
}
private static <K, V> boolean keyEquals(Node<K, V> a, Node<K, V> b) {
return a != null && b != null && a.key.equals(b.key);
}
/**
* Represents the relative offset in a {@code PathBuffer} to get the
* corresponding relation.
*
* <p>
* For example, the index of the current node's parent is
* {@code pointer - NodePathOffset.PARENT.ordinal()}
* equals {@code pointer - 2}.
* </p>
*/
enum NodePathOffset {
CURRENT,
SIBLING,
PARENT,
UNCLE,
GRANDPARENT;
}
private final static boolean LEFT = false;
private final static boolean RIGHT = true;
/**
* A fixed size reusable buffer that stores the "path" of a node when traversing
* a binary tree.
* Allowing easy access to a sibling, parent, uncle, or grandparent relative to
* a node without
* the need of a {@code parent} pointer.
*
* <p>
* Every instance of `PathBuffer` has a max size of {@code MAX_TREE_HEIGHT}.
* This limit means it can store the path of a tree with {@code 2^63 - 1} nodes
* from the root to its leafs.
* </p>
*
* @param <K>
* @param <V>
*/
static final class PathBuffer<K, V> {
private int pointer = 0;
private int len = 0;
private long branches = 0L;
private final Node<K, V>[] buffer;
@SuppressWarnings("unchecked")
public PathBuffer(int size) {
buffer = new Node[size];
}
/**
* Puts the root of the tree in the buffer. Assumes the buffer is empty.
*
* @param root
*/
public void setRoot(Node<K, V> root) {
len = 1;
pointer = 0;
buffer[0] = root;
}
/**
* @return the root of the tree stored
*/
public Node<K, V> getRoot() {
return buffer[0];
}
/**
* @return whether we are at the root
*/
public boolean atRoot() {
return pointer == 0;
}
public void clear() {
pointer = 0;
len = 0;
}
/**
* Add a node and its sibling to the buffer.
* Sets the current pointer to the current child of `parent`.
*
* @param parent
* @param gotoRight set the current pointer to the right child of `parent`,
* else set current to the left child.
*/
public void addFrom(Node<K, V> parent, boolean gotoRight) {
if (pointer + 2 >= len) {
len += 2;
}
pointer += 2;
assert pointer < buffer.length;
// current
buffer[pointer] = gotoRight ? parent.right : parent.left;
setBranch(pointer, gotoRight);
// sibling
buffer[pointer - 1] = gotoRight ? parent.left : parent.right;
// branches[pointer - 1] = !gotoRight;
// setBranch(pointer - 1, !gotoRight);
}
/**
* Go to the node at `offset` relative from the current node.
* Set's current to the root node if the node at `offset` relative from the
* current node
* cannot exist.
*
* @param offset
*/
public void gotoNode(NodePathOffset offset) {
int target = pointer - offset.ordinal();
pointer = target;
}
/**
* Get a node relative to the current node.
*
* @param offset the offset from the current node
* @return `null` if the node at `offset` doesn't exist.
*/
public Node<K, V> getNode(NodePathOffset offset) {
int target = pointer - offset.ordinal();
if (target < 0)
return null;
return buffer[target];
}
/**
* Set a node relative to the current node
*
* @param offset the offset from the current node
* @param node
*/
public void setNode(NodePathOffset offset, Node<K, V> node) {
int target = pointer - offset.ordinal();
assert target >= 0 : "attempted to set node above root";
buffer[target] = node;
}
public void setNode(int target, Node<K, V> node) {
assert target >= 0 : "attempted to set node above root";
assert target < len : "attempted to set target out of range";
buffer[target] = node;
}
/**
* Copies the node relative to the current node and updates the buffer
*
* @param offset the offset from the current node
*/
public void copyNode(NodePathOffset offset) {
int target = pointer - offset.ordinal();
assert target >= 0 : "attempted to set node above root";
buffer[target] = buffer[target].copy();
}
/**
* Colors the node relative to the current node red and updates the buffer
*
* @param offset the offset from the current node
*/
public void colorRed(NodePathOffset offset) {
int target = pointer - offset.ordinal();
if (target < 0)
return;
buffer[target] = buffer[target].withColor(RED);
}
/**
* Colors the node relative to the current node black and updates the buffer
*
* @param offset the offset from the current node
*/
public void colorBlack(NodePathOffset offset) {
int target = pointer - offset.ordinal();
if (target < 0)
return;
buffer[target] = buffer[target].withColor(BLACK);
}
/**
* Update the child of the node at `offset` relative from the current node.
* Does <b>not</b> make a copy of the parent node.
*
* @param offset the offset from the current node
* @param isRightBranch whether to set the node's right child
* @param node the new node
*/
public void setChildOf(NodePathOffset offset, boolean isRightBranch, Node<K, V> node) {
int target = pointer - offset.ordinal();
if (target < 0)
return;
// assert target >= 0 : "attempted to set child of node above root";
if (isRightBranch) {
buffer[target].right = node;
} else {
buffer[target].left = node;
}
}
private void setBranch(int offset, boolean value) {
if (value) {
branches |= (1L << (offset / 2));
} else {
branches &= ~(1L << (offset / 2));
}
// branches[offset] = value;
}
/**
* @param offset
* @return whether the node at `offset` relative from the current node is its
* parents
* right or left child
*/
public boolean getBranch(NodePathOffset offset) {
int index = (pointer - offset.ordinal()) / 2; // only need to store
assert index >= 0 : "attempted to get branch from node above root";
return (branches & (1L << index)) != 0;
// return branches[index];
}
/**
* @return the current offset in the path buffer
*/
int getPointer() {
return pointer;
}
/**
* Set the path buffer to a target pointer
*
* @param target
*/
void setPointer(int target) {
assert target >= 0 : "attempted to set node above root";
assert target < len : "attempted to set target out of range";
pointer = target;
}
/* ---------- Testing --------- */
int size() {
return len;
}
Node<K, V>[] getBuffer() {
return buffer;
}
}
/**
* Copy all parent nodes and return the new root node
*
* @param pb
* @return
*/
private Node<K, V> copyUntilRoot(PathBuffer<K, V> pb) {
while (!pb.atRoot()) {
// copy parent
pb.copyNode(NodePathOffset.PARENT);
// update child pointer of parent
pb.setChildOf(
NodePathOffset.PARENT,
pb.getBranch(NodePathOffset.CURRENT),
pb.getNode(NodePathOffset.CURRENT));
// move up the tree
pb.gotoNode(NodePathOffset.PARENT);
}
return pb.getNode(NodePathOffset.CURRENT);
}
/**
* CLR rotate left. Copies nodes that are changed.
*
* @param x
* @return the new y node
*/
private Node<K, V> rotateLeft(Node<K, V> x) {
Node<K, V> y = x.right;
return y.withLeft(x.withRight(y.left));
}
/**
* CLR rotate right. Copies nodes that are changed.
*
* @param y
* @return the new x node
*/
private Node<K, V> rotateRight(Node<K, V> y) {
Node<K, V> x = y.left;
return x.withRight(y.withLeft(x.right));
}
/* ---------------- Utilities -------------- */
/**
* Compares using comparator or natural ordering if null. Called only by
* methods that have performed required type checks.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
static int cpr(Comparator c, Object x, Object y) {
return (c != null) ? c.compare(x, y) : ((Comparable) x).compareTo(y);
}
static <K, V> AbstractMap.SimpleImmutableEntry<K, V> exportNode(Node<K, V> n) {
return n == null ? null : new AbstractMap.SimpleImmutableEntry<>(n.key, n.value);
}
/* ---------------- Traversal -------------- */
/**
* Find a node by key
*
* @param key
* @return the node if found, else {@code null}
*/
final Node<K, V> findNode(Object key) {
Node<K, V> current = root.get();
while (current != null) {
int cmp = cpr(comparator, key, current.key);
if (cmp < 0) {
current = current.left;
} else if (cmp > 0) {
current = current.right;
} else {
return current;
}
}
return null;
}
/**
* Find a node by key. Assumes {@code root} is set in the path buffer
*
* @param <K>
* @param <V>
* @param key
* @param pb the path buffer
* @param comparator
* @return the node if found, else {@code null}
*/
static <K, V> Node<K, V> findNode(Object key, PathBuffer<K, V> pb, Comparator<? super K> comparator) {
Node<K, V> current = pb.getRoot();
while (current != null) {
int cmp = cpr(comparator, key, current.key);
if (cmp < 0) {
pb.addFrom(current, LEFT);
current = current.left;
} else if (cmp > 0) {
pb.addFrom(current, RIGHT);
current = current.right;
} else {
return current;
}
}
return null;
}
/**
* Get the successor of the {@code current} node in the path buffer
*
* @param pb the PathBuffer
* @param <K>
* @param <V>
* @return the successor or `null` if there is no successor
*/
static <K, V> Node<K, V> successor(PathBuffer<K, V> pb) {
Node<K, V> node = pb.getNode(NodePathOffset.CURRENT);
if (node == null) {
return null;
} else if (node.right != null) {
pb.addFrom(node, RIGHT);
node = node.right;
while (node.left != null) {
pb.addFrom(node, LEFT);
node = node.left;
}
return node;
} else {
while (pb.getNode(NodePathOffset.PARENT) != null && pb.getBranch(NodePathOffset.CURRENT) == RIGHT) {
pb.gotoNode(NodePathOffset.PARENT);
}
pb.gotoNode(NodePathOffset.PARENT);
return pb.getNode(NodePathOffset.CURRENT);
}
}
/**
* Get the node with the smalles key in the right subtree of the current node
*
* @param pb the path buffer
* @return the minimum node in the right subtree of the curent node
*/
private Node<K, V> tree_minimum(PathBuffer<K, V> pb) {
Node<K, V> n = pb.getNode(NodePathOffset.CURRENT);
pb.addFrom(n, RIGHT);
n = n.right;
while (n != null && n.left != null) {
pb.addFrom(n, LEFT);
n = n.left;
}
return n;
}
/**
* Get the predecessor of the {@code current} node in the path buffer
*
* @param pb the PathBuffer
* @param <K>
* @param <V>
* @return the predecessor
*/
static <K, V> Node<K, V> predecessor(PathBuffer<K, V> pb) {
Node<K, V> node = pb.getNode(NodePathOffset.CURRENT);
if (node == null) {
return null;
} else if (node.left != null) {
pb.addFrom(node, LEFT);
node = node.left;
while (node.right != null) {
pb.addFrom(node, RIGHT);
node = node.right;
}
return node;
} else {
while (pb.getNode(NodePathOffset.PARENT) != null && pb.getBranch(NodePathOffset.CURRENT) == LEFT) {
pb.gotoNode(NodePathOffset.PARENT);
}
pb.gotoNode(NodePathOffset.PARENT);
return pb.getNode(NodePathOffset.CURRENT);
}
}
/* ---------------- Finding and removing first element -------------- */
final Node<K, V> findFirst() {
Node<K, V> current = root.get();
if (current != null) {
while (current.left != null)
current = current.left;
}
return current;
}
static <K, V> Node<K, V> findFirst(PathBuffer<K, V> pb) {
Node<K, V> current = pb.getRoot();
if (current != null) {
while (current.left != null) {
pb.addFrom(current, LEFT);
current = current.left;
}
}
return current;
}
final AbstractMap.SimpleImmutableEntry<K, V> findFirstEntry() {
return exportNode(findFirst());
}
/**
* Removes first entry; returns its snapshot.
*
* @return null if empty, else snapshot of first entry
*/
private AbstractMap.SimpleImmutableEntry<K, V> doRemoveFirstEntry() {
int spins = 0;
while (true) {
Node<K, V> oldRoot = root.get();
PathBuffer<K, V> pb = getPathBuffer();
pb.setRoot(oldRoot);
Node<K, V> node = findFirst(pb);
if (node != null) {
if (root.compareAndSet(oldRoot, deleteNode(pb))) {
this.size.decrementAndGet();
return new AbstractMap.SimpleImmutableEntry<>(node.key, node.value);
}
spins = backoff(spins);
} else {
return null;
}
}
}
/* ---------------- Finding and removing last element -------------- */
final Node<K, V> findLast() {
Node<K, V> current = root.get();
if (current != null) {
while (current.right != null)
current = current.right;
}
return current;
}
static <K, V> Node<K, V> findLast(PathBuffer<K, V> pb) {
Node<K, V> current = pb.getRoot();
if (current != null) {
while (current.right != null) {
pb.addFrom(current, RIGHT);
current = current.right;
}
}
return current;
}
final AbstractMap.SimpleImmutableEntry<K, V> findLastEntry() {
return exportNode(findLast());
}
/**
* Removes last entry; returns its snapshot. Specialized variant of
* doRemove.
*
* @return null if empty, else snapshot of last entry
*/
private Map.Entry<K, V> doRemoveLastEntry() {
int spins = 0;
while (true) {
Node<K, V> oldRoot = root.get();
PathBuffer<K, V> pb = getPathBuffer();
pb.setRoot(oldRoot);
Node<K, V> node = findLast(pb);
if (node != null) {
if (root.compareAndSet(oldRoot, deleteNode(pb))) {
this.size.decrementAndGet();
return new AbstractMap.SimpleImmutableEntry<>(node.key, node.value);
}
spins = backoff(spins);
} else {
return null;
}
}
}
/* ---------------- Insertion -------------- */
/**
* Insert a key-value pair. Replaces the old value if the key has already been
* inserted.
*
* @param key the key
* @param value the key
* @param onlyIfAbsent if true, will prevent replacing an existing value
* @return
*/
private V putInternal(K key, V value, boolean onlyIfAbsent) {
if (key == null) {
throw new NullPointerException();
}
int spins = 0;
casLoop: while (true) {
Node<K, V> oldRoot = root.get();
if (oldRoot == null) {
cpr(comparator, key, key); // type check
// insert root
Node<K, V> newRoot = new Node<>(key, value);
newRoot.color = BLACK;
if (root.compareAndSet(null, newRoot)) {
this.size.incrementAndGet();
return null;
}
spins = backoff(spins);
continue;
}
PathBuffer<K, V> pb = getPathBuffer();
pb.setRoot(oldRoot);
Node<K, V> target = oldRoot;
int cmp;
do {
cmp = cpr(comparator, key, target.key);
if (cmp < 0) {
pb.addFrom(target, LEFT);
target = target.left;
} else if (cmp > 0) {
pb.addFrom(target, RIGHT);
target = target.right;
} else {
// node has same value, replace it and else return the old value
V oldValue = target.value;
if (!onlyIfAbsent) {
pb.setNode(NodePathOffset.CURRENT, target.withValue(value));
Node<K, V> newRoot = copyUntilRoot(pb);
if (root.compareAndSet(oldRoot, newRoot)) {
return oldValue;
}
spins = backoff(spins);
continue casLoop;
}
return oldValue;
}
} while (target != null);
Node<K, V> createdNode = new Node<K, V>(key, value);
// insert node in the buffer. left/right pointer of parent is updated in
// `fixAfterInsertion` or eventually `copyUntilRoot`.
pb.setNode(NodePathOffset.CURRENT, createdNode);
Node<K, V> newRoot = fixAfterInsertion(pb);
if (root.compareAndSet(oldRoot, newRoot)) {
this.size.incrementAndGet();
return null;
}
spins = backoff(spins);
}
}
/**
* Rewrite of CLR algorithm to use the {@link PathBuffer} structure.
* Copies all nodes that need to be changed up until the root.
*
* @param pb the PathBuffer
* @return the new root node
*/
private Node<K, V> fixAfterInsertion(PathBuffer<K, V> pb) {
// case 1 don't need to do anything if the parent is null (the root)
// case 2: if the parent is red rule 4 is violated, because inserted nodes
// are always red
while (pb.getNode(NodePathOffset.CURRENT) != null && !pb.atRoot()
&& colorOf(pb.getNode(NodePathOffset.PARENT)) == RED) {
boolean parentBranch = pb.getBranch(NodePathOffset.PARENT);
// update child pointer from the parent
pb.copyNode(NodePathOffset.PARENT);
pb.setChildOf(
NodePathOffset.PARENT,
pb.getBranch(NodePathOffset.CURRENT),
pb.getNode(NodePathOffset.CURRENT));
if (pb.getNode(NodePathOffset.UNCLE) != null && colorOf(pb.getNode(NodePathOffset.UNCLE)) == RED) {
// case 3: uncle is red: recolour the grandparent and its children (rule 4)
pb.colorBlack(NodePathOffset.PARENT);
pb.colorBlack(NodePathOffset.UNCLE);
pb.colorRed(NodePathOffset.GRANDPARENT);
// update child pointers
pb.setChildOf(NodePathOffset.GRANDPARENT, parentBranch, pb.getNode(NodePathOffset.PARENT));
pb.setChildOf(NodePathOffset.GRANDPARENT, !parentBranch, pb.getNode(NodePathOffset.UNCLE));
// update target pointer
pb.gotoNode(NodePathOffset.GRANDPARENT);
} else {
// case 4: uncle is black (nil) and an "inner child"
// i.e. the current node, its parent and grandparent
// form a triangle around the uncle.
// balance the tree by performing a RL or RL rotation depending on which side
// the uncle is relative to the current node
Node<K, V> newNode;
pb.copyNode(NodePathOffset.GRANDPARENT);
if (parentBranch == LEFT && pb.getBranch(NodePathOffset.CURRENT) == RIGHT) {
newNode = rotateLeft(pb.getNode(NodePathOffset.PARENT));
pb.setNode(NodePathOffset.PARENT, newNode);
} else if (parentBranch == RIGHT && pb.getBranch(NodePathOffset.CURRENT) == LEFT) {
newNode = rotateRight(pb.getNode(NodePathOffset.PARENT));
pb.setNode(NodePathOffset.PARENT, newNode);
}
// at this point the node is always an "outer child"
// i.e. the current node and its parent and grandparent form a straight line
// at this point both the node and its parent are red and its grandparent is
// black
// if we rotate the grandparent and recolour it and the nodes parent the tree is
// fixed
pb.colorBlack(NodePathOffset.PARENT);
pb.colorRed(NodePathOffset.GRANDPARENT);
// update child pointer
pb.setChildOf(
NodePathOffset.GRANDPARENT,
pb.getBranch(NodePathOffset.PARENT),
pb.getNode(NodePathOffset.PARENT));
if (parentBranch == LEFT) {
newNode = rotateRight(pb.getNode(NodePathOffset.GRANDPARENT));
pb.setNode(NodePathOffset.GRANDPARENT, newNode);
} else {
newNode = rotateLeft(pb.getNode(NodePathOffset.GRANDPARENT));
pb.setNode(NodePathOffset.GRANDPARENT, newNode);
}
pb.gotoNode(NodePathOffset.GRANDPARENT);
// tree is fixed at this point (parent is black) and we don't need to check
// again
break;
}
}
// walk up to the root node and copy the parents
Node<K, V> newRoot = copyUntilRoot(pb);
// root node always has to be black
newRoot.color = BLACK;
return newRoot;
}
/* ---------------- Deletion -------------- */
/**
* Delete the associated node
*
* @param key the key
* @param value value if non-null, the value that must be associated with the
* key
* @return the old value, or null if not found
*/
private V doRemove(Object key, Object value) {
if (key == null) {
throw new NullPointerException();
}
int spins = 0;
while (true) {
Node<K, V> oldRoot = root.get();
PathBuffer<K, V> pb = getPathBuffer();
pb.setRoot(oldRoot);
Node<K, V> node = findNode(key, pb, comparator);
if (node == null) {
return null;
}
if (value != null && !value.equals(node.value)) {
return null;