Debian Codegraph @

src/main/org/h2/mvstore/tx/TransactionMap.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.tx;
7
8 import java.util.AbstractMap;
9 import java.util.AbstractSet;
10 import java.util.BitSet;
11 import java.util.Iterator;
12 import java.util.Map;
13 import java.util.NoSuchElementException;
14 import java.util.Set;
15 import java.util.concurrent.atomic.AtomicReference;
16 import java.util.function.BiFunction;
17
18 import org.h2.engine.IsolationLevel;
19 import org.h2.mvstore.Cursor;
20 import org.h2.mvstore.DataUtils;
21 import org.h2.mvstore.MVMap;
22 import org.h2.mvstore.MVStoreException;
23 import org.h2.mvstore.RootReference;
24 import org.h2.mvstore.type.DataType;
25 import org.h2.value.VersionedValue;
26
27 /**
28 * A map that supports transactions.
29 *
30 * <p>
31 * <b>Methods of this class may be changed at any time without notice.</b> If
32 * you use this class directly make sure that your application or library
33 * requires exactly the same version of MVStore or H2 jar as the version that
34 * you use during its development and build.
35 * </p>
36 *
37 * @param <K> the key type
38 * @param <V> the value type
39 */
40 public final class TransactionMap<K, V> extends AbstractMap<K,V> {
41
42 /**
43 * The map used for writing (the latest version).
44 * <p>
45 * Key: key the key of the data.
46 * Value: { transactionId, oldVersion, value }
47 */
48 public final MVMap<K, VersionedValue<V>> map;
49
50 /**
51 * The transaction which is used for this map.
52 */
53 private final Transaction transaction;
54
55 /**
56 * Snapshot of this map as of beginning of transaction or
57 * first usage within transaction or
58 * beginning of the statement, depending on isolation level
59 */
60 private Snapshot<K,VersionedValue<V>> snapshot;
61
62 /**
63 * Snapshot of this map as of beginning of beginning of the statement
64 */
65 private Snapshot<K,VersionedValue<V>> statementSnapshot;
66
67 /**
68 * Indicates whether underlying map was modified from within related transaction
69 */
70 private boolean hasChanges;
71
72 private final TxDecisionMaker<K,V> txDecisionMaker;
73 private final TxDecisionMaker<K,V> ifAbsentDecisionMaker;
74 private final TxDecisionMaker<K,V> lockDecisionMaker;
75
76
77 TransactionMap(Transaction transaction, MVMap<K, VersionedValue<V>> map) {
78 this.transaction = transaction;
79 this.map = map;
80 this.txDecisionMaker = new TxDecisionMaker<>(map.getId(), transaction);
81 this.ifAbsentDecisionMaker = new TxDecisionMaker.PutIfAbsentDecisionMaker<>(map.getId(),
82 transaction, this::getFromSnapshot);
83 this.lockDecisionMaker = transaction.allowNonRepeatableRead()
84 ? new TxDecisionMaker.LockDecisionMaker<>(map.getId(), transaction)
85 : new TxDecisionMaker.RepeatableReadLockDecisionMaker<>(map.getId(), transaction,
86 map.getValueType(), this::getFromSnapshot);
87
88 }
89
90 /**
91 * Get a clone of this map for the given transaction.
92 *
93 * @param transaction the transaction
94 * @return the map
95 */
96 public TransactionMap<K,V> getInstance(Transaction transaction) {
97 return transaction.openMapX(map);
98 }
99
100 /**
101 * Get the number of entries, as a integer. {@link Integer#MAX_VALUE} is
102 * returned if there are more than this entries.
103 *
104 * @return the number of entries, as an integer
105 * @see #sizeAsLong()
106 */
107 @Override
108 public int size() {
109 long size = sizeAsLong();
110 return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size;
111 }
112
113 /**
114 * Get the size of the raw map. This includes uncommitted entries, and
115 * transiently removed entries, so it is the maximum number of entries.
116 *
117 * @return the maximum size
118 */
119 public long sizeAsLongMax() {
120 return map.sizeAsLong();
121 }
122
123 /**
124 * Get the size of the map as seen by this transaction.
125 *
126 * @return the size
127 */
128 public long sizeAsLong() {
129 IsolationLevel isolationLevel = transaction.getIsolationLevel();
130 if (!isolationLevel.allowNonRepeatableRead() && hasChanges) {
131 return sizeAsLongRepeatableReadWithChanges();
132 }
133 // getting coherent picture of the map, committing transactions, and undo logs
134 // either from values stored in transaction (never loops in that case),
135 // or current values from the transaction store (loops until moment of silence)
136 Snapshot<K,VersionedValue<V>> snapshot;
137 RootReference<Long,Record<?,?>>[] undoLogRootReferences;
138 do {
139 snapshot = getSnapshot();
140 undoLogRootReferences = getTransaction().getUndoLogRootReferences();
141 } while (!snapshot.equals(getSnapshot()));
142
143 RootReference<K,VersionedValue<V>> mapRootReference = snapshot.root;
144 long size = mapRootReference.getTotalCount();
145 long undoLogsTotalSize = undoLogRootReferences == null ? size
146 : TransactionStore.calculateUndoLogsTotalSize(undoLogRootReferences);
147 // if we are looking at the map without any uncommitted values
148 if (undoLogsTotalSize == 0) {
149 return size;
150 }
151 return adjustSize(undoLogRootReferences, mapRootReference,
152 isolationLevel == IsolationLevel.READ_UNCOMMITTED ? null : snapshot.committingTransactions,
153 size, undoLogsTotalSize);
154 }
155
156 private long adjustSize(RootReference<Long, Record<?, ?>>[] undoLogRootReferences,
157 RootReference<K, VersionedValue<V>> mapRootReference, BitSet committingTransactions, long size,
158 long undoLogsTotalSize) {
159 // Entries describing removals from the map by this transaction and all transactions,
160 // which are committed but not closed yet,
161 // and entries about additions to the map by other uncommitted transactions were counted,
162 // but they should not contribute into total count.
163 if (2 * undoLogsTotalSize > size) {
164 // the undo log is larger than half of the map - scan the entries of the map directly
165 Cursor<K, VersionedValue<V>> cursor = map.cursor(mapRootReference, null, null, false);
166 while (cursor.hasNext()) {
167 cursor.next();
168 VersionedValue<?> currentValue = cursor.getValue();
169 assert currentValue != null;
170 long operationId = currentValue.getOperationId();
171 if (operationId != 0 && // skip committed entries
172 isIrrelevant(operationId, currentValue, committingTransactions)) {
173 --size;
174 }
175 }
176 } else {
177 assert undoLogRootReferences != null;
178 // The undo logs are much smaller than the map - scan all undo logs,
179 // and then lookup relevant map entry.
180 for (RootReference<Long,Record<?,?>> undoLogRootReference : undoLogRootReferences) {
181 if (undoLogRootReference != null) {
182 Cursor<Long, Record<?, ?>> cursor = undoLogRootReference.root.map.cursor(undoLogRootReference,
183 null, null, false);
184 while (cursor.hasNext()) {
185 cursor.next();
186 Record<?,?> op = cursor.getValue();
187 if (op.mapId == map.getId()) {
188 @SuppressWarnings("unchecked")
189 VersionedValue<V> currentValue = map.get(mapRootReference.root, (K)op.key);
190 // If map entry is not there, then we never counted
191 // it, in the first place, so skip it.
192 // This is possible when undo entry exists because
193 // it belongs to a committed but not yet closed
194 // transaction, and it was later deleted by some
195 // other already committed and closed transaction.
196 if (currentValue != null) {
197 // only the last undo entry for any given map
198 // key should be considered
199 long operationId = cursor.getKey();
200 assert operationId != 0;
201 if (currentValue.getOperationId() == operationId &&
202 isIrrelevant(operationId, currentValue, committingTransactions)) {
203 --size;
204 }
205 }
206 }
207 }
208 }
209 }
210 }
211 return size;
212 }
213
214 private boolean isIrrelevant(long operationId, VersionedValue<?> currentValue, BitSet committingTransactions) {
215 Object v;
216 if (committingTransactions == null) {
217 v = currentValue.getCurrentValue();
218 } else {
219 int txId = TransactionStore.getTransactionId(operationId);
220 v = txId == transaction.transactionId || committingTransactions.get(txId)
221 ? currentValue.getCurrentValue() : currentValue.getCommittedValue();
222 }
223 return v == null;
224 }
225
226 private long sizeAsLongRepeatableReadWithChanges() {
227 long count = 0L;
228 RepeatableIterator<K, V, K> iterator = new RepeatableIterator<>(this, null, null, false, false);
229 while (iterator.fetchNext() != null) {
230 count++;
231 }
232 return count;
233 }
234
235 /**
236 * Remove an entry.
237 * <p>
238 * If the row is locked, this method will retry until the row could be
239 * updated or until a lock timeout.
240 *
241 * @param key the key
242 * @throws MVStoreException if a lock timeout occurs
243 * @throws ClassCastException if type of the specified key is not compatible with this map
244 */
245 @SuppressWarnings("unchecked")
246 @Override
247 public V remove(Object key) {
248 return set((K)key, (V)null);
249 }
250
251 /**
252 * Update the value for the given key.
253 * <p>
254 * If the row is locked, this method will retry until the row could be
255 * updated or until a lock timeout.
256 *
257 * @param key the key
258 * @param value the new value (not null)
259 * @return the old value
260 * @throws MVStoreException if a lock timeout occurs
261 */
262 @Override
263 public V put(K key, V value) {
264 DataUtils.checkArgument(value != null, "The value may not be null");
265 return set(key, value);
266 }
267
268 /**
269 * Put the value for the given key if entry for this key does not exist.
270 * It is atomic equivalent of the following expression:
271 * contains(key) ? get(k) : put(key, value);
272 *
273 * @param key the key
274 * @param value the new value (not null)
275 * @return the old value
276 */
277 @Override
278 public V putIfAbsent(K key, V value) {
279 DataUtils.checkArgument(value != null, "The value may not be null");
280 ifAbsentDecisionMaker.initialize(key, value);
281 V result = set(key, ifAbsentDecisionMaker, -1);
282 if (ifAbsentDecisionMaker.getDecision() == MVMap.Decision.ABORT) {
283 result = ifAbsentDecisionMaker.getLastValue();
284 }
285 return result;
286 }
287
288 /**
289 * Appends entry to underlying map. This method may be used concurrently,
290 * but latest appended values are not guaranteed to be visible.
291 * @param key should be higher in map's order than any existing key
292 * @param value to be appended
293 */
294 public void append(K key, V value) {
295 map.append(key, VersionedValueUncommitted.getInstance(
296 transaction.log(new Record<>(map.getId(), key, null)), value, null));
297 hasChanges = true;
298 }
299
300 /**
301 * Lock row for the given key.
302 * <p>
303 * If the row is locked, this method will retry until the row could be
304 * updated or until a lock timeout.
305 *
306 * @param key the key
307 * @return the locked value
308 * @throws MVStoreException if a lock timeout occurs
309 */
310 public V lock(K key) {
311 return lock(key, -1);
312 }
313
314 /**
315 * Lock row for the given key.
316 * <p>
317 * If the row is locked, this method will retry until the row could be
318 * updated or until a lock timeout.
319 *
320 * @param key the key
321 * @param timeoutMillis
322 * timeout in milliseconds, {@code -1} for default, {@code -2} to
323 * skip locking if row is already locked by another transaction
324 * @return the locked value
325 * @throws MVStoreException if a lock timeout occurs
326 */
327 public V lock(K key, int timeoutMillis) {
328 lockDecisionMaker.initialize(key, null);
329 return set(key, lockDecisionMaker, timeoutMillis);
330 }
331
332 /**
333 * Update the value for the given key, without adding an undo log entry.
334 *
335 * @param key the key
336 * @param value the value
337 * @return the old value
338 */
339 @SuppressWarnings("UnusedReturnValue")
340 public V putCommitted(K key, V value) {
341 DataUtils.checkArgument(value != null, "The value may not be null");
342 VersionedValue<V> newValue = VersionedValueCommitted.getInstance(value);
343 VersionedValue<V> oldValue = map.put(key, newValue);
344 V result = oldValue == null ? null : oldValue.getCurrentValue();
345 return result;
346 }
347
348 private V set(K key, V value) {
349 txDecisionMaker.initialize(key, value);
350 return set(key, txDecisionMaker, -1);
351 }
352
353 private V set(Object key, TxDecisionMaker<K,V> decisionMaker, int timeoutMillis) {
354 Transaction blockingTransaction;
355 VersionedValue<V> result;
356 String mapName = null;
357 do {
358 assert transaction.getBlockerId() == 0;
359 @SuppressWarnings("unchecked")
360 K k = (K) key;
361 // second parameter (value) is not really used,
362 // since TxDecisionMaker has it embedded
363 result = map.operate(k, null, decisionMaker);
364
365 MVMap.Decision decision = decisionMaker.getDecision();
366 assert decision != null;
367 assert decision != MVMap.Decision.REPEAT;
368 blockingTransaction = decisionMaker.getBlockingTransaction();
369 if (decision != MVMap.Decision.ABORT || blockingTransaction == null) {
370 hasChanges |= decision != MVMap.Decision.ABORT;
371 V res = result == null ? null : result.getCurrentValue();
372 return res;
373 }
374 decisionMaker.reset();
375 if (timeoutMillis == -2) {
376 return null;
377 }
378 if (mapName == null) {
379 mapName = map.getName();
380 }
381 } while (timeoutMillis != 0 && transaction.waitFor(blockingTransaction, mapName, key, timeoutMillis));
382
383 throw DataUtils.newMVStoreException(DataUtils.ERROR_TRANSACTION_LOCKED,
384 "Map entry <{0}> with key <{1}> and value {2} is locked by tx {3} and can not be updated by tx {4}"
385 + " within allocated time interval {5} ms.",
386 mapName, key, result, blockingTransaction.transactionId, transaction.transactionId,
387 timeoutMillis == -1 ? transaction.timeoutMillis : timeoutMillis);
388 }
389
390 /**
391 * Try to remove the value for the given key.
392 * <p>
393 * This will fail if the row is locked by another transaction (that
394 * means, if another open transaction changed the row).
395 *
396 * @param key the key
397 * @return whether the entry could be removed
398 */
399 public boolean tryRemove(K key) {
400 return trySet(key, null);
401 }
402
403 /**
404 * Try to update the value for the given key.
405 * <p>
406 * This will fail if the row is locked by another transaction (that
407 * means, if another open transaction changed the row).
408 *
409 * @param key the key
410 * @param value the new value
411 * @return whether the entry could be updated
412 */
413 public boolean tryPut(K key, V value) {
414 DataUtils.checkArgument(value != null, "The value may not be null");
415 return trySet(key, value);
416 }
417
418 /**
419 * Try to set or remove the value. When updating only unchanged entries,
420 * then the value is only changed if it was not changed after opening
421 * the map.
422 *
423 * @param key the key
424 * @param value the new value (null to remove the value)
425 * @return true if the value was set, false if there was a concurrent
426 * update
427 */
428 public boolean trySet(K key, V value) {
429 try {
430 // TODO: effective transaction.timeoutMillis should be set to 0 here
431 // and restored before return
432 // TODO: eliminate exception usage as part of normal control flaw
433 set(key, value);
434 return true;
435 } catch (MVStoreException e) {
436 return false;
437 }
438 }
439
440 /**
441 * Get the effective value for the given key.
442 *
443 * @param key the key
444 * @return the value or null
445 * @throws ClassCastException if type of the specified key is not compatible with this map
446 */
447 @SuppressWarnings("unchecked")
448 @Override
449 public V get(Object key) {
450 return getImmediate((K)key);
451 }
452
453 /**
454 * Get the value for the given key, or null if value does not exist in accordance with transactional rules.
455 * Value is taken from a snapshot, appropriate for an isolation level of the related transaction
456 *
457 * @param key the key
458 * @return the value, or null if not found
459 */
460 public V getFromSnapshot(K key) {
461 switch (transaction.isolationLevel) {
462 case READ_UNCOMMITTED: {
463 Snapshot<K,VersionedValue<V>> snapshot = getStatementSnapshot();
464 VersionedValue<V> data = map.get(snapshot.root.root, key);
465 if (data != null) {
466 return data.getCurrentValue();
467 }
468 return null;
469 }
470 case REPEATABLE_READ:
471 case SNAPSHOT:
472 case SERIALIZABLE:
473 if (transaction.hasChanges()) {
474 Snapshot<K,VersionedValue<V>> snapshot = getStatementSnapshot();
475 VersionedValue<V> data = map.get(snapshot.root.root, key);
476 if (data != null) {
477 long id = data.getOperationId();
478 if (id != 0L && transaction.transactionId == TransactionStore.getTransactionId(id)) {
479 return data.getCurrentValue();
480 }
481 }
482 }
483 //$FALL-THROUGH$
484 case READ_COMMITTED:
485 default:
486 Snapshot<K,VersionedValue<V>> snapshot = getSnapshot();
487 return getFromSnapshot(snapshot.root, snapshot.committingTransactions, key);
488 }
489 }
490
491 private V getFromSnapshot(RootReference<K, VersionedValue<V>> rootRef, BitSet committingTransactions, K key) {
492 VersionedValue<V> data = map.get(rootRef.root, key);
493 if (data == null) {
494 // doesn't exist
495 return null;
496 }
497 long id = data.getOperationId();
498 if (id != 0) {
499 int tx = TransactionStore.getTransactionId(id);
500 if (tx != transaction.transactionId && !committingTransactions.get(tx)) {
501 // added/modified/removed by uncommitted transaction, change should not be visible
502 return data.getCommittedValue();
503 }
504 }
505 // added/modified/removed by this transaction or another transaction which is committed by now
506 return data.getCurrentValue();
507 }
508
509 /**
510 * Get the value for the given key, or null if not found.
511 * Operation is performed on a snapshot of the map taken during this call.
512 *
513 * @param key the key
514 * @return the value, or null if not found
515 */
516 public V getImmediate(K key) {
517 return useSnapshot((rootReference, committedTransactions) ->
518 getFromSnapshot(rootReference, committedTransactions, key));
519 }
520
521 Snapshot<K,VersionedValue<V>> getSnapshot() {
522 return snapshot == null ? createSnapshot() : snapshot;
523 }
524
525 Snapshot<K,VersionedValue<V>> getStatementSnapshot() {
526 return statementSnapshot == null ? createSnapshot() : statementSnapshot;
527 }
528
529 void setStatementSnapshot(Snapshot<K,VersionedValue<V>> snapshot) {
530 statementSnapshot = snapshot;
531 }
532
533 void promoteSnapshot() {
534 if (snapshot == null) {
535 snapshot = statementSnapshot;
536 }
537 }
538
539 /**
540 * Create a new snapshot for this map.
541 *
542 * @return the snapshot
543 */
544 Snapshot<K,VersionedValue<V>> createSnapshot() {
545 return useSnapshot(Snapshot::new);
546 }
547
548 /**
549 * Gets a coherent picture of committing transactions and root reference,
550 * passes it to the specified function, and returns its result.
551 *
552 * @param <R> type of the result
553 *
554 * @param snapshotConsumer
555 * function to invoke on a snapshot
556 * @return function's result
557 */
558 <R> R useSnapshot(BiFunction<RootReference<K,VersionedValue<V>>, BitSet, R> snapshotConsumer) {
559 // The purpose of the following loop is to get a coherent picture
560 // of a state of two independent volatile / atomic variables,
561 // which they had at some recent moment in time.
562 // In order to get such a "snapshot", we wait for a moment of silence,
563 // when neither of the variables concurrently changes it's value.
564 AtomicReference<BitSet> holder = transaction.store.committingTransactions;
565 BitSet committingTransactions = holder.get();
566 while (true) {
567 BitSet prevCommittingTransactions = committingTransactions;
568 RootReference<K,VersionedValue<V>> root = map.getRoot();
569 committingTransactions = holder.get();
570 if (committingTransactions == prevCommittingTransactions) {
571 return snapshotConsumer.apply(root, committingTransactions);
572 }
573 }
574 }
575
576 /**
577 * Whether the map contains the key.
578 *
579 * @param key the key
580 * @return true if the map contains an entry for this key
581 * @throws ClassCastException if type of the specified key is not compatible with this map
582 */
583 @SuppressWarnings("unchecked")
584 @Override
585 public boolean containsKey(Object key) {
586 return getImmediate((K)key) != null;
587 }
588
589 /**
590 * Check if the row was deleted by this transaction.
591 *
592 * @param key the key
593 * @return {@code true} if it was
594 */
595 public boolean isDeletedByCurrentTransaction(K key) {
596 VersionedValue<V> data = map.get(key);
597 if (data != null) {
598 long id = data.getOperationId();
599 return id != 0 && TransactionStore.getTransactionId(id) == transaction.transactionId
600 && data.getCurrentValue() == null;
601 }
602 return false;
603 }
604
605 /**
606 * Whether the entry for this key was added or removed from this
607 * session.
608 *
609 * @param key the key
610 * @return true if yes
611 */
612 public boolean isSameTransaction(K key) {
613 VersionedValue<V> data = map.get(key);
614 if (data == null) {
615 // doesn't exist or deleted by a committed transaction
616 return false;
617 }
618 int tx = TransactionStore.getTransactionId(data.getOperationId());
619 return tx == transaction.transactionId;
620 }
621
622 /**
623 * Check whether this map is closed.
624 *
625 * @return true if closed
626 */
627 public boolean isClosed() {
628 return map.isClosed();
629 }
630
631 /**
632 * Clear the map.
633 */
634 @Override
635 public void clear() {
636 // TODO truncate transactionally?
637 map.clear();
638 hasChanges = true;
639 }
640
641 @Override
642 public Set<Entry<K, V>> entrySet() {
643 return new AbstractSet<Entry<K, V>>() {
644
645 @Override
646 public Iterator<Entry<K, V>> iterator() {
647 return entryIterator(null, null);
648 }
649
650 @Override
651 public int size() {
652 return TransactionMap.this.size();
653 }
654
655 @Override
656 public boolean contains(Object o) {
657 return TransactionMap.this.containsKey(o);
658 }
659
660 };
661 }
662
663 /**
664 * Get the first entry.
665 *
666 * @return the first entry, or null if empty
667 */
668 public Entry<K,V> firstEntry() {
669 return this.<Entry<K,V>>chooseIterator(null, null, false, true).fetchNext();
670 }
671
672 /**
673 * Get the first key.
674 *
675 * @return the first key, or null if empty
676 */
677 public K firstKey() {
678 return this.<K>chooseIterator(null, null, false, false).fetchNext();
679 }
680
681 /**
682 * Get the last entry.
683 *
684 * @return the last entry, or null if empty
685 */
686 public Entry<K,V> lastEntry() {
687 return this.<Entry<K,V>>chooseIterator(null, null, true, true).fetchNext();
688 }
689
690 /**
691 * Get the last key.
692 *
693 * @return the last key, or null if empty
694 */
695 public K lastKey() {
696 return this.<K>chooseIterator(null, null, true, false).fetchNext();
697 }
698
699 /**
700 * Get the entry with smallest key that is larger than the given key, or null if no
701 * such key exists.
702 *
703 * @param key the key (may not be null)
704 * @return the result
705 */
706 public Entry<K,V> higherEntry(K key) {
707 return higherLowerEntry(key, false);
708 }
709
710 /**
711 * Get the smallest key that is larger than the given key, or null if no
712 * such key exists.
713 *
714 * @param key the key (may not be null)
715 * @return the result
716 */
717 public K higherKey(K key) {
718 return higherLowerKey(key, false);
719 }
720
721 /**
722 * Get the entry with smallest key that is larger than or equal to this key,
723 * or null if no such key exists.
724 *
725 * @param key the key (may not be null)
726 * @return the result
727 */
728 public Entry<K,V> ceilingEntry(K key) {
729 return this.<Entry<K, V>>chooseIterator(key, null, false, true).fetchNext();
730 }
731
732 /**
733 * Get the smallest key that is larger than or equal to this key,
734 * or null if no such key exists.
735 *
736 * @param key the key (may not be null)
737 * @return the result
738 */
739 public K ceilingKey(K key) {
740 return this.<K>chooseIterator(key, null, false, false).fetchNext();
741 }
742
743 /**
744 * Get the entry with largest key that is smaller than or equal to this key,
745 * or null if no such key exists.
746 *
747 * @param key the key (may not be null)
748 * @return the result
749 */
750 public Entry<K,V> floorEntry(K key) {
751 return this.<Entry<K, V>>chooseIterator(key, null, true, true).fetchNext();
752 }
753
754 /**
755 * Get the largest key that is smaller than or equal to this key,
756 * or null if no such key exists.
757 *
758 * @param key the key (may not be null)
759 * @return the result
760 */
761 public K floorKey(K key) {
762 return this.<K>chooseIterator(key, null, true, false).fetchNext();
763 }
764
765 /**
766 * Get the entry with largest key that is smaller than the given key, or null if no
767 * such key exists.
768 *
769 * @param key the key (may not be null)
770 * @return the result
771 */
772 public Entry<K,V> lowerEntry(K key) {
773 return higherLowerEntry(key, true);
774 }
775
776 /**
777 * Get the largest key that is smaller than the given key, or null if no
778 * such key exists.
779 *
780 * @param key the key (may not be null)
781 * @return the result
782 */
783 public K lowerKey(K key) {
784 return higherLowerKey(key, true);
785 }
786
787 private Entry<K, V> higherLowerEntry(K key, boolean lower) {
788 TMIterator<K, V, Entry<K, V>> it = chooseIterator(key, null, lower, true);
789 Entry<K, V> result = it.fetchNext();
790 if (result != null && map.getKeyType().compare(key, result.getKey()) == 0) {
791 result = it.fetchNext();
792 }
793 return result;
794 }
795
796 private K higherLowerKey(K key, boolean lower) {
797 TMIterator<K, V, K> it = chooseIterator(key, null, lower, false);
798 K result = it.fetchNext();
799 if (result != null && map.getKeyType().compare(key, result) == 0) {
800 result = it.fetchNext();
801 }
802 return result;
803 }
804
805 /**
806 * Iterate over keys.
807 *
808 * @param from the first key to return
809 * @return the iterator
810 */
811 public Iterator<K> keyIterator(K from) {
812 return chooseIterator(from, null, false, false);
813 }
814
815 /**
816 * Iterate over keys in the specified order.
817 *
818 * @param from the first key to return
819 * @param reverse if true, iterate in reverse (descending) order
820 * @return the iterator
821 */
822 public TMIterator<K, V, K> keyIterator(K from, boolean reverse) {
823 return chooseIterator(from, null, reverse, false);
824 }
825
826 /**
827 * Iterate over keys.
828 *
829 * @param from the first key to return
830 * @param to the last key to return or null if there is no limit
831 * @return the iterator
832 */
833 public TMIterator<K, V, K> keyIterator(K from, K to) {
834 return chooseIterator(from, to, false, false);
835 }
836
837 /**
838 * Iterate over keys, including keys from uncommitted entries.
839 *
840 * @param from the first key to return
841 * @param to the last key to return or null if there is no limit
842 * @return the iterator
843 */
844 public TMIterator<K, V, K> keyIteratorUncommitted(K from, K to) {
845 return new ValidationIterator<>(this, from, to);
846 }
847
848 /**
849 * Iterate over entries.
850 *
851 * @param from the first key to return
852 * @param to the last key to return
853 * @return the iterator
854 */
855 public TMIterator<K, V, Map.Entry<K, V>> entryIterator(final K from, final K to) {
856 return chooseIterator(from, to, false, true);
857 }
858
859 private <X> TMIterator<K, V, X> chooseIterator(K from, K to, boolean reverse, boolean forEntries) {
860 switch (transaction.isolationLevel) {
861 case READ_UNCOMMITTED:
862 return new UncommittedIterator<>(this, from, to, reverse, forEntries);
863 case REPEATABLE_READ:
864 case SNAPSHOT:
865 case SERIALIZABLE:
866 if (hasChanges) {
867 return new RepeatableIterator<>(this, from, to, reverse, forEntries);
868 }
869 //$FALL-THROUGH$
870 case READ_COMMITTED:
871 default:
872 return new CommittedIterator<>(this, from, to, reverse, forEntries);
873 }
874 }
875
876 public Transaction getTransaction() {
877 return transaction;
878 }
879
880 public DataType<K> getKeyType() {
881 return map.getKeyType();
882 }
883
884 /**
885 * The iterator for read uncommitted isolation level. This iterator is also
886 * used for unique indexes.
887 *
888 * @param <K>
889 * the type of keys
890 * @param <X>
891 * the type of elements
892 */
893 private static class UncommittedIterator<K,V,X> extends TMIterator<K,V,X> {
894 UncommittedIterator(TransactionMap<K, V> transactionMap, K from, K to, boolean reverse, boolean forEntries) {
895 super(transactionMap, from, to, transactionMap.createSnapshot(), reverse, forEntries);
896 }
897
898 UncommittedIterator(TransactionMap<K, V> transactionMap, K from, K to, Snapshot<K, VersionedValue<V>> snapshot,
899 boolean reverse, boolean forEntries) {
900 super(transactionMap, from, to, snapshot, reverse, forEntries);
901 }
902
903 @Override
904 public final X fetchNext() {
905 while (cursor.hasNext()) {
906 K key = cursor.next();
907 VersionedValue<?> data = cursor.getValue();
908 if (data != null) {
909 Object currentValue = data.getCurrentValue();
910 if (currentValue != null || shouldIgnoreRemoval(data)) {
911 return toElement(key, currentValue);
912 }
913 }
914 }
915 return null;
916 }
917
918 boolean shouldIgnoreRemoval(VersionedValue<?> data) {
919 return false;
920 }
921 }
922
923
924 // This iterator should include all entries applicable for unique index validation,
925 // committed and otherwise, only excluding keys removed by the current transaction
926 // or by some other already committed (but not closed yet) transactions
927 private static final class ValidationIterator<K,V,X> extends UncommittedIterator<K,V,X> {
928 ValidationIterator(TransactionMap<K,V> transactionMap, K from, K to) {
929 super(transactionMap, from, to, transactionMap.createSnapshot(), false, false);
930 }
931
932 @Override
933 boolean shouldIgnoreRemoval(VersionedValue<?> data) {
934 assert data.getCurrentValue() == null;
935 long id = data.getOperationId();
936 if (id != 0) {
937 int tx = TransactionStore.getTransactionId(id);
938 return transactionId != tx && !committingTransactions.get(tx);
939 }
940 return false;
941 }
942 }
943
944 /**
945 * The iterator for read committed isolation level. Can also be used on
946 * higher levels when the transaction doesn't have own changes.
947 *
948 * @param <K>
949 * the type of keys
950 * @param <X>
951 * the type of elements
952 */
953 private static final class CommittedIterator<K,V,X> extends TMIterator<K,V,X> {
954 CommittedIterator(TransactionMap<K, V> transactionMap, K from, K to, boolean reverse, boolean forEntries) {
955 super(transactionMap, from, to, transactionMap.getSnapshot(), reverse, forEntries);
956 }
957
958 @Override
959 public X fetchNext() {
960 while (cursor.hasNext()) {
961 K key = cursor.next();
962 VersionedValue<?> data = cursor.getValue();
963 // If value doesn't exist or it was deleted by a committed transaction,
964 // or if value is a committed one, just return it.
965 if (data != null) {
966 long id = data.getOperationId();
967 if (id != 0) {
968 int tx = TransactionStore.getTransactionId(id);
969 if (tx != transactionId && !committingTransactions.get(tx)) {
970 // current value comes from another uncommitted transaction
971 // take committed value instead
972 Object committedValue = data.getCommittedValue();
973 if (committedValue == null) {
974 continue;
975 }
976 return toElement(key, committedValue);
977 }
978 }
979 Object currentValue = data.getCurrentValue();
980 if (currentValue != null) {
981 return toElement(key, currentValue);
982 }
983 }
984 }
985 return null;
986 }
987 }
988
989 /**
990 * The iterator for repeatable read and serializable isolation levels.
991 *
992 * @param <K>
993 * the type of keys
994 * @param <X>
995 * the type of elements
996 */
997 private static final class RepeatableIterator<K,V,X> extends TMIterator<K,V,X> {
998 private final DataType<K> keyType;
999
1000 private K snapshotKey;
1001
1002 private Object snapshotValue;
1003
1004 private final Cursor<K, VersionedValue<V>> uncommittedCursor;
1005
1006 private K uncommittedKey;
1007
1008 private V uncommittedValue;
1009
1010 RepeatableIterator(TransactionMap<K, V> transactionMap, K from, K to, boolean reverse, boolean forEntries) {
1011 super(transactionMap, from, to, transactionMap.getSnapshot(), reverse, forEntries);
1012 keyType = transactionMap.map.getKeyType();
1013 Snapshot<K,VersionedValue<V>> snapshot = transactionMap.getStatementSnapshot();
1014 uncommittedCursor = transactionMap.map.cursor(snapshot.root, from, to, reverse);
1015 }
1016
1017 @Override
1018 public X fetchNext() {
1019 X next = null;
1020 do {
1021 if (snapshotKey == null) {
1022 fetchSnapshot();
1023 }
1024 if (uncommittedKey == null) {
1025 fetchUncommitted();
1026 }
1027 if (snapshotKey == null && uncommittedKey == null) {
1028 break;
1029 }
1030 int cmp = snapshotKey == null ? 1 :
1031 uncommittedKey == null ? -1 :
1032 keyType.compare(snapshotKey, uncommittedKey);
1033 if (cmp < 0) {
1034 next = toElement(snapshotKey, snapshotValue);
1035 snapshotKey = null;
1036 break;
1037 }
1038 if (uncommittedValue != null) {
1039 // This entry was added / updated by this transaction, use the new value
1040 next = toElement(uncommittedKey, uncommittedValue);
1041 }
1042 if (cmp == 0) { // This entry was updated / deleted
1043 snapshotKey = null;
1044 }
1045 uncommittedKey = null;
1046 } while (next == null);
1047 return next;
1048 }
1049
1050 private void fetchSnapshot() {
1051 while (cursor.hasNext()) {
1052 K key = cursor.next();
1053 VersionedValue<?> data = cursor.getValue();
1054 // If value doesn't exist or it was deleted by a committed transaction,
1055 // or if value is a committed one, just return it.
1056 if (data != null) {
1057 Object value = data.getCommittedValue();
1058 long id = data.getOperationId();
1059 if (id != 0) {
1060 int tx = TransactionStore.getTransactionId(id);
1061 if (tx == transactionId || committingTransactions.get(tx)) {
1062 // value comes from this transaction or another committed transaction
1063 // take current value instead instead of committed one
1064 value = data.getCurrentValue();
1065 }
1066 }
1067 if (value != null) {
1068 snapshotKey = key;
1069 snapshotValue = value;
1070 return;
1071 }
1072 }
1073 }
1074 }
1075
1076 private void fetchUncommitted() {
1077 while (uncommittedCursor.hasNext()) {
1078 K key = uncommittedCursor.next();
1079 VersionedValue<V> data = uncommittedCursor.getValue();
1080 if (data != null) {
1081 long id = data.getOperationId();
1082 if (id != 0L && transactionId == TransactionStore.getTransactionId(id)) {
1083 uncommittedKey = key;
1084 uncommittedValue = data.getCurrentValue();
1085 return;
1086 }
1087 }
1088 }
1089 }
1090 }
1091
1092 public abstract static class TMIterator<K,V,X> implements Iterator<X> {
1093 final int transactionId;
1094
1095 final BitSet committingTransactions;
1096
1097 protected final Cursor<K, VersionedValue<V>> cursor;
1098
1099 private final boolean forEntries;
1100
1101 X current;
1102
1103 TMIterator(TransactionMap<K, V> transactionMap, K from, K to, Snapshot<K, VersionedValue<V>> snapshot,
1104 boolean reverse, boolean forEntries) {
1105 Transaction transaction = transactionMap.getTransaction();
1106 this.transactionId = transaction.transactionId;
1107 this.forEntries = forEntries;
1108 this.cursor = transactionMap.map.cursor(snapshot.root, from, to, reverse);
1109 this.committingTransactions = snapshot.committingTransactions;
1110 }
1111
1112 @SuppressWarnings("unchecked")
1113 final X toElement(K key, Object value) {
1114 return (X) (forEntries ? new AbstractMap.SimpleImmutableEntry<>(key, value) : key);
1115 }
1116
1117 /**
1118 * Fetches a next entry.
1119 *
1120 * This method cannot be used together with {@link #hasNext()} and
1121 * {@link #next()}.
1122 *
1123 * @return the next entry or {@code null}
1124 */
1125 public abstract X fetchNext();
1126
1127 @Override
1128 public final boolean hasNext() {
1129 return current != null || (current = fetchNext()) != null;
1130 }
1131
1132 @Override
1133 public final X next() {
1134 X result = current;
1135 if (result == null) {
1136 if ((result = fetchNext()) == null) {
1137 throw new NoSuchElementException();
1138 }
1139 } else {
1140 current = null;
1141 }
1142 return result;
1143 }
1144
1145 }
1146
1147 }