Debian Codegraph @

src/main/org/h2/mvstore/tx/TransactionMap.java

raw
1 /*
2 * Copyright 2004-2019 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (http://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.mvstore.tx;
7
8 import org.h2.mvstore.Cursor;
9 import org.h2.mvstore.DataUtils;
10 import org.h2.mvstore.MVMap;
11 import org.h2.mvstore.Page;
12 import org.h2.mvstore.RootReference;
13 import org.h2.mvstore.type.DataType;
14 import org.h2.value.VersionedValue;
15
16 import java.util.AbstractMap;
17 import java.util.AbstractSet;
18 import java.util.BitSet;
19 import java.util.Iterator;
20 import java.util.Map;
21 import java.util.NoSuchElementException;
22 import java.util.Set;
23
24 /**
25 * A map that supports transactions.
26 *
27 * <p>
28 * <b>Methods of this class may be changed at any time without notice.</b> If
29 * you use this class directly make sure that your application or library
30 * requires exactly the same version of MVStore or H2 jar as the version that
31 * you use during its development and build.
32 * </p>
33 *
34 * @param <K> the key type
35 * @param <V> the value type
36 */
37 public class TransactionMap<K, V> extends AbstractMap<K, V> {
38
39 /**
40 * The map used for writing (the latest version).
41 * <p>
42 * Key: key the key of the data.
43 * Value: { transactionId, oldVersion, value }
44 */
45 public final MVMap<K, VersionedValue> map;
46
47 /**
48 * The transaction which is used for this map.
49 */
50 private final Transaction transaction;
51
52 TransactionMap(Transaction transaction, MVMap<K, VersionedValue> map) {
53 this.transaction = transaction;
54 this.map = map;
55 }
56
57 /**
58 * Get a clone of this map for the given transaction.
59 *
60 * @param transaction the transaction
61 * @return the map
62 */
63 public TransactionMap<K, V> getInstance(Transaction transaction) {
64 return new TransactionMap<>(transaction, map);
65 }
66
67 /**
68 * Get the number of entries, as a integer. {@link Integer#MAX_VALUE} is
69 * returned if there are more than this entries.
70 *
71 * @return the number of entries, as an integer
72 * @see #sizeAsLong()
73 */
74 @Override
75 public final int size() {
76 long size = sizeAsLong();
77 return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size;
78 }
79
80 /**
81 * Get the size of the raw map. This includes uncommitted entries, and
82 * transiently removed entries, so it is the maximum number of entries.
83 *
84 * @return the maximum size
85 */
86 public long sizeAsLongMax() {
87 return map.sizeAsLong();
88 }
89
90 /**
91 * Get the size of the map as seen by this transaction.
92 *
93 * @return the size
94 */
95 public long sizeAsLong() {
96 TransactionStore store = transaction.store;
97
98 // The purpose of the following loop is to get a coherent picture
99 // of a state of three independent volatile / atomic variables,
100 // which they had at some recent moment in time.
101 // In order to get such a "snapshot", we wait for a moment of silence,
102 // when none of the variables concurrently changes it's value.
103 BitSet committingTransactions;
104 RootReference mapRootReference;
105 RootReference[] undoLogRootReferences;
106 long undoLogSize;
107 do {
108 committingTransactions = store.committingTransactions.get();
109 mapRootReference = map.flushAndGetRoot();
110 BitSet opentransactions = store.openTransactions.get();
111 undoLogRootReferences = new RootReference[opentransactions.length()];
112 undoLogSize = 0;
113 for (int i = opentransactions.nextSetBit(0); i >= 0; i = opentransactions.nextSetBit(i+1)) {
114 MVMap<Long, Object[]> undoLog = store.undoLogs[i];
115 if (undoLog != null) {
116 RootReference rootReference = undoLog.flushAndGetRoot();
117 undoLogRootReferences[i] = rootReference;
118 undoLogSize += rootReference.getTotalCount();
119 }
120 }
121 } while(committingTransactions != store.committingTransactions.get() ||
122 mapRootReference != map.getRoot());
123 // Now we have a snapshot, where mapRootReference points to state of the map,
124 // undoLogRootReference captures the state of undo log
125 // and committingTransactions mask tells us which of seemingly uncommitted changes
126 // should be considered as committed.
127 // Subsequent processing uses this snapshot info only.
128 Page mapRootPage = mapRootReference.root;
129 long size = mapRootReference.getTotalCount();
130 // if we are looking at the map without any uncommitted values
131 if (undoLogSize == 0) {
132 return size;
133 }
134
135 // Entries describing removals from the map by this transaction and all transactions,
136 // which are committed but not closed yet,
137 // and entries about additions to the map by other uncommitted transactions were counted,
138 // but they should not contribute into total count.
139 if (2 * undoLogSize > size) {
140 // the undo log is larger than half of the map - scan the entries of the map directly
141 Cursor<K, VersionedValue> cursor = new Cursor<>(mapRootPage, null);
142 while(cursor.hasNext()) {
143 cursor.next();
144 VersionedValue currentValue = cursor.getValue();
145 assert currentValue != null;
146 long operationId = currentValue.getOperationId();
147 if (operationId != 0) { // skip committed entries
148 int txId = TransactionStore.getTransactionId(operationId);
149 boolean isVisible = txId == transaction.transactionId ||
150 committingTransactions.get(txId);
151 Object v = isVisible ? currentValue.getCurrentValue() : currentValue.getCommittedValue();
152 if (v == null) {
153 --size;
154 }
155 }
156 }
157 } else {
158 // The undo logs are much smaller than the map - scan all undo logs,
159 // and then lookup relevant map entry.
160 for (RootReference undoLogRootReference : undoLogRootReferences) {
161 if (undoLogRootReference != null) {
162 Cursor<Long, Object[]> cursor = new Cursor<>(undoLogRootReference.root, null);
163 while (cursor.hasNext()) {
164 cursor.next();
165 Object op[] = cursor.getValue();
166 if ((int) op[0] == map.getId()) {
167 VersionedValue currentValue = map.get(mapRootPage, op[1]);
168 // If map entry is not there, then we never counted
169 // it, in the first place, so skip it.
170 // This is possible when undo entry exists because
171 // it belongs to a committed but not yet closed
172 // transaction, and it was later deleted by some
173 // other already committed and closed transaction.
174 if (currentValue != null) {
175 // only the last undo entry for any given map
176 // key should be considered
177 long operationId = cursor.getKey();
178 if (currentValue.getOperationId() == operationId) {
179 int txId = TransactionStore.getTransactionId(operationId);
180 boolean isVisible = txId == transaction.transactionId ||
181 committingTransactions.get(txId);
182 Object v = isVisible ? currentValue.getCurrentValue()
183 : currentValue.getCommittedValue();
184 if (v == null) {
185 --size;
186 }
187 }
188 }
189 }
190 }
191 }
192 }
193 }
194 return size;
195 }
196
197 /**
198 * Remove an entry.
199 * <p>
200 * If the row is locked, this method will retry until the row could be
201 * updated or until a lock timeout.
202 *
203 * @param key the key
204 * @throws IllegalStateException if a lock timeout occurs
205 * @throws ClassCastException if type of the specified key is not compatible with this map
206 */
207 @Override
208 public V remove(Object key) {
209 return set(key, (V)null);
210 }
211
212 /**
213 * Update the value for the given key.
214 * <p>
215 * If the row is locked, this method will retry until the row could be
216 * updated or until a lock timeout.
217 *
218 * @param key the key
219 * @param value the new value (not null)
220 * @return the old value
221 * @throws IllegalStateException if a lock timeout occurs
222 */
223 @Override
224 public V put(K key, V value) {
225 DataUtils.checkArgument(value != null, "The value may not be null");
226 return set(key, value);
227 }
228
229 /**
230 * Put the value for the given key if entry for this key does not exist.
231 * It is atomic equivalent of the following expression:
232 * contains(key) ? get(k) : put(key, value);
233 *
234 * @param key the key
235 * @param value the new value (not null)
236 * @return the old value
237 */
238 // Do not add @Override, code should be compatible with Java 7
239 public V putIfAbsent(K key, V value) {
240 DataUtils.checkArgument(value != null, "The value may not be null");
241 TxDecisionMaker decisionMaker = new TxDecisionMaker.PutIfAbsentDecisionMaker(map.getId(), key, value,
242 transaction);
243 return set(key, decisionMaker);
244 }
245
246 /**
247 * Appends entry to underlying map. This method may be used concurrently,
248 * but latest appended values are not guaranteed to be visible.
249 * @param key should be higher in map's order than any existing key
250 * @param value to be appended
251 */
252 public void append(K key, V value) {
253 map.append(key, VersionedValueUncommitted.getInstance(transaction.log(map.getId(), key, null), value, null));
254 }
255
256 /**
257 * Lock row for the given key.
258 * <p>
259 * If the row is locked, this method will retry until the row could be
260 * updated or until a lock timeout.
261 *
262 * @param key the key
263 * @return the locked value
264 * @throws IllegalStateException if a lock timeout occurs
265 */
266 public V lock(K key) {
267 TxDecisionMaker decisionMaker = new TxDecisionMaker.LockDecisionMaker(map.getId(), key, transaction);
268 return set(key, decisionMaker);
269 }
270
271 /**
272 * Update the value for the given key, without adding an undo log entry.
273 *
274 * @param key the key
275 * @param value the value
276 * @return the old value
277 */
278 public V putCommitted(K key, V value) {
279 DataUtils.checkArgument(value != null, "The value may not be null");
280 VersionedValue newValue = VersionedValueCommitted.getInstance(value);
281 VersionedValue oldValue = map.put(key, newValue);
282 @SuppressWarnings("unchecked")
283 V result = (V) (oldValue == null ? null : oldValue.getCurrentValue());
284 return result;
285 }
286
287 private V set(Object key, V value) {
288 TxDecisionMaker decisionMaker = new TxDecisionMaker.PutDecisionMaker(map.getId(), key, value, transaction);
289 return set(key, decisionMaker);
290 }
291
292 private V set(Object key, TxDecisionMaker decisionMaker) {
293 TransactionStore store = transaction.store;
294 Transaction blockingTransaction;
295 long sequenceNumWhenStarted;
296 VersionedValue result;
297 do {
298 sequenceNumWhenStarted = store.openTransactions.get().getVersion();
299 assert transaction.getBlockerId() == 0;
300 // although second parameter (value) is not really used,
301 // since TxDecisionMaker has it embedded,
302 // MVRTreeMap has weird traversal logic based on it,
303 // and any non-null value will do
304 @SuppressWarnings("unchecked")
305 K k = (K) key;
306 result = map.operate(k, VersionedValue.DUMMY, decisionMaker);
307
308 MVMap.Decision decision = decisionMaker.getDecision();
309 assert decision != null;
310 assert decision != MVMap.Decision.REPEAT;
311 blockingTransaction = decisionMaker.getBlockingTransaction();
312 if (decision != MVMap.Decision.ABORT || blockingTransaction == null) {
313 @SuppressWarnings("unchecked")
314 V res = result == null ? null : (V) result.getCurrentValue();
315 return res;
316 }
317 decisionMaker.reset();
318 } while (blockingTransaction.sequenceNum > sequenceNumWhenStarted
319 || transaction.waitFor(blockingTransaction, map, key));
320
321 throw DataUtils.newIllegalStateException(DataUtils.ERROR_TRANSACTION_LOCKED,
322 "Map entry <{0}> with key <{1}> and value {2} is locked by tx {3} and can not be updated by tx {4}"
323 + " within allocated time interval {5} ms.",
324 map.getName(), key, result, blockingTransaction.transactionId, transaction.transactionId,
325 transaction.timeoutMillis);
326 }
327
328 /**
329 * Try to remove the value for the given key.
330 * <p>
331 * This will fail if the row is locked by another transaction (that
332 * means, if another open transaction changed the row).
333 *
334 * @param key the key
335 * @return whether the entry could be removed
336 */
337 public boolean tryRemove(K key) {
338 return trySet(key, null);
339 }
340
341 /**
342 * Try to update the value for the given key.
343 * <p>
344 * This will fail if the row is locked by another transaction (that
345 * means, if another open transaction changed the row).
346 *
347 * @param key the key
348 * @param value the new value
349 * @return whether the entry could be updated
350 */
351 public boolean tryPut(K key, V value) {
352 DataUtils.checkArgument(value != null, "The value may not be null");
353 return trySet(key, value);
354 }
355
356 /**
357 * Try to set or remove the value. When updating only unchanged entries,
358 * then the value is only changed if it was not changed after opening
359 * the map.
360 *
361 * @param key the key
362 * @param value the new value (null to remove the value)
363 * @return true if the value was set, false if there was a concurrent
364 * update
365 */
366 public boolean trySet(K key, V value) {
367 try {
368 // TODO: effective transaction.timeoutMillis should be set to 0 here
369 // and restored before return
370 // TODO: eliminate exception usage as part of normal control flaw
371 set(key, value);
372 return true;
373 } catch (IllegalStateException e) {
374 return false;
375 }
376 }
377
378 /**
379 * Get the effective value for the given key.
380 *
381 * @param key the key
382 * @return the value or null
383 * @throws ClassCastException if type of the specified key is not compatible with this map
384 */
385 @Override
386 @SuppressWarnings("unchecked")
387 public V get(Object key) {
388 VersionedValue data = map.get(key);
389 if (data == null) {
390 // doesn't exist or deleted by a committed transaction
391 return null;
392 }
393 long id = data.getOperationId();
394 if (id == 0) {
395 // it is committed
396 return (V)data.getCurrentValue();
397 }
398 int tx = TransactionStore.getTransactionId(id);
399 if (tx == transaction.transactionId || transaction.store.committingTransactions.get().get(tx)) {
400 // added by this transaction or another transaction which is committed by now
401 return (V) data.getCurrentValue();
402 } else {
403 return (V) data.getCommittedValue();
404 }
405 }
406
407 /**
408 * Whether the map contains the key.
409 *
410 * @param key the key
411 * @return true if the map contains an entry for this key
412 * @throws ClassCastException if type of the specified key is not compatible with this map
413 */
414 @Override
415 public boolean containsKey(Object key) {
416 return get(key) != null;
417 }
418
419 /**
420 * Whether the entry for this key was added or removed from this
421 * session.
422 *
423 * @param key the key
424 * @return true if yes
425 */
426 public boolean isSameTransaction(K key) {
427 VersionedValue data = map.get(key);
428 if (data == null) {
429 // doesn't exist or deleted by a committed transaction
430 return false;
431 }
432 int tx = TransactionStore.getTransactionId(data.getOperationId());
433 return tx == transaction.transactionId;
434 }
435
436 /**
437 * Check whether this map is closed.
438 *
439 * @return true if closed
440 */
441 public boolean isClosed() {
442 return map.isClosed();
443 }
444
445 /**
446 * Clear the map.
447 */
448 @Override
449 public void clear() {
450 // TODO truncate transactionally?
451 map.clear();
452 }
453
454 @Override
455 public Set<Entry<K, V>> entrySet() {
456 return new AbstractSet<Entry<K, V>>() {
457
458 @Override
459 public Iterator<Entry<K, V>> iterator() {
460 return entryIterator(null, null);
461 }
462
463 @Override
464 public int size() {
465 return TransactionMap.this.size();
466 }
467
468 @Override
469 public boolean contains(Object o) {
470 return TransactionMap.this.containsKey(o);
471 }
472
473 };
474 }
475
476 /**
477 * Get the first key.
478 *
479 * @return the first key, or null if empty
480 */
481 public K firstKey() {
482 Iterator<K> it = keyIterator(null);
483 return it.hasNext() ? it.next() : null;
484 }
485
486 /**
487 * Get the last key.
488 *
489 * @return the last key, or null if empty
490 */
491 public K lastKey() {
492 K k = map.lastKey();
493 while (k != null && get(k) == null) {
494 k = map.lowerKey(k);
495 }
496 return k;
497 }
498
499 /**
500 * Get the smallest key that is larger than the given key, or null if no
501 * such key exists.
502 *
503 * @param key the key (may not be null)
504 * @return the result
505 */
506 public K higherKey(K key) {
507 do {
508 key = map.higherKey(key);
509 } while (key != null && get(key) == null);
510 return key;
511 }
512
513 /**
514 * Get the smallest key that is larger than or equal to this key,
515 * or null if no such key exists.
516 *
517 * @param key the key (may not be null)
518 * @return the result
519 */
520 public K ceilingKey(K key) {
521 Iterator<K> it = keyIterator(key);
522 return it.hasNext() ? it.next() : null;
523 }
524
525 /**
526 * Get the largest key that is smaller than or equal to this key,
527 * or null if no such key exists.
528 *
529 * @param key the key (may not be null)
530 * @return the result
531 */
532 public K floorKey(K key) {
533 key = map.floorKey(key);
534 while (key != null && get(key) == null) {
535 // Use lowerKey() for the next attempts, otherwise we'll get an infinite loop
536 key = map.lowerKey(key);
537 }
538 return key;
539 }
540
541 /**
542 * Get the largest key that is smaller than the given key, or null if no
543 * such key exists.
544 *
545 * @param key the key (may not be null)
546 * @return the result
547 */
548 public K lowerKey(K key) {
549 do {
550 key = map.lowerKey(key);
551 } while (key != null && get(key) == null);
552 return key;
553 }
554
555 /**
556 * Iterate over keys.
557 *
558 * @param from the first key to return
559 * @return the iterator
560 */
561 public Iterator<K> keyIterator(K from) {
562 return keyIterator(from, null, false);
563 }
564
565 /**
566 * Iterate over keys.
567 *
568 * @param from the first key to return
569 * @param to the last key to return or null if there is no limit
570 * @param includeUncommitted whether uncommitted entries should be
571 * included
572 * @return the iterator
573 */
574 public Iterator<K> keyIterator(K from, K to, boolean includeUncommitted) {
575 return new KeyIterator<>(this, from, to, includeUncommitted);
576 }
577
578 /**
579 * Iterate over entries.
580 *
581 * @param from the first key to return
582 * @param to the last key to return
583 * @return the iterator
584 */
585 public Iterator<Map.Entry<K, V>> entryIterator(final K from, final K to) {
586 return new EntryIterator<>(this, from, to);
587 }
588
589 /**
590 * Iterate over keys.
591 *
592 * @param iterator the iterator to wrap
593 * @param includeUncommitted whether uncommitted entries should be
594 * included
595 * @return the iterator
596 */
597 public Iterator<K> wrapIterator(final Iterator<K> iterator,
598 final boolean includeUncommitted) {
599 // TODO duplicate code for wrapIterator and entryIterator
600 return new Iterator<K>() {
601 private K current;
602
603 {
604 fetchNext();
605 }
606
607 private void fetchNext() {
608 while (iterator.hasNext()) {
609 current = iterator.next();
610 if (includeUncommitted) {
611 return;
612 }
613 if (containsKey(current)) {
614 return;
615 }
616 }
617 current = null;
618 }
619
620 @Override
621 public boolean hasNext() {
622 return current != null;
623 }
624
625 @Override
626 public K next() {
627 K result = current;
628 fetchNext();
629 return result;
630 }
631
632 @Override
633 public void remove() {
634 throw DataUtils.newUnsupportedOperationException(
635 "Removal is not supported");
636 }
637 };
638 }
639
640 public Transaction getTransaction() {
641 return transaction;
642 }
643
644 public DataType getKeyType() {
645 return map.getKeyType();
646 }
647
648
649 private static final class KeyIterator<K> extends TMIterator<K,K> {
650
651 public KeyIterator(TransactionMap<K, ?> transactionMap, K from, K to, boolean includeUncommitted) {
652 super(transactionMap, from, to, includeUncommitted);
653 }
654
655 @Override
656 protected K registerCurrent(K key, VersionedValue data) {
657 return key;
658 }
659 }
660
661 private static final class EntryIterator<K,V> extends TMIterator<K,Map.Entry<K,V>> {
662
663 public EntryIterator(TransactionMap<K, ?> transactionMap, K from, K to) {
664 super(transactionMap, from, to, false);
665 }
666
667 @Override
668 @SuppressWarnings("unchecked")
669 protected Map.Entry<K, V> registerCurrent(K key, VersionedValue data) {
670 return new AbstractMap.SimpleImmutableEntry<>(key, (V) data.getCurrentValue());
671 }
672 }
673
674 private abstract static class TMIterator<K,X> implements Iterator<X> {
675 private final int transactionId;
676 private final BitSet committingTransactions;
677 private final Cursor<K,VersionedValue> cursor;
678 private final boolean includeAllUncommitted;
679 private X current;
680
681 TMIterator(TransactionMap<K,?> transactionMap, K from, K to, boolean includeAllUncommitted) {
682 Transaction transaction = transactionMap.getTransaction();
683 this.transactionId = transaction.transactionId;
684 TransactionStore store = transaction.store;
685 MVMap<K, VersionedValue> map = transactionMap.map;
686 // The purpose of the following loop is to get a coherent picture
687 // of a state of two independent volatile / atomic variables,
688 // which they had at some recent moment in time.
689 // In order to get such a "snapshot", we wait for a moment of silence,
690 // when neither of the variables concurrently changes it's value.
691 BitSet committingTransactions;
692 RootReference mapRootReference;
693 do {
694 committingTransactions = store.committingTransactions.get();
695 mapRootReference = map.flushAndGetRoot();
696 } while (committingTransactions != store.committingTransactions.get());
697 // Now we have a snapshot, where mapRootReference points to state of the map
698 // and committingTransactions mask tells us which of seemingly uncommitted changes
699 // should be considered as committed.
700 // Subsequent map traversal uses this snapshot info only.
701 this.cursor = new Cursor<>(mapRootReference.root, from, to);
702 this.committingTransactions = committingTransactions;
703
704 this.includeAllUncommitted = includeAllUncommitted;
705 fetchNext();
706 }
707
708 protected abstract X registerCurrent(K key, VersionedValue data);
709
710 private void fetchNext() {
711 while (cursor.hasNext()) {
712 K key = cursor.next();
713 VersionedValue data = cursor.getValue();
714 if (!includeAllUncommitted) {
715 // If value doesn't exist or it was deleted by a committed transaction,
716 // or if value is a committed one, just return it.
717 if (data != null) {
718 long id = data.getOperationId();
719 if (id != 0) {
720 int tx = TransactionStore.getTransactionId(id);
721 if (tx != transactionId && !committingTransactions.get(tx)) {
722 // current value comes from another uncommitted transaction
723 // take committed value instead
724 Object committedValue = data.getCommittedValue();
725 data = committedValue == null ? null
726 : VersionedValueCommitted.getInstance(committedValue);
727 }
728 }
729 }
730 }
731 if (data != null && (data.getCurrentValue() != null ||
732 includeAllUncommitted && transactionId !=
733 TransactionStore.getTransactionId(data.getOperationId()))) {
734 current = registerCurrent(key, data);
735 return;
736 }
737 }
738 current = null;
739 }
740
741 @Override
742 public final boolean hasNext() {
743 return current != null;
744 }
745
746 @Override
747 public final X next() {
748 if(current == null) {
749 throw new NoSuchElementException();
750 }
751 X result = current;
752 fetchNext();
753 return result;
754 }
755
756 @Override
757 public final void remove() {
758 throw DataUtils.newUnsupportedOperationException(
759 "Removal is not supported");
760 }
761 }
762
763 }