Debian Codegraph @

src/main/org/h2/mvstore/MVMap.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.mvstore;
7
8 import static org.h2.engine.Constants.MEMORY_POINTER;
9
10 import java.util.AbstractList;
11 import java.util.AbstractMap;
12 import java.util.AbstractSet;
13 import java.util.Arrays;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Set;
18 import java.util.concurrent.ConcurrentMap;
19 import java.util.concurrent.atomic.AtomicLong;
20 import java.util.concurrent.atomic.AtomicReference;
21
22 import org.h2.mvstore.type.DataType;
23 import org.h2.mvstore.type.ObjectDataType;
24 import org.h2.util.MemoryEstimator;
25
26 /**
27 * A stored map.
28 * <p>
29 * All read and write operations can happen concurrently with all other
30 * operations, without risk of corruption.
31 *
32 * @param <K> the key class
33 * @param <V> the value class
34 */
35 public class MVMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> {
36
37 /**
38 * The store.
39 */
40 public final MVStore store;
41
42 /**
43 * Reference to the current root page.
44 */
45 private final AtomicReference<RootReference<K,V>> root;
46
47 private final int id;
48 private final long createVersion;
49 private final DataType<K> keyType;
50 private final DataType<V> valueType;
51 private final int keysPerPage;
52 private final boolean singleWriter;
53 private final K[] keysBuffer;
54 private final V[] valuesBuffer;
55
56 private final Object lock = new Object();
57 private volatile boolean notificationRequested;
58
59 /**
60 * Whether the map is closed. Volatile so we don't accidentally write to a
61 * closed map in multithreaded mode.
62 */
63 private volatile boolean closed;
64 private boolean readOnly;
65 private boolean isVolatile;
66 private final AtomicLong avgKeySize;
67 private final AtomicLong avgValSize;
68
69 protected MVMap(Map<String, Object> config, DataType<K> keyType, DataType<V> valueType) {
70 this((MVStore) config.get("store"), keyType, valueType,
71 DataUtils.readHexInt(config, "id", 0),
72 DataUtils.readHexLong(config, "createVersion", 0),
73 new AtomicReference<>(),
74 ((MVStore) config.get("store")).getKeysPerPage(),
75 config.containsKey("singleWriter") && (Boolean) config.get("singleWriter")
76 );
77 setInitialRoot(createEmptyLeaf(), store.getCurrentVersion());
78 }
79
80 // constructor for cloneIt()
81 @SuppressWarnings("CopyConstructorMissesField")
82 protected MVMap(MVMap<K, V> source) {
83 this(source.store, source.keyType, source.valueType, source.id, source.createVersion,
84 new AtomicReference<>(source.root.get()), source.keysPerPage, source.singleWriter);
85 }
86
87 // meta map constructor
88 MVMap(MVStore store, int id, DataType<K> keyType, DataType<V> valueType) {
89 this(store, keyType, valueType, id, 0, new AtomicReference<>(), store.getKeysPerPage(), false);
90 setInitialRoot(createEmptyLeaf(), store.getCurrentVersion());
91 }
92
93 private MVMap(MVStore store, DataType<K> keyType, DataType<V> valueType, int id, long createVersion,
94 AtomicReference<RootReference<K,V>> root, int keysPerPage, boolean singleWriter) {
95 this.store = store;
96 this.id = id;
97 this.createVersion = createVersion;
98 this.keyType = keyType;
99 this.valueType = valueType;
100 this.root = root;
101 this.keysPerPage = keysPerPage;
102 this.keysBuffer = singleWriter ? keyType.createStorage(keysPerPage) : null;
103 this.valuesBuffer = singleWriter ? valueType.createStorage(keysPerPage) : null;
104 this.singleWriter = singleWriter;
105 this.avgKeySize = keyType.isMemoryEstimationAllowed() ? new AtomicLong() : null;
106 this.avgValSize = valueType.isMemoryEstimationAllowed() ? new AtomicLong() : null;
107
108 }
109
110 /**
111 * Clone the current map.
112 *
113 * @return clone of this.
114 */
115 protected MVMap<K, V> cloneIt() {
116 return new MVMap<>(this);
117 }
118
119 /**
120 * Get the metadata key for the root of the given map id.
121 *
122 * @param mapId the map id
123 * @return the metadata key
124 */
125 static String getMapRootKey(int mapId) {
126 return DataUtils.META_ROOT + Integer.toHexString(mapId);
127 }
128
129 /**
130 * Get the metadata key for the given map id.
131 *
132 * @param mapId the map id
133 * @return the metadata key
134 */
135 static String getMapKey(int mapId) {
136 return DataUtils.META_MAP + Integer.toHexString(mapId);
137 }
138
139 /**
140 * Add or replace a key-value pair.
141 *
142 * @param key the key (may not be null)
143 * @param value the value (may not be null)
144 * @return the old value if the key existed, or null otherwise
145 */
146 @Override
147 public V put(K key, V value) {
148 DataUtils.checkArgument(value != null, "The value may not be null");
149 return operate(key, value, DecisionMaker.PUT);
150 }
151
152 /**
153 * Get the first key, or null if the map is empty.
154 *
155 * @return the first key, or null
156 */
157 public final K firstKey() {
158 return getFirstLast(true);
159 }
160
161 /**
162 * Get the last key, or null if the map is empty.
163 *
164 * @return the last key, or null
165 */
166 public final K lastKey() {
167 return getFirstLast(false);
168 }
169
170 /**
171 * Get the key at the given index.
172 * <p>
173 * This is a O(log(size)) operation.
174 *
175 * @param index the index
176 * @return the key
177 */
178 public final K getKey(long index) {
179 if (index < 0 || index >= sizeAsLong()) {
180 return null;
181 }
182 Page<K,V> p = getRootPage();
183 long offset = 0;
184 while (true) {
185 if (p.isLeaf()) {
186 if (index >= offset + p.getKeyCount()) {
187 return null;
188 }
189 K key = p.getKey((int) (index - offset));
190 return key;
191 }
192 int i = 0, size = getChildPageCount(p);
193 for (; i < size; i++) {
194 long c = p.getCounts(i);
195 if (index < c + offset) {
196 break;
197 }
198 offset += c;
199 }
200 if (i == size) {
201 return null;
202 }
203 p = p.getChildPage(i);
204 }
205 }
206
207 /**
208 * Get the key list. The list is a read-only representation of all keys.
209 * <p>
210 * The get and indexOf methods are O(log(size)) operations. The result of
211 * indexOf is cast to an int.
212 *
213 * @return the key list
214 */
215 public final List<K> keyList() {
216 return new AbstractList<K>() {
217
218 @Override
219 public K get(int index) {
220 return getKey(index);
221 }
222
223 @Override
224 public int size() {
225 return MVMap.this.size();
226 }
227
228 @Override
229 @SuppressWarnings("unchecked")
230 public int indexOf(Object key) {
231 return (int) getKeyIndex((K) key);
232 }
233
234 };
235 }
236
237 /**
238 * Get the index of the given key in the map.
239 * <p>
240 * This is a O(log(size)) operation.
241 * <p>
242 * If the key was found, the returned value is the index in the key array.
243 * If not found, the returned value is negative, where -1 means the provided
244 * key is smaller than any keys. See also Arrays.binarySearch.
245 *
246 * @param key the key
247 * @return the index
248 */
249 public final long getKeyIndex(K key) {
250 Page<K,V> p = getRootPage();
251 if (p.getTotalCount() == 0) {
252 return -1;
253 }
254 long offset = 0;
255 while (true) {
256 int x = p.binarySearch(key);
257 if (p.isLeaf()) {
258 if (x < 0) {
259 offset = -offset;
260 }
261 return offset + x;
262 }
263 if (x++ < 0) {
264 x = -x;
265 }
266 for (int i = 0; i < x; i++) {
267 offset += p.getCounts(i);
268 }
269 p = p.getChildPage(x);
270 }
271 }
272
273 /**
274 * Get the first (lowest) or last (largest) key.
275 *
276 * @param first whether to retrieve the first key
277 * @return the key, or null if the map is empty
278 */
279 private K getFirstLast(boolean first) {
280 Page<K,V> p = getRootPage();
281 return getFirstLast(p, first);
282 }
283
284 private K getFirstLast(Page<K,V> p, boolean first) {
285 if (p.getTotalCount() == 0) {
286 return null;
287 }
288 while (true) {
289 if (p.isLeaf()) {
290 return p.getKey(first ? 0 : p.getKeyCount() - 1);
291 }
292 p = p.getChildPage(first ? 0 : getChildPageCount(p) - 1);
293 }
294 }
295
296 /**
297 * Get the smallest key that is larger than the given key (next key in ascending order),
298 * or null if no such key exists.
299 *
300 * @param key the key
301 * @return the result
302 */
303 public final K higherKey(K key) {
304 return getMinMax(key, false, true);
305 }
306
307 /**
308 * Get the smallest key that is larger than the given key, for the given
309 * root page, or null if no such key exists.
310 *
311 * @param rootRef the root reference of the map
312 * @param key to start from
313 * @return the result
314 */
315 public final K higherKey(RootReference<K,V> rootRef, K key) {
316 return getMinMax(rootRef, key, false, true);
317 }
318
319 /**
320 * Get the smallest key that is larger or equal to this key.
321 *
322 * @param key the key
323 * @return the result
324 */
325 public final K ceilingKey(K key) {
326 return getMinMax(key, false, false);
327 }
328
329 /**
330 * Get the largest key that is smaller or equal to this key.
331 *
332 * @param key the key
333 * @return the result
334 */
335 public final K floorKey(K key) {
336 return getMinMax(key, true, false);
337 }
338
339 /**
340 * Get the largest key that is smaller than the given key, or null if no
341 * such key exists.
342 *
343 * @param key the key
344 * @return the result
345 */
346 public final K lowerKey(K key) {
347 return getMinMax(key, true, true);
348 }
349
350 /**
351 * Get the largest key that is smaller than the given key, for the given
352 * root page, or null if no such key exists.
353 *
354 * @param rootRef the root page
355 * @param key the key
356 * @return the result
357 */
358 public final K lowerKey(RootReference<K, V> rootRef, K key) {
359 return getMinMax(rootRef, key, true, true);
360 }
361
362 /**
363 * Get the smallest or largest key using the given bounds.
364 *
365 * @param key the key
366 * @param min whether to retrieve the smallest key
367 * @param excluding if the given upper/lower bound is exclusive
368 * @return the key, or null if no such key exists
369 */
370 private K getMinMax(K key, boolean min, boolean excluding) {
371 return getMinMax(flushAndGetRoot(), key, min, excluding);
372 }
373
374 private K getMinMax(RootReference<K,V> rootRef, K key, boolean min, boolean excluding) {
375 return getMinMax(rootRef.root, key, min, excluding);
376 }
377
378 private K getMinMax(Page<K,V> p, K key, boolean min, boolean excluding) {
379 int x = p.binarySearch(key);
380 if (p.isLeaf()) {
381 if (x < 0) {
382 x = -x - (min ? 2 : 1);
383 } else if (excluding) {
384 x += min ? -1 : 1;
385 }
386 if (x < 0 || x >= p.getKeyCount()) {
387 return null;
388 }
389 return p.getKey(x);
390 }
391 if (x++ < 0) {
392 x = -x;
393 }
394 while (true) {
395 if (x < 0 || x >= getChildPageCount(p)) {
396 return null;
397 }
398 K k = getMinMax(p.getChildPage(x), key, min, excluding);
399 if (k != null) {
400 return k;
401 }
402 x += min ? -1 : 1;
403 }
404 }
405
406
407 /**
408 * Get the value for the given key, or null if not found.
409 *
410 * @param key the key
411 * @return the value, or null if not found
412 * @throws ClassCastException if type of the specified key is not compatible with this map
413 */
414 @SuppressWarnings("unchecked")
415 @Override
416 public final V get(Object key) {
417 return get(getRootPage(), (K) key);
418 }
419
420 /**
421 * Get the value for the given key from a snapshot, or null if not found.
422 *
423 * @param p the root of a snapshot
424 * @param key the key
425 * @return the value, or null if not found
426 * @throws ClassCastException if type of the specified key is not compatible with this map
427 */
428 public V get(Page<K,V> p, K key) {
429 return Page.get(p, key);
430 }
431
432 @Override
433 public final boolean containsKey(Object key) {
434 return get(key) != null;
435 }
436
437 /**
438 * Remove all entries.
439 */
440 @Override
441 public void clear() {
442 clearIt();
443 }
444
445 /**
446 * Remove all entries and return the root reference.
447 *
448 * @return the new root reference
449 */
450 RootReference<K,V> clearIt() {
451 Page<K,V> emptyRootPage = createEmptyLeaf();
452 int attempt = 0;
453 while (true) {
454 RootReference<K,V> rootReference = flushAndGetRoot();
455 if (rootReference.getTotalCount() == 0) {
456 return rootReference;
457 }
458 boolean locked = rootReference.isLockedByCurrentThread();
459 if (!locked) {
460 if (attempt++ == 0) {
461 beforeWrite();
462 } else if (attempt > 3 || rootReference.isLocked()) {
463 rootReference = lockRoot(rootReference, attempt);
464 locked = true;
465 }
466 }
467 Page<K,V> rootPage = rootReference.root;
468 long version = rootReference.version;
469 try {
470 if (!locked) {
471 rootReference = rootReference.updateRootPage(emptyRootPage, attempt);
472 if (rootReference == null) {
473 continue;
474 }
475 }
476 if (isPersistent()) {
477 registerUnsavedMemory(rootPage.removeAllRecursive(version));
478 }
479 rootPage = emptyRootPage;
480 return rootReference;
481 } finally {
482 if(locked) {
483 unlockRoot(rootPage);
484 }
485 }
486 }
487 }
488
489 protected final void registerUnsavedMemory(int memory) {
490 if (isPersistent()) {
491 store.registerUnsavedMemory(memory);
492 }
493 }
494
495 /**
496 * Close the map. Accessing the data is still possible (to allow concurrent
497 * reads), but it is marked as closed.
498 */
499 final void close() {
500 closed = true;
501 }
502
503 public final boolean isClosed() {
504 return closed;
505 }
506
507 /**
508 * Remove a key-value pair, if the key exists.
509 *
510 * @param key the key (may not be null)
511 * @return the old value if the key existed, or null otherwise
512 * @throws ClassCastException if type of the specified key is not compatible with this map
513 */
514 @Override
515 @SuppressWarnings("unchecked")
516 public V remove(Object key) {
517 return operate((K)key, null, DecisionMaker.REMOVE);
518 }
519
520 /**
521 * Add a key-value pair if it does not yet exist.
522 *
523 * @param key the key (may not be null)
524 * @param value the new value
525 * @return the old value if the key existed, or null otherwise
526 */
527 @Override
528 public final V putIfAbsent(K key, V value) {
529 return operate(key, value, DecisionMaker.IF_ABSENT);
530 }
531
532 /**
533 * Remove a key-value pair if the value matches the stored one.
534 *
535 * @param key the key (may not be null)
536 * @param value the expected value
537 * @return true if the item was removed
538 */
539 @SuppressWarnings("unchecked")
540 @Override
541 public boolean remove(Object key, Object value) {
542 EqualsDecisionMaker<V> decisionMaker = new EqualsDecisionMaker<>(valueType, (V)value);
543 operate((K)key, null, decisionMaker);
544 return decisionMaker.getDecision() != Decision.ABORT;
545 }
546
547 /**
548 * Check whether the two values are equal.
549 *
550 * @param <X> type of values to compare
551 *
552 * @param a the first value
553 * @param b the second value
554 * @param datatype to use for comparison
555 * @return true if they are equal
556 */
557 static <X> boolean areValuesEqual(DataType<X> datatype, X a, X b) {
558 return a == b
559 || a != null && b != null && datatype.compare(a, b) == 0;
560 }
561
562 /**
563 * Replace a value for an existing key, if the value matches.
564 *
565 * @param key the key (may not be null)
566 * @param oldValue the expected value
567 * @param newValue the new value
568 * @return true if the value was replaced
569 */
570 @Override
571 public final boolean replace(K key, V oldValue, V newValue) {
572 EqualsDecisionMaker<V> decisionMaker = new EqualsDecisionMaker<>(valueType, oldValue);
573 V result = operate(key, newValue, decisionMaker);
574 boolean res = decisionMaker.getDecision() != Decision.ABORT;
575 assert !res || areValuesEqual(valueType, oldValue, result) : oldValue + " != " + result;
576 return res;
577 }
578
579 /**
580 * Replace a value for an existing key.
581 *
582 * @param key the key (may not be null)
583 * @param value the new value
584 * @return the old value, if the value was replaced, or null
585 */
586 @Override
587 public final V replace(K key, V value) {
588 return operate(key, value, DecisionMaker.IF_PRESENT);
589 }
590
591 /**
592 * Compare two keys.
593 *
594 * @param a the first key
595 * @param b the second key
596 * @return -1 if the first key is smaller, 1 if bigger, 0 if equal
597 */
598 @SuppressWarnings("unused")
599 final int compare(K a, K b) {
600 return keyType.compare(a, b);
601 }
602
603 /**
604 * Get the key type.
605 *
606 * @return the key type
607 */
608 public final DataType<K> getKeyType() {
609 return keyType;
610 }
611
612 /**
613 * Get the value type.
614 *
615 * @return the value type
616 */
617 public final DataType<V> getValueType() {
618 return valueType;
619 }
620
621 boolean isSingleWriter() {
622 return singleWriter;
623 }
624
625 /**
626 * Read a page.
627 *
628 * @param pos the position of the page
629 * @return the page
630 */
631 final Page<K,V> readPage(long pos) {
632 return store.readPage(this, pos);
633 }
634
635 /**
636 * Set the position of the root page.
637 * @param rootPos the position, 0 for empty
638 * @param version to set for this map
639 *
640 */
641 final void setRootPos(long rootPos, long version) {
642 Page<K,V> root = readOrCreateRootPage(rootPos);
643 if (root.map != this) {
644 // this can only happen on concurrent opening of existing map,
645 // when second thread picks up some cached page already owned by
646 // the first map's instantiation (both maps share the same id)
647 assert id == root.map.id;
648 // since it is unknown which one will win the race,
649 // let each map instance to have it's own copy
650 root = root.copy(this, false);
651 }
652 setInitialRoot(root, version - 1);
653 setWriteVersion(version);
654 }
655
656 private Page<K,V> readOrCreateRootPage(long rootPos) {
657 Page<K,V> root = rootPos == 0 ? createEmptyLeaf() : readPage(rootPos);
658 return root;
659 }
660
661 /**
662 * Iterate over a number of keys.
663 *
664 * @param from the first key to return
665 * @return the iterator
666 */
667 public final Iterator<K> keyIterator(K from) {
668 return cursor(from, null, false);
669 }
670
671 /**
672 * Iterate over a number of keys in reverse order
673 *
674 * @param from the first key to return
675 * @return the iterator
676 */
677 public final Iterator<K> keyIteratorReverse(K from) {
678 return cursor(from, null, true);
679 }
680
681 final boolean rewritePage(long pagePos) {
682 Page<K, V> p = readPage(pagePos);
683 if (p.getKeyCount()==0) {
684 return true;
685 }
686 assert p.isSaved();
687 K key = p.getKey(0);
688 if (!isClosed()) {
689 RewriteDecisionMaker<V> decisionMaker = new RewriteDecisionMaker<>(p.getPos());
690 V result = operate(key, null, decisionMaker);
691 boolean res = decisionMaker.getDecision() != Decision.ABORT;
692 assert !res || result != null;
693 return res;
694 }
695 return false;
696 }
697
698 /**
699 * Get a cursor to iterate over a number of keys and values in the latest version of this map.
700 *
701 * @param from the first key to return
702 * @return the cursor
703 */
704 public final Cursor<K, V> cursor(K from) {
705 return cursor(from, null, false);
706 }
707
708 /**
709 * Get a cursor to iterate over a number of keys and values in the latest version of this map.
710 *
711 * @param from the first key to return
712 * @param to the last key to return
713 * @param reverse if true, iterate in reverse (descending) order
714 * @return the cursor
715 */
716 public final Cursor<K, V> cursor(K from, K to, boolean reverse) {
717 return cursor(flushAndGetRoot(), from, to, reverse);
718 }
719
720 /**
721 * Get a cursor to iterate over a number of keys and values.
722 *
723 * @param rootReference of this map's version to iterate over
724 * @param from the first key to return
725 * @param to the last key to return
726 * @param reverse if true, iterate in reverse (descending) order
727 * @return the cursor
728 */
729 public Cursor<K, V> cursor(RootReference<K,V> rootReference, K from, K to, boolean reverse) {
730 return new Cursor<>(rootReference, from, to, reverse);
731 }
732
733 @Override
734 public final Set<Map.Entry<K, V>> entrySet() {
735 final RootReference<K,V> rootReference = flushAndGetRoot();
736 return new AbstractSet<Entry<K, V>>() {
737
738 @Override
739 public Iterator<Entry<K, V>> iterator() {
740 final Cursor<K, V> cursor = cursor(rootReference, null, null, false);
741 return new Iterator<Entry<K, V>>() {
742
743 @Override
744 public boolean hasNext() {
745 return cursor.hasNext();
746 }
747
748 @Override
749 public Entry<K, V> next() {
750 K k = cursor.next();
751 return new SimpleImmutableEntry<>(k, cursor.getValue());
752 }
753 };
754
755 }
756
757 @Override
758 public int size() {
759 return MVMap.this.size();
760 }
761
762 @Override
763 public boolean contains(Object o) {
764 return MVMap.this.containsKey(o);
765 }
766
767 };
768
769 }
770
771 @Override
772 public Set<K> keySet() {
773 final RootReference<K,V> rootReference = flushAndGetRoot();
774 return new AbstractSet<K>() {
775
776 @Override
777 public Iterator<K> iterator() {
778 return cursor(rootReference, null, null, false);
779 }
780
781 @Override
782 public int size() {
783 return MVMap.this.size();
784 }
785
786 @Override
787 public boolean contains(Object o) {
788 return MVMap.this.containsKey(o);
789 }
790
791 };
792 }
793
794 /**
795 * Get the map name.
796 *
797 * @return the name
798 */
799 public final String getName() {
800 return store.getMapName(id);
801 }
802
803 public final MVStore getStore() {
804 return store;
805 }
806
807 protected final boolean isPersistent() {
808 return store.isPersistent() && !isVolatile;
809 }
810
811 /**
812 * Get the map id. Please note the map id may be different after compacting
813 * a store.
814 *
815 * @return the map id
816 */
817 public final int getId() {
818 return id;
819 }
820
821 /**
822 * The current root page (may not be null).
823 *
824 * @return the root page
825 */
826 public final Page<K,V> getRootPage() {
827 return flushAndGetRoot().root;
828 }
829
830 public RootReference<K,V> getRoot() {
831 return root.get();
832 }
833
834 /**
835 * Get the root reference, flushing any current append buffer.
836 *
837 * @return current root reference
838 */
839 public RootReference<K,V> flushAndGetRoot() {
840 RootReference<K,V> rootReference = getRoot();
841 if (singleWriter && rootReference.getAppendCounter() > 0) {
842 return flushAppendBuffer(rootReference, true);
843 }
844 return rootReference;
845 }
846
847 /**
848 * Set the initial root.
849 *
850 * @param rootPage root page
851 * @param version initial version
852 */
853 final void setInitialRoot(Page<K,V> rootPage, long version) {
854 root.set(new RootReference<>(rootPage, version));
855 }
856
857 /**
858 * Compare and set the root reference.
859 *
860 * @param expectedRootReference the old (expected)
861 * @param updatedRootReference the new
862 * @return whether updating worked
863 */
864 final boolean compareAndSetRoot(RootReference<K,V> expectedRootReference,
865 RootReference<K,V> updatedRootReference) {
866 return root.compareAndSet(expectedRootReference, updatedRootReference);
867 }
868
869 /**
870 * Rollback to the given version.
871 *
872 * @param version the version
873 */
874 final void rollbackTo(long version) {
875 // check if the map was removed and re-created later ?
876 if (version > createVersion) {
877 rollbackRoot(version);
878 }
879 }
880
881 /**
882 * Roll the root back to the specified version.
883 *
884 * @param version to rollback to
885 * @return true if rollback was a success, false if there was not enough in-memory history
886 */
887 boolean rollbackRoot(long version) {
888 RootReference<K,V> rootReference = flushAndGetRoot();
889 RootReference<K,V> previous;
890 while (rootReference.version >= version && (previous = rootReference.previous) != null) {
891 if (root.compareAndSet(rootReference, previous)) {
892 rootReference = previous;
893 closed = false;
894 }
895 }
896 setWriteVersion(version);
897 return rootReference.version < version;
898 }
899
900 /**
901 * Use the new root page from now on.
902 *
903 * @param <K> the key class
904 * @param <V> the value class
905 * @param expectedRootReference expected current root reference
906 * @param newRootPage the new root page
907 * @param attemptUpdateCounter how many attempt (including current)
908 * were made to update root
909 * @return new RootReference or null if update failed
910 */
911 protected static <K,V> boolean updateRoot(RootReference<K,V> expectedRootReference, Page<K,V> newRootPage,
912 int attemptUpdateCounter) {
913 return expectedRootReference.updateRootPage(newRootPage, attemptUpdateCounter) != null;
914 }
915
916 /**
917 * Forget those old versions that are no longer needed.
918 * @param rootReference to inspect
919 */
920 private void removeUnusedOldVersions(RootReference<K,V> rootReference) {
921 rootReference.removeUnusedOldVersions(store.getOldestVersionToKeep());
922 }
923
924 public final boolean isReadOnly() {
925 return readOnly;
926 }
927
928 /**
929 * Set the volatile flag of the map.
930 *
931 * @param isVolatile the volatile flag
932 */
933 public final void setVolatile(boolean isVolatile) {
934 this.isVolatile = isVolatile;
935 }
936
937 /**
938 * Whether this is volatile map, meaning that changes
939 * are not persisted. By default (even if the store is not persisted),
940 * maps are not volatile.
941 *
942 * @return whether this map is volatile
943 */
944 public final boolean isVolatile() {
945 return isVolatile;
946 }
947
948 /**
949 * This method is called before writing to the map. The default
950 * implementation checks whether writing is allowed, and tries
951 * to detect concurrent modification.
952 *
953 * @throws UnsupportedOperationException if the map is read-only,
954 * or if another thread is concurrently writing
955 */
956 protected final void beforeWrite() {
957 assert !getRoot().isLockedByCurrentThread() : getRoot();
958 if (closed) {
959 int id = getId();
960 String mapName = store.getMapName(id);
961 throw DataUtils.newMVStoreException(
962 DataUtils.ERROR_CLOSED, "Map {0}({1}) is closed. {2}", mapName, id, store.getPanicException());
963 }
964 if (readOnly) {
965 throw DataUtils.newUnsupportedOperationException(
966 "This map is read-only");
967 }
968 store.beforeWrite(this);
969 }
970
971 @Override
972 public final int hashCode() {
973 return id;
974 }
975
976 @Override
977 public final boolean equals(Object o) {
978 return this == o;
979 }
980
981 /**
982 * Get the number of entries, as a integer. {@link Integer#MAX_VALUE} is
983 * returned if there are more than this entries.
984 *
985 * @return the number of entries, as an integer
986 * @see #sizeAsLong()
987 */
988 @Override
989 public final int size() {
990 long size = sizeAsLong();
991 return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size;
992 }
993
994 /**
995 * Get the number of entries, as a long.
996 *
997 * @return the number of entries
998 */
999 public final long sizeAsLong() {
1000 return getRoot().getTotalCount();
1001 }
1002
1003 @Override
1004 public boolean isEmpty() {
1005 return sizeAsLong() == 0;
1006 }
1007
1008 final long getCreateVersion() {
1009 return createVersion;
1010 }
1011
1012 /**
1013 * Open an old version for the given map.
1014 * It will restore map at last known state of the version specified.
1015 * (at the point right before the commit() call, which advanced map to the next version)
1016 * Map is opened in read-only mode.
1017 *
1018 * @param version the version
1019 * @return the map
1020 */
1021 public final MVMap<K, V> openVersion(long version) {
1022 if (readOnly) {
1023 throw DataUtils.newUnsupportedOperationException(
1024 "This map is read-only; need to call " +
1025 "the method on the writable map");
1026 }
1027 DataUtils.checkArgument(version >= createVersion,
1028 "Unknown version {0}; this map was created in version is {1}",
1029 version, createVersion);
1030 RootReference<K,V> rootReference = flushAndGetRoot();
1031 removeUnusedOldVersions(rootReference);
1032 RootReference<K,V> previous;
1033 while ((previous = rootReference.previous) != null && previous.version >= version) {
1034 rootReference = previous;
1035 }
1036 if (previous == null && version < store.getOldestVersionToKeep()) {
1037 throw DataUtils.newIllegalArgumentException("Unknown version {0}", version);
1038 }
1039 MVMap<K, V> m = openReadOnly(rootReference.root, version);
1040 assert m.getVersion() <= version : m.getVersion() + " <= " + version;
1041 return m;
1042 }
1043
1044 /**
1045 * Open a copy of the map in read-only mode.
1046 *
1047 * @param rootPos position of the root page
1048 * @param version to open
1049 * @return the opened map
1050 */
1051 final MVMap<K, V> openReadOnly(long rootPos, long version) {
1052 Page<K,V> root = readOrCreateRootPage(rootPos);
1053 return openReadOnly(root, version);
1054 }
1055
1056 private MVMap<K, V> openReadOnly(Page<K,V> root, long version) {
1057 MVMap<K, V> m = cloneIt();
1058 m.readOnly = true;
1059 m.setInitialRoot(root, version);
1060 return m;
1061 }
1062
1063 /**
1064 * Get version of the map, which is the version of the store,
1065 * at the moment when map was modified last time.
1066 *
1067 * @return version
1068 */
1069 public final long getVersion() {
1070 return getRoot().getVersion();
1071 }
1072
1073 /**
1074 * Does the root have changes since the specified version?
1075 *
1076 * @param version root version
1077 * @return true if has changes
1078 */
1079 final boolean hasChangesSince(long version) {
1080 return getRoot().hasChangesSince(version, isPersistent());
1081 }
1082
1083 /**
1084 * Get the child page count for this page. This is to allow another map
1085 * implementation to override the default, in case the last child is not to
1086 * be used.
1087 *
1088 * @param p the page
1089 * @return the number of direct children
1090 */
1091 protected int getChildPageCount(Page<K,V> p) {
1092 return p.getRawChildPageCount();
1093 }
1094
1095 /**
1096 * Get the map type. When opening an existing map, the map type must match.
1097 *
1098 * @return the map type
1099 */
1100 public String getType() {
1101 return null;
1102 }
1103
1104 /**
1105 * Get the map metadata as a string.
1106 *
1107 * @param name the map name (or null)
1108 * @return the string
1109 */
1110 protected String asString(String name) {
1111 StringBuilder buff = new StringBuilder();
1112 if (name != null) {
1113 DataUtils.appendMap(buff, "name", name);
1114 }
1115 if (createVersion != 0) {
1116 DataUtils.appendMap(buff, "createVersion", createVersion);
1117 }
1118 String type = getType();
1119 if (type != null) {
1120 DataUtils.appendMap(buff, "type", type);
1121 }
1122 return buff.toString();
1123 }
1124
1125 final RootReference<K,V> setWriteVersion(long writeVersion) {
1126 int attempt = 0;
1127 while(true) {
1128 RootReference<K,V> rootReference = flushAndGetRoot();
1129 if(rootReference.version >= writeVersion) {
1130 return rootReference;
1131 } else if (isClosed()) {
1132 // map was closed a while back and can not possibly be in use by now
1133 // it's time to remove it completely from the store (it was anonymous already)
1134 if (rootReference.getVersion() + 1 < store.getOldestVersionToKeep()) {
1135 store.deregisterMapRoot(id);
1136 return null;
1137 }
1138 }
1139
1140 RootReference<K,V> lockedRootReference = null;
1141 if (++attempt > 3 || rootReference.isLocked()) {
1142 lockedRootReference = lockRoot(rootReference, attempt);
1143 rootReference = flushAndGetRoot();
1144 }
1145
1146 try {
1147 rootReference = rootReference.tryUnlockAndUpdateVersion(writeVersion, attempt);
1148 if (rootReference != null) {
1149 lockedRootReference = null;
1150 removeUnusedOldVersions(rootReference);
1151 return rootReference;
1152 }
1153 } finally {
1154 if (lockedRootReference != null) {
1155 unlockRoot();
1156 }
1157 }
1158 }
1159 }
1160
1161 /**
1162 * Create empty leaf node page.
1163 *
1164 * @return new page
1165 */
1166 protected Page<K,V> createEmptyLeaf() {
1167 return Page.createEmptyLeaf(this);
1168 }
1169
1170 /**
1171 * Create empty internal node page.
1172 *
1173 * @return new page
1174 */
1175 protected Page<K,V> createEmptyNode() {
1176 return Page.createEmptyNode(this);
1177 }
1178
1179 /**
1180 * Copy a map. All pages are copied.
1181 *
1182 * @param sourceMap the source map
1183 */
1184 final void copyFrom(MVMap<K, V> sourceMap) {
1185 MVStore.TxCounter txCounter = store.registerVersionUsage();
1186 try {
1187 beforeWrite();
1188 copy(sourceMap.getRootPage(), null, 0);
1189 } finally {
1190 store.deregisterVersionUsage(txCounter);
1191 }
1192 }
1193
1194 private void copy(Page<K,V> source, Page<K,V> parent, int index) {
1195 Page<K,V> target = source.copy(this, true);
1196 if (parent == null) {
1197 setInitialRoot(target, MVStore.INITIAL_VERSION);
1198 } else {
1199 parent.setChild(index, target);
1200 }
1201 if (!source.isLeaf()) {
1202 for (int i = 0; i < getChildPageCount(target); i++) {
1203 if (source.getChildPagePos(i) != 0) {
1204 // position 0 means no child
1205 // (for example the last entry of an r-tree node)
1206 // (the MVMap is also used for r-trees for compacting)
1207 copy(source.getChildPage(i), target, i);
1208 }
1209 }
1210 target.setComplete();
1211 }
1212 store.registerUnsavedMemoryAndCommitIfNeeded(target.getMemory());
1213 }
1214
1215 /**
1216 * If map was used in append mode, this method will ensure that append buffer
1217 * is flushed - emptied with all entries inserted into map as a new leaf.
1218 * @param rootReference current RootReference
1219 * @param fullFlush whether buffer should be completely flushed,
1220 * otherwise just a single empty slot is required
1221 * @return potentially updated RootReference
1222 */
1223 private RootReference<K,V> flushAppendBuffer(RootReference<K,V> rootReference, boolean fullFlush) {
1224 boolean preLocked = rootReference.isLockedByCurrentThread();
1225 boolean locked = preLocked;
1226 int keysPerPage = store.getKeysPerPage();
1227 try {
1228 IntValueHolder unsavedMemoryHolder = new IntValueHolder();
1229 int attempt = 0;
1230 int keyCount;
1231 int availabilityThreshold = fullFlush ? 0 : keysPerPage - 1;
1232 while ((keyCount = rootReference.getAppendCounter()) > availabilityThreshold) {
1233 if (!locked) {
1234 // instead of just calling lockRoot() we loop here and check if someone else
1235 // already flushed the buffer, then we don't need a lock
1236 rootReference = tryLock(rootReference, ++attempt);
1237 if (rootReference == null) {
1238 rootReference = getRoot();
1239 continue;
1240 }
1241 locked = true;
1242 }
1243
1244 Page<K,V> rootPage = rootReference.root;
1245 long version = rootReference.version;
1246 CursorPos<K,V> pos = rootPage.getAppendCursorPos(null);
1247 assert pos != null;
1248 assert pos.index < 0 : pos.index;
1249 int index = -pos.index - 1;
1250 assert index == pos.page.getKeyCount() : index + " != " + pos.page.getKeyCount();
1251 Page<K,V> p = pos.page;
1252 CursorPos<K,V> tip = pos;
1253 pos = pos.parent;
1254
1255 int remainingBuffer = 0;
1256 Page<K,V> page = null;
1257 int available = keysPerPage - p.getKeyCount();
1258 if (available > 0) {
1259 p = p.copy();
1260 if (keyCount <= available) {
1261 p.expand(keyCount, keysBuffer, valuesBuffer);
1262 } else {
1263 p.expand(available, keysBuffer, valuesBuffer);
1264 keyCount -= available;
1265 if (fullFlush) {
1266 K[] keys = p.createKeyStorage(keyCount);
1267 V[] values = p.createValueStorage(keyCount);
1268 System.arraycopy(keysBuffer, available, keys, 0, keyCount);
1269 if (valuesBuffer != null) {
1270 System.arraycopy(valuesBuffer, available, values, 0, keyCount);
1271 }
1272 page = Page.createLeaf(this, keys, values, 0);
1273 } else {
1274 System.arraycopy(keysBuffer, available, keysBuffer, 0, keyCount);
1275 if (valuesBuffer != null) {
1276 System.arraycopy(valuesBuffer, available, valuesBuffer, 0, keyCount);
1277 }
1278 remainingBuffer = keyCount;
1279 }
1280 }
1281 } else {
1282 tip = tip.parent;
1283 page = Page.createLeaf(this,
1284 Arrays.copyOf(keysBuffer, keyCount),
1285 valuesBuffer == null ? null : Arrays.copyOf(valuesBuffer, keyCount),
1286 0);
1287 }
1288
1289 unsavedMemoryHolder.value = 0;
1290 if (page != null) {
1291 assert page.map == this;
1292 assert page.getKeyCount() > 0;
1293 K key = page.getKey(0);
1294 unsavedMemoryHolder.value += page.getMemory();
1295 while (true) {
1296 if (pos == null) {
1297 if (p.getKeyCount() == 0) {
1298 p = page;
1299 } else {
1300 K[] keys = p.createKeyStorage(1);
1301 keys[0] = key;
1302 Page.PageReference<K,V>[] children = Page.createRefStorage(2);
1303 children[0] = new Page.PageReference<>(p);
1304 children[1] = new Page.PageReference<>(page);
1305 unsavedMemoryHolder.value += p.getMemory();
1306 p = Page.createNode(this, keys, children, p.getTotalCount() + page.getTotalCount(), 0);
1307 }
1308 break;
1309 }
1310 Page<K,V> c = p;
1311 p = pos.page;
1312 index = pos.index;
1313 pos = pos.parent;
1314 p = p.copy();
1315 p.setChild(index, page);
1316 p.insertNode(index, key, c);
1317 keyCount = p.getKeyCount();
1318 int at = keyCount - (p.isLeaf() ? 1 : 2);
1319 if (keyCount <= keysPerPage &&
1320 (p.getMemory() < store.getMaxPageSize() || at <= 0)) {
1321 break;
1322 }
1323 key = p.getKey(at);
1324 page = p.split(at);
1325 unsavedMemoryHolder.value += p.getMemory() + page.getMemory();
1326 }
1327 }
1328 p = replacePage(pos, p, unsavedMemoryHolder);
1329 rootReference = rootReference.updatePageAndLockedStatus(p, preLocked || isPersistent(),
1330 remainingBuffer);
1331 if (rootReference != null) {
1332 // should always be the case, except for spurious failure?
1333 locked = preLocked || isPersistent();
1334 if (isPersistent() && tip != null) {
1335 registerUnsavedMemory(unsavedMemoryHolder.value + tip.processRemovalInfo(version));
1336 }
1337 assert rootReference.getAppendCounter() <= availabilityThreshold;
1338 break;
1339 }
1340 rootReference = getRoot();
1341 }
1342 } finally {
1343 if (locked && !preLocked) {
1344 rootReference = unlockRoot();
1345 }
1346 }
1347 return rootReference;
1348 }
1349
1350 private static <K,V> Page<K,V> replacePage(CursorPos<K,V> path, Page<K,V> replacement,
1351 IntValueHolder unsavedMemoryHolder) {
1352 int unsavedMemory = replacement.isSaved() ? 0 : replacement.getMemory();
1353 while (path != null) {
1354 Page<K,V> parent = path.page;
1355 // condition below should always be true, but older versions (up to 1.4.197)
1356 // may create single-childed (with no keys) internal nodes, which we skip here
1357 if (parent.getKeyCount() > 0) {
1358 Page<K,V> child = replacement;
1359 replacement = parent.copy();
1360 replacement.setChild(path.index, child);
1361 unsavedMemory += replacement.getMemory();
1362 }
1363 path = path.parent;
1364 }
1365 unsavedMemoryHolder.value += unsavedMemory;
1366 return replacement;
1367 }
1368
1369 /**
1370 * Appends entry to this map. this method is NOT thread safe and can not be used
1371 * neither concurrently, nor in combination with any method that updates this map.
1372 * Non-updating method may be used concurrently, but latest appended values
1373 * are not guaranteed to be visible.
1374 * @param key should be higher in map's order than any existing key
1375 * @param value to be appended
1376 */
1377 public void append(K key, V value) {
1378 if (singleWriter) {
1379 beforeWrite();
1380 RootReference<K,V> rootReference = lockRoot(getRoot(), 1);
1381 int appendCounter = rootReference.getAppendCounter();
1382 try {
1383 if (appendCounter >= keysPerPage) {
1384 rootReference = flushAppendBuffer(rootReference, false);
1385 appendCounter = rootReference.getAppendCounter();
1386 assert appendCounter < keysPerPage;
1387 }
1388 keysBuffer[appendCounter] = key;
1389 if (valuesBuffer != null) {
1390 valuesBuffer[appendCounter] = value;
1391 }
1392 ++appendCounter;
1393 } finally {
1394 unlockRoot(appendCounter);
1395 }
1396 } else {
1397 put(key, value);
1398 }
1399 }
1400
1401 /**
1402 * Removes last entry from this map. this method is NOT thread safe and can not be used
1403 * neither concurrently, nor in combination with any method that updates this map.
1404 * Non-updating method may be used concurrently, but latest removal may not be visible.
1405 */
1406 public void trimLast() {
1407 if (singleWriter) {
1408 RootReference<K,V> rootReference = getRoot();
1409 int appendCounter = rootReference.getAppendCounter();
1410 boolean useRegularRemove = appendCounter == 0;
1411 if (!useRegularRemove) {
1412 rootReference = lockRoot(rootReference, 1);
1413 try {
1414 appendCounter = rootReference.getAppendCounter();
1415 useRegularRemove = appendCounter == 0;
1416 if (!useRegularRemove) {
1417 --appendCounter;
1418 }
1419 } finally {
1420 unlockRoot(appendCounter);
1421 }
1422 }
1423 if (useRegularRemove) {
1424 Page<K,V> lastLeaf = rootReference.root.getAppendCursorPos(null).page;
1425 assert lastLeaf.isLeaf();
1426 assert lastLeaf.getKeyCount() > 0;
1427 Object key = lastLeaf.getKey(lastLeaf.getKeyCount() - 1);
1428 remove(key);
1429 }
1430 } else {
1431 remove(lastKey());
1432 }
1433 }
1434
1435 @Override
1436 public final String toString() {
1437 return asString(null);
1438 }
1439
1440 /**
1441 * A builder for maps.
1442 *
1443 * @param <M> the map type
1444 * @param <K> the key type
1445 * @param <V> the value type
1446 */
1447 public interface MapBuilder<M extends MVMap<K, V>, K, V> {
1448
1449 /**
1450 * Create a new map of the given type.
1451 * @param store which will own this map
1452 * @param config configuration
1453 *
1454 * @return the map
1455 */
1456 M create(MVStore store, Map<String, Object> config);
1457
1458 DataType<K> getKeyType();
1459
1460 DataType<V> getValueType();
1461
1462 void setKeyType(DataType<? super K> dataType);
1463
1464 void setValueType(DataType<? super V> dataType);
1465
1466 }
1467
1468 /**
1469 * A builder for this class.
1470 *
1471 * @param <K> the key type
1472 * @param <V> the value type
1473 */
1474 public abstract static class BasicBuilder<M extends MVMap<K, V>, K, V> implements MapBuilder<M, K, V> {
1475
1476 private DataType<K> keyType;
1477 private DataType<V> valueType;
1478
1479 /**
1480 * Create a new builder with the default key and value data types.
1481 */
1482 protected BasicBuilder() {
1483 // ignore
1484 }
1485
1486 @Override
1487 public DataType<K> getKeyType() {
1488 return keyType;
1489 }
1490
1491 @Override
1492 public DataType<V> getValueType() {
1493 return valueType;
1494 }
1495
1496 @SuppressWarnings("unchecked")
1497 @Override
1498 public void setKeyType(DataType<? super K> keyType) {
1499 this.keyType = (DataType<K>)keyType;
1500 }
1501
1502 @SuppressWarnings("unchecked")
1503 @Override
1504 public void setValueType(DataType<? super V> valueType) {
1505 this.valueType = (DataType<V>)valueType;
1506 }
1507
1508 /**
1509 * Set the key data type.
1510 *
1511 * @param keyType the key type
1512 * @return this
1513 */
1514 public BasicBuilder<M, K, V> keyType(DataType<? super K> keyType) {
1515 setKeyType(keyType);
1516 return this;
1517 }
1518
1519 /**
1520 * Set the value data type.
1521 *
1522 * @param valueType the value type
1523 * @return this
1524 */
1525 public BasicBuilder<M, K, V> valueType(DataType<? super V> valueType) {
1526 setValueType(valueType);
1527 return this;
1528 }
1529
1530 @Override
1531 public M create(MVStore store, Map<String, Object> config) {
1532 if (getKeyType() == null) {
1533 setKeyType(new ObjectDataType());
1534 }
1535 if (getValueType() == null) {
1536 setValueType(new ObjectDataType());
1537 }
1538 DataType<K> keyType = getKeyType();
1539 DataType<V> valueType = getValueType();
1540 config.put("store", store);
1541 config.put("key", keyType);
1542 config.put("val", valueType);
1543 return create(config);
1544 }
1545
1546 /**
1547 * Create map from config.
1548 * @param config config map
1549 * @return new map
1550 */
1551 protected abstract M create(Map<String, Object> config);
1552
1553 }
1554
1555 /**
1556 * A builder for this class.
1557 *
1558 * @param <K> the key type
1559 * @param <V> the value type
1560 */
1561 public static class Builder<K, V> extends BasicBuilder<MVMap<K, V>, K, V> {
1562 private boolean singleWriter;
1563
1564 public Builder() {}
1565
1566 @Override
1567 public Builder<K,V> keyType(DataType<? super K> dataType) {
1568 setKeyType(dataType);
1569 return this;
1570 }
1571
1572 @Override
1573 public Builder<K, V> valueType(DataType<? super V> dataType) {
1574 setValueType(dataType);
1575 return this;
1576 }
1577
1578 /**
1579 * Set up this Builder to produce MVMap, which can be used in append mode
1580 * by a single thread.
1581 * @see MVMap#append(Object, Object)
1582 * @return this Builder for chained execution
1583 */
1584 public Builder<K,V> singleWriter() {
1585 singleWriter = true;
1586 return this;
1587 }
1588
1589 @Override
1590 protected MVMap<K, V> create(Map<String, Object> config) {
1591 config.put("singleWriter", singleWriter);
1592 Object type = config.get("type");
1593 if(type == null || type.equals("rtree")) {
1594 return new MVMap<>(config, getKeyType(), getValueType());
1595 }
1596 throw new IllegalArgumentException("Incompatible map type");
1597 }
1598 }
1599
1600 /**
1601 * The decision on what to do on an update.
1602 */
1603 public enum Decision { ABORT, REMOVE, PUT, REPEAT }
1604
1605 /**
1606 * Class DecisionMaker provides callback interface (and should become a such in Java 8)
1607 * for MVMap.operate method.
1608 * It provides control logic to make a decision about how to proceed with update
1609 * at the point in execution when proper place and possible existing value
1610 * for insert/update/delete key is found.
1611 * Revised value for insert/update is also provided based on original input value
1612 * and value currently existing in the map.
1613 *
1614 * @param <V> value type of the map
1615 */
1616 public abstract static class DecisionMaker<V> {
1617 /**
1618 * Decision maker for transaction rollback.
1619 */
1620 public static final DecisionMaker<Object> DEFAULT = new DecisionMaker<Object>() {
1621 @Override
1622 public Decision decide(Object existingValue, Object providedValue) {
1623 return providedValue == null ? Decision.REMOVE : Decision.PUT;
1624 }
1625
1626 @Override
1627 public String toString() {
1628 return "default";
1629 }
1630 };
1631
1632 /**
1633 * Decision maker for put().
1634 */
1635 public static final DecisionMaker<Object> PUT = new DecisionMaker<Object>() {
1636 @Override
1637 public Decision decide(Object existingValue, Object providedValue) {
1638 return Decision.PUT;
1639 }
1640
1641 @Override
1642 public String toString() {
1643 return "put";
1644 }
1645 };
1646
1647 /**
1648 * Decision maker for remove().
1649 */
1650 public static final DecisionMaker<Object> REMOVE = new DecisionMaker<Object>() {
1651 @Override
1652 public Decision decide(Object existingValue, Object providedValue) {
1653 return Decision.REMOVE;
1654 }
1655
1656 @Override
1657 public String toString() {
1658 return "remove";
1659 }
1660 };
1661
1662 /**
1663 * Decision maker for putIfAbsent() key/value.
1664 */
1665 static final DecisionMaker<Object> IF_ABSENT = new DecisionMaker<Object>() {
1666 @Override
1667 public Decision decide(Object existingValue, Object providedValue) {
1668 return existingValue == null ? Decision.PUT : Decision.ABORT;
1669 }
1670
1671 @Override
1672 public String toString() {
1673 return "if_absent";
1674 }
1675 };
1676
1677 /**
1678 * Decision maker for replace().
1679 */
1680 static final DecisionMaker<Object> IF_PRESENT= new DecisionMaker<Object>() {
1681 @Override
1682 public Decision decide(Object existingValue, Object providedValue) {
1683 return existingValue != null ? Decision.PUT : Decision.ABORT;
1684 }
1685
1686 @Override
1687 public String toString() {
1688 return "if_present";
1689 }
1690 };
1691
1692 /**
1693 * Makes a decision about how to proceed with the update.
1694 *
1695 * @param existingValue the old value
1696 * @param providedValue the new value
1697 * @param tip the cursor position
1698 * @return the decision
1699 */
1700 public Decision decide(V existingValue, V providedValue, CursorPos<?, ?> tip) {
1701 return decide(existingValue, providedValue);
1702 }
1703
1704 /**
1705 * Makes a decision about how to proceed with the update.
1706 * @param existingValue value currently exists in the map
1707 * @param providedValue original input value
1708 * @return PUT if a new value need to replace existing one or
1709 * a new value to be inserted if there is none
1710 * REMOVE if existing value should be deleted
1711 * ABORT if update operation should be aborted or repeated later
1712 * REPEAT if update operation should be repeated immediately
1713 */
1714 public abstract Decision decide(V existingValue, V providedValue);
1715
1716 /**
1717 * Provides revised value for insert/update based on original input value
1718 * and value currently existing in the map.
1719 * This method is only invoked after call to decide(), if it returns PUT.
1720 * @param existingValue value currently exists in the map
1721 * @param providedValue original input value
1722 * @param <T> value type
1723 * @return value to be used by insert/update
1724 */
1725 public <T extends V> T selectValue(T existingValue, T providedValue) {
1726 return providedValue;
1727 }
1728
1729 /**
1730 * Resets internal state (if any) of a this DecisionMaker to it's initial state.
1731 * This method is invoked whenever concurrent update failure is encountered,
1732 * so we can re-start update process.
1733 */
1734 public void reset() {}
1735 }
1736
1737 /**
1738 * Add, replace or remove a key-value pair.
1739 *
1740 * @param key the key (may not be null)
1741 * @param value new value, it may be null when removal is intended
1742 * @param decisionMaker command object to make choices during transaction.
1743 * @return previous value, if mapping for that key existed, or null otherwise
1744 */
1745 public V operate(K key, V value, DecisionMaker<? super V> decisionMaker) {
1746 IntValueHolder unsavedMemoryHolder = new IntValueHolder();
1747 int attempt = 0;
1748 while(true) {
1749 RootReference<K,V> rootReference = flushAndGetRoot();
1750 boolean locked = rootReference.isLockedByCurrentThread();
1751 if (!locked) {
1752 if (attempt++ == 0) {
1753 beforeWrite();
1754 }
1755 if (attempt > 3 || rootReference.isLocked()) {
1756 rootReference = lockRoot(rootReference, attempt);
1757 locked = true;
1758 }
1759 }
1760 Page<K,V> rootPage = rootReference.root;
1761 long version = rootReference.version;
1762 CursorPos<K,V> tip;
1763 V result;
1764 unsavedMemoryHolder.value = 0;
1765 try {
1766 CursorPos<K,V> pos = CursorPos.traverseDown(rootPage, key);
1767 if (!locked && rootReference != getRoot()) {
1768 continue;
1769 }
1770 Page<K,V> p = pos.page;
1771 int index = pos.index;
1772 tip = pos;
1773 pos = pos.parent;
1774 result = index < 0 ? null : p.getValue(index);
1775 Decision decision = decisionMaker.decide(result, value, tip);
1776
1777 switch (decision) {
1778 case REPEAT:
1779 decisionMaker.reset();
1780 continue;
1781 case ABORT:
1782 if (!locked && rootReference != getRoot()) {
1783 decisionMaker.reset();
1784 continue;
1785 }
1786 return result;
1787 case REMOVE: {
1788 if (index < 0) {
1789 if (!locked && rootReference != getRoot()) {
1790 decisionMaker.reset();
1791 continue;
1792 }
1793 return null;
1794 }
1795
1796 if (p.getTotalCount() == 1 && pos != null) {
1797 int keyCount;
1798 do {
1799 p = pos.page;
1800 index = pos.index;
1801 pos = pos.parent;
1802 keyCount = p.getKeyCount();
1803 // condition below should always be false, but older
1804 // versions (up to 1.4.197) may create
1805 // single-childed (with no keys) internal nodes,
1806 // which we skip here
1807 } while (keyCount == 0 && pos != null);
1808
1809 if (keyCount <= 1) {
1810 if (keyCount == 1) {
1811 assert index <= 1;
1812 p = p.getChildPage(1 - index);
1813 } else {
1814 // if root happens to be such single-childed
1815 // (with no keys) internal node, then just
1816 // replace it with empty leaf
1817 p = Page.createEmptyLeaf(this);
1818 }
1819 break;
1820 }
1821 }
1822 p = p.copy();
1823 p.remove(index);
1824 break;
1825 }
1826 case PUT: {
1827 value = decisionMaker.selectValue(result, value);
1828 p = p.copy();
1829 if (index < 0) {
1830 p.insertLeaf(-index - 1, key, value);
1831 int keyCount;
1832 while ((keyCount = p.getKeyCount()) > store.getKeysPerPage()
1833 || p.getMemory() > store.getMaxPageSize()
1834 && keyCount > (p.isLeaf() ? 1 : 2)) {
1835 long totalCount = p.getTotalCount();
1836 int at = keyCount >> 1;
1837 K k = p.getKey(at);
1838 Page<K,V> split = p.split(at);
1839 unsavedMemoryHolder.value += p.getMemory() + split.getMemory();
1840 if (pos == null) {
1841 K[] keys = p.createKeyStorage(1);
1842 keys[0] = k;
1843 Page.PageReference<K,V>[] children = Page.createRefStorage(2);
1844 children[0] = new Page.PageReference<>(p);
1845 children[1] = new Page.PageReference<>(split);
1846 p = Page.createNode(this, keys, children, totalCount, 0);
1847 break;
1848 }
1849 Page<K,V> c = p;
1850 p = pos.page;
1851 index = pos.index;
1852 pos = pos.parent;
1853 p = p.copy();
1854 p.setChild(index, split);
1855 p.insertNode(index, k, c);
1856 }
1857 } else {
1858 p.setValue(index, value);
1859 }
1860 break;
1861 }
1862 }
1863 rootPage = replacePage(pos, p, unsavedMemoryHolder);
1864 if (!locked) {
1865 rootReference = rootReference.updateRootPage(rootPage, attempt);
1866 if (rootReference == null) {
1867 decisionMaker.reset();
1868 continue;
1869 }
1870 }
1871 if (isPersistent()) {
1872 registerUnsavedMemory(unsavedMemoryHolder.value + tip.processRemovalInfo(version));
1873 }
1874 return result;
1875 } finally {
1876 if(locked) {
1877 unlockRoot(rootPage);
1878 }
1879 }
1880 }
1881 }
1882
1883 private RootReference<K,V> lockRoot(RootReference<K,V> rootReference, int attempt) {
1884 while(true) {
1885 RootReference<K,V> lockedRootReference = tryLock(rootReference, attempt++);
1886 if (lockedRootReference != null) {
1887 return lockedRootReference;
1888 }
1889 rootReference = getRoot();
1890 }
1891 }
1892
1893 /**
1894 * Try to lock the root.
1895 *
1896 * @param rootReference the old root reference
1897 * @param attempt the number of attempts so far
1898 * @return the new root reference
1899 */
1900 protected RootReference<K,V> tryLock(RootReference<K,V> rootReference, int attempt) {
1901 RootReference<K,V> lockedRootReference = rootReference.tryLock(attempt);
1902 if (lockedRootReference != null) {
1903 return lockedRootReference;
1904 }
1905 assert !rootReference.isLockedByCurrentThread() : rootReference;
1906 RootReference<K,V> oldRootReference = rootReference.previous;
1907 int contention = 1;
1908 if (oldRootReference != null) {
1909 long updateAttemptCounter = rootReference.updateAttemptCounter -
1910 oldRootReference.updateAttemptCounter;
1911 assert updateAttemptCounter >= 0 : updateAttemptCounter;
1912 long updateCounter = rootReference.updateCounter - oldRootReference.updateCounter;
1913 assert updateCounter >= 0 : updateCounter;
1914 assert updateAttemptCounter >= updateCounter : updateAttemptCounter + " >= " + updateCounter;
1915 contention += (int)((updateAttemptCounter+1) / (updateCounter+1));
1916 }
1917
1918 if(attempt > 4) {
1919 if (attempt <= 12) {
1920 Thread.yield();
1921 } else if (attempt <= 70 - 2 * contention) {
1922 try {
1923 Thread.sleep(contention);
1924 } catch (InterruptedException ex) {
1925 throw new RuntimeException(ex);
1926 }
1927 } else {
1928 synchronized (lock) {
1929 notificationRequested = true;
1930 try {
1931 lock.wait(5);
1932 } catch (InterruptedException ignore) {
1933 }
1934 }
1935 }
1936 }
1937 return null;
1938 }
1939
1940 /**
1941 * Unlock the root page, the new root being null.
1942 *
1943 * @return the new root reference (never null)
1944 */
1945 private RootReference<K,V> unlockRoot() {
1946 return unlockRoot(null, -1);
1947 }
1948
1949 /**
1950 * Unlock the root page.
1951 *
1952 * @param newRootPage the new root
1953 * @return the new root reference (never null)
1954 */
1955 protected RootReference<K,V> unlockRoot(Page<K,V> newRootPage) {
1956 return unlockRoot(newRootPage, -1);
1957 }
1958
1959 private void unlockRoot(int appendCounter) {
1960 unlockRoot(null, appendCounter);
1961 }
1962
1963 private RootReference<K,V> unlockRoot(Page<K,V> newRootPage, int appendCounter) {
1964 RootReference<K,V> updatedRootReference;
1965 do {
1966 RootReference<K,V> rootReference = getRoot();
1967 assert rootReference.isLockedByCurrentThread();
1968 updatedRootReference = rootReference.updatePageAndLockedStatus(
1969 newRootPage == null ? rootReference.root : newRootPage,
1970 false,
1971 appendCounter == -1 ? rootReference.getAppendCounter() : appendCounter
1972 );
1973 } while(updatedRootReference == null);
1974
1975 notifyWaiters();
1976 return updatedRootReference;
1977 }
1978
1979 private void notifyWaiters() {
1980 if (notificationRequested) {
1981 synchronized (lock) {
1982 notificationRequested = false;
1983 lock.notify();
1984 }
1985 }
1986 }
1987
1988 final boolean isMemoryEstimationAllowed() {
1989 return avgKeySize != null || avgValSize != null;
1990 }
1991
1992 final int evaluateMemoryForKeys(K[] storage, int count) {
1993 if (avgKeySize == null) {
1994 return calculateMemory(keyType, storage, count);
1995 }
1996 return MemoryEstimator.estimateMemory(avgKeySize, keyType, storage, count);
1997 }
1998
1999 final int evaluateMemoryForValues(V[] storage, int count) {
2000 if (avgValSize == null) {
2001 return calculateMemory(valueType, storage, count);
2002 }
2003 return MemoryEstimator.estimateMemory(avgValSize, valueType, storage, count);
2004 }
2005
2006 private static <T> int calculateMemory(DataType<T> keyType, T[] storage, int count) {
2007 int mem = count * MEMORY_POINTER;
2008 for (int i = 0; i < count; i++) {
2009 mem += keyType.getMemory(storage[i]);
2010 }
2011 return mem;
2012 }
2013
2014 final int evaluateMemoryForKey(K key) {
2015 if (avgKeySize == null) {
2016 return keyType.getMemory(key);
2017 }
2018 return MemoryEstimator.estimateMemory(avgKeySize, keyType, key);
2019 }
2020
2021 final int evaluateMemoryForValue(V value) {
2022 if (avgValSize == null) {
2023 return valueType.getMemory(value);
2024 }
2025 return MemoryEstimator.estimateMemory(avgValSize, valueType, value);
2026 }
2027
2028 static int samplingPct(AtomicLong stats) {
2029 return MemoryEstimator.samplingPct(stats);
2030 }
2031
2032 private static final class EqualsDecisionMaker<V> extends DecisionMaker<V> {
2033 private final DataType<V> dataType;
2034 private final V expectedValue;
2035 private Decision decision;
2036
2037 EqualsDecisionMaker(DataType<V> dataType, V expectedValue) {
2038 this.dataType = dataType;
2039 this.expectedValue = expectedValue;
2040 }
2041
2042 @Override
2043 public Decision decide(V existingValue, V providedValue) {
2044 assert decision == null;
2045 decision = !areValuesEqual(dataType, expectedValue, existingValue) ? Decision.ABORT :
2046 providedValue == null ? Decision.REMOVE : Decision.PUT;
2047 return decision;
2048 }
2049
2050 @Override
2051 public void reset() {
2052 decision = null;
2053 }
2054
2055 Decision getDecision() {
2056 return decision;
2057 }
2058
2059 @Override
2060 public String toString() {
2061 return "equals_to "+expectedValue;
2062 }
2063 }
2064
2065 private static final class RewriteDecisionMaker<V> extends DecisionMaker<V> {
2066 private final long pagePos;
2067 private Decision decision;
2068
2069 RewriteDecisionMaker(long pagePos) {
2070 this.pagePos = pagePos;
2071 }
2072
2073 @Override
2074 public Decision decide(V existingValue, V providedValue, CursorPos<?,?> tip) {
2075 assert decision == null;
2076 decision = Decision.ABORT;
2077 if(!DataUtils.isLeafPosition(pagePos)) {
2078 while ((tip = tip.parent) != null) {
2079 if (tip.page.getPos() == pagePos) {
2080 decision = decide(existingValue, providedValue);
2081 break;
2082 }
2083 }
2084 } else if (tip.page.getPos() == pagePos) {
2085 decision = decide(existingValue, providedValue);
2086 }
2087 return decision;
2088 }
2089
2090 @Override
2091 public Decision decide(V existingValue, V providedValue) {
2092 decision = existingValue == null ? Decision.ABORT : Decision.PUT;
2093 return decision;
2094 }
2095
2096 @Override
2097 public <T extends V> T selectValue(T existingValue, T providedValue) {
2098 return existingValue;
2099 }
2100
2101 @Override
2102 public void reset() {
2103 decision = null;
2104 }
2105
2106 Decision getDecision() {
2107 return decision;
2108 }
2109
2110 @Override
2111 public String toString() {
2112 return "rewrite";
2113 }
2114 }
2115
2116 private static final class IntValueHolder {
2117 int value;
2118
2119 IntValueHolder() {}
2120 }
2121 }