Debian Codegraph @

src/main/org/h2/mvstore/tx/TransactionStore.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 java.nio.ByteBuffer;
9 import java.util.ArrayList;
10 import java.util.BitSet;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.concurrent.atomic.AtomicReference;
14 import java.util.concurrent.atomic.AtomicReferenceArray;
15 import org.h2.mvstore.Cursor;
16 import org.h2.mvstore.DataUtils;
17 import org.h2.mvstore.MVMap;
18 import org.h2.mvstore.MVStore;
19 import org.h2.mvstore.WriteBuffer;
20 import org.h2.mvstore.type.DataType;
21 import org.h2.mvstore.type.ObjectDataType;
22 import org.h2.util.StringUtils;
23 import org.h2.value.VersionedValue;
24
25 /**
26 * A store that supports concurrent MVCC read-committed transactions.
27 */
28 public class TransactionStore {
29
30 /**
31 * The store.
32 */
33 final MVStore store;
34
35 /**
36 * Default blocked transaction timeout
37 */
38 private final int timeoutMillis;
39
40 /**
41 * The persisted map of prepared transactions.
42 * Key: transactionId, value: [ status, name ].
43 */
44 private final MVMap<Integer, Object[]> preparedTransactions;
45
46 /**
47 * Undo logs.
48 * <p>
49 * If the first entry for a transaction doesn't have a logId
50 * of 0, then the transaction is partially committed (which means rollback
51 * is not possible). Log entries are written before the data is changed
52 * (write-ahead).
53 * <p>
54 * Key: opId, value: [ mapId, key, oldValue ].
55 */
56 @SuppressWarnings("unchecked")
57 final MVMap<Long,Object[]> undoLogs[] = new MVMap[MAX_OPEN_TRANSACTIONS];
58 private final MVMap.Builder<Long,Object[]> undoLogBuilder;
59
60 private final MVMap.Builder<Object, VersionedValue> mapBuilder;
61
62 /**
63 * This BitSet is used as vacancy indicator for transaction slots in transactions[].
64 * It provides easy way to find first unoccupied slot, and also allows for copy-on-write
65 * non-blocking updates.
66 */
67 final AtomicReference<VersionedBitSet> openTransactions = new AtomicReference<>(new VersionedBitSet());
68
69 /**
70 * This is intended to be the source of ultimate truth about transaction being committed.
71 * Once bit is set, corresponding transaction is logically committed,
72 * although it might be plenty of "uncommitted" entries in various maps
73 * and undo record are still around.
74 * Nevertheless, all of those should be considered by other transactions as committed.
75 */
76 final AtomicReference<BitSet> committingTransactions = new AtomicReference<>(new BitSet());
77
78 private boolean init;
79
80 /**
81 * Soft limit on the number of concurrently opened transactions.
82 * Not really needed but used by some test.
83 */
84 private int maxTransactionId = MAX_OPEN_TRANSACTIONS;
85
86 /**
87 * Array holding all open transaction objects.
88 * Position in array is "transaction id".
89 * VolatileReferenceArray would do the job here, but there is no such thing in Java yet
90 */
91 private final AtomicReferenceArray<Transaction> transactions =
92 new AtomicReferenceArray<>(MAX_OPEN_TRANSACTIONS + 1);
93
94 private static final String UNDO_LOG_NAME_PREFIX = "undoLog";
95 private static final char UNDO_LOG_COMMITTED = '-'; // must come before open in lexicographical order
96 private static final char UNDO_LOG_OPEN = '.';
97
98 /**
99 * Hard limit on the number of concurrently opened transactions
100 */
101 // TODO: introduce constructor parameter instead of a static field, driven by URL parameter
102 private static final int MAX_OPEN_TRANSACTIONS = 65535;
103
104
105 /**
106 * Generate a string used to name undo log map for a specific transaction.
107 * This name will contain transaction id and reflect the fact
108 * whether transaction is logically committed or not.
109 * This information might be used by recovery procedure after unclean shutdown
110 * (termination before transaction is fully committed).
111 *
112 * @param committed true if transaction is logically committed, false otherwise
113 * @param transactionId of the corresponding transaction
114 * @return undo log name
115 */
116 public static String getUndoLogName(boolean committed, int transactionId) {
117 return UNDO_LOG_NAME_PREFIX +
118 (committed ? UNDO_LOG_COMMITTED : UNDO_LOG_OPEN) +
119 (transactionId > 0 ? String.valueOf(transactionId) : "");
120 }
121
122 /**
123 * Create a new transaction store.
124 *
125 * @param store the store
126 */
127 public TransactionStore(MVStore store) {
128 this(store, new ObjectDataType(), 0);
129 }
130
131 /**
132 * Create a new transaction store.
133 *
134 * @param store the store
135 * @param dataType the data type for map keys and values
136 * @param timeoutMillis lock acquisition timeout in milliseconds, 0 means no wait
137 */
138 public TransactionStore(MVStore store, DataType dataType, int timeoutMillis) {
139 this.store = store;
140 this.timeoutMillis = timeoutMillis;
141 preparedTransactions = store.openMap("openTransactions",
142 new MVMap.Builder<Integer, Object[]>());
143 DataType oldValueType = new VersionedValueType(dataType);
144 ArrayType undoLogValueType = new ArrayType(new DataType[]{
145 new ObjectDataType(), dataType, oldValueType
146 });
147 undoLogBuilder = new MVMap.Builder<Long, Object[]>()
148 .singleWriter()
149 .valueType(undoLogValueType);
150 DataType vt = new VersionedValueType(dataType);
151 mapBuilder = new MVMap.Builder<Object, VersionedValue>()
152 .keyType(dataType).valueType(vt);
153 }
154
155 /**
156 * Initialize the store. This is needed before a transaction can be opened.
157 * If the transaction store is corrupt, this method can throw an exception,
158 * in which case the store can only be used for reading.
159 */
160 public void init() {
161 if (!init) {
162 for (String mapName : store.getMapNames()) {
163 if (mapName.startsWith(UNDO_LOG_NAME_PREFIX)) {
164 // Unexpectedly short name may be encountered upon upgrade from older version
165 // where undo log was persisted as a single map, remove it.
166 if (mapName.length() > UNDO_LOG_NAME_PREFIX.length()) {
167 boolean committed = mapName.charAt(UNDO_LOG_NAME_PREFIX.length()) == UNDO_LOG_COMMITTED;
168 if (store.hasData(mapName) || committed) {
169 int transactionId = StringUtils.parseUInt31(mapName, UNDO_LOG_NAME_PREFIX.length() + 1,
170 mapName.length());
171 VersionedBitSet openTxBitSet = openTransactions.get();
172 if (!openTxBitSet.get(transactionId)) {
173 Object[] data = preparedTransactions.get(transactionId);
174 int status;
175 String name;
176 if (data == null) {
177 status = Transaction.STATUS_OPEN;
178 name = null;
179 } else {
180 status = (Integer) data[0];
181 name = (String) data[1];
182 }
183 if (committed) {
184 status = Transaction.STATUS_COMMITTED;
185 }
186 MVMap<Long, Object[]> undoLog = store.openMap(mapName, undoLogBuilder);
187 undoLogs[transactionId] = undoLog;
188 Long lastUndoKey = undoLog.lastKey();
189 assert committed || lastUndoKey != null;
190 assert committed || getTransactionId(lastUndoKey) == transactionId;
191 long logId = lastUndoKey == null ? 0 : getLogId(lastUndoKey) + 1;
192 registerTransaction(transactionId, status, name, logId, timeoutMillis, 0,
193 ROLLBACK_LISTENER_NONE);
194 continue;
195 }
196 }
197 }
198
199 if (!store.isReadOnly()) {
200 store.removeMap(mapName);
201 }
202 }
203 }
204 init = true;
205 }
206 }
207
208 /**
209 * Commit all transactions that are in the committed state, and
210 * rollback all open transactions.
211 */
212 public void endLeftoverTransactions() {
213 List<Transaction> list = getOpenTransactions();
214 for (Transaction t : list) {
215 int status = t.getStatus();
216 if (status == Transaction.STATUS_COMMITTED) {
217 t.commit();
218 } else if (status != Transaction.STATUS_PREPARED) {
219 t.rollback();
220 }
221 }
222 }
223
224 /**
225 * Set the maximum transaction id, after which ids are re-used. If the old
226 * transaction is still in use when re-using an old id, the new transaction
227 * fails.
228 *
229 * @param max the maximum id
230 */
231 public void setMaxTransactionId(int max) {
232 DataUtils.checkArgument(max <= MAX_OPEN_TRANSACTIONS,
233 "Concurrent transactions limit is too high: {0}", max);
234 this.maxTransactionId = max;
235 }
236
237 /**
238 * Check whether a given map exists.
239 *
240 * @param name the map name
241 * @return true if it exists
242 */
243 public boolean hasMap(String name) {
244 return store.hasMap(name);
245 }
246
247 private static final int LOG_ID_BITS = Transaction.LOG_ID_BITS;
248 private static final long LOG_ID_MASK = (1L << LOG_ID_BITS) - 1;
249
250 /**
251 * Combine the transaction id and the log id to an operation id.
252 *
253 * @param transactionId the transaction id
254 * @param logId the log id
255 * @return the operation id
256 */
257 static long getOperationId(int transactionId, long logId) {
258 DataUtils.checkArgument(transactionId >= 0 && transactionId < (1 << (64 - LOG_ID_BITS)),
259 "Transaction id out of range: {0}", transactionId);
260 DataUtils.checkArgument(logId >= 0 && logId <= LOG_ID_MASK,
261 "Transaction log id out of range: {0}", logId);
262 return ((long) transactionId << LOG_ID_BITS) | logId;
263 }
264
265 /**
266 * Get the transaction id for the given operation id.
267 *
268 * @param operationId the operation id
269 * @return the transaction id
270 */
271 static int getTransactionId(long operationId) {
272 return (int) (operationId >>> LOG_ID_BITS);
273 }
274
275 /**
276 * Get the log id for the given operation id.
277 *
278 * @param operationId the operation id
279 * @return the log id
280 */
281 static long getLogId(long operationId) {
282 return operationId & LOG_ID_MASK;
283 }
284
285 /**
286 * Get the list of unclosed transactions that have pending writes.
287 *
288 * @return the list of transactions (sorted by id)
289 */
290 public List<Transaction> getOpenTransactions() {
291 if(!init) {
292 init();
293 }
294 ArrayList<Transaction> list = new ArrayList<>();
295 int transactionId = 0;
296 BitSet bitSet = openTransactions.get();
297 while((transactionId = bitSet.nextSetBit(transactionId + 1)) > 0) {
298 Transaction transaction = getTransaction(transactionId);
299 if(transaction != null) {
300 if(transaction.getStatus() != Transaction.STATUS_CLOSED) {
301 list.add(transaction);
302 }
303 }
304 }
305 return list;
306 }
307
308 /**
309 * Close the transaction store.
310 */
311 public synchronized void close() {
312 store.commit();
313 }
314
315 /**
316 * Begin a new transaction.
317 *
318 * @return the transaction
319 */
320 public Transaction begin() {
321 return begin(ROLLBACK_LISTENER_NONE, timeoutMillis, 0);
322 }
323
324 /**
325 * Begin a new transaction.
326 * @param listener to be notified in case of a rollback
327 * @param timeoutMillis to wait for a blocking transaction
328 * @param ownerId of the owner (Session?) to be reported by getBlockerId
329 * @return the transaction
330 */
331 public Transaction begin(RollbackListener listener, int timeoutMillis, int ownerId) {
332
333 if(timeoutMillis <= 0) {
334 timeoutMillis = this.timeoutMillis;
335 }
336 Transaction transaction = registerTransaction(0, Transaction.STATUS_OPEN, null, 0,
337 timeoutMillis, ownerId, listener);
338 return transaction;
339 }
340
341 private Transaction registerTransaction(int txId, int status, String name, long logId,
342 int timeoutMillis, int ownerId, RollbackListener listener) {
343 int transactionId;
344 long sequenceNo;
345 boolean success;
346 do {
347 VersionedBitSet original = openTransactions.get();
348 if (txId == 0) {
349 transactionId = original.nextClearBit(1);
350 } else {
351 transactionId = txId;
352 assert !original.get(transactionId);
353 }
354 if (transactionId > maxTransactionId) {
355 throw DataUtils.newIllegalStateException(
356 DataUtils.ERROR_TOO_MANY_OPEN_TRANSACTIONS,
357 "There are {0} open transactions",
358 transactionId - 1);
359 }
360 VersionedBitSet clone = original.clone();
361 clone.set(transactionId);
362 sequenceNo = clone.getVersion() + 1;
363 clone.setVersion(sequenceNo);
364 success = openTransactions.compareAndSet(original, clone);
365 } while(!success);
366
367 Transaction transaction = new Transaction(this, transactionId, sequenceNo, status, name, logId,
368 timeoutMillis, ownerId, listener);
369
370 assert transactions.get(transactionId) == null;
371 transactions.set(transactionId, transaction);
372
373 if (undoLogs[transactionId] == null) {
374 String undoName = getUndoLogName(status == Transaction.STATUS_COMMITTED, transactionId);
375 MVMap<Long, Object[]> undoLog = store.openMap(undoName, undoLogBuilder);
376 undoLogs[transactionId] = undoLog;
377 }
378 return transaction;
379 }
380
381 /**
382 * Store a transaction.
383 *
384 * @param t the transaction
385 */
386 void storeTransaction(Transaction t) {
387 if (t.getStatus() == Transaction.STATUS_PREPARED ||
388 t.getName() != null) {
389 Object[] v = { t.getStatus(), t.getName() };
390 preparedTransactions.put(t.getId(), v);
391 t.wasStored = true;
392 }
393 }
394
395 /**
396 * Add an undo log entry.
397 *
398 * @param transactionId id of the transaction
399 * @param logId sequential number of the log record within transaction
400 * @param undoLogRecord Object[mapId, key, previousValue]
401 * @return undo key
402 */
403 long addUndoLogRecord(int transactionId, long logId, Object[] undoLogRecord) {
404 MVMap<Long, Object[]> undoLog = undoLogs[transactionId];
405 long undoKey = getOperationId(transactionId, logId);
406 if (logId == 0 && !undoLog.isEmpty()) {
407 throw DataUtils.newIllegalStateException(
408 DataUtils.ERROR_TOO_MANY_OPEN_TRANSACTIONS,
409 "An old transaction with the same id " +
410 "is still open: {0}",
411 transactionId);
412 }
413 undoLog.append(undoKey, undoLogRecord);
414 return undoKey;
415 }
416
417 /**
418 * Remove an undo log entry.
419 * @param transactionId id of the transaction
420 */
421 void removeUndoLogRecord(int transactionId) {
422 undoLogs[transactionId].trimLast();
423 }
424
425 /**
426 * Remove the given map.
427 *
428 * @param <K> the key type
429 * @param <V> the value type
430 * @param map the map
431 */
432 <K, V> void removeMap(TransactionMap<K, V> map) {
433 store.removeMap(map.map, false);
434 }
435
436 /**
437 * Commit a transaction.
438 * @param t transaction to commit
439 * @param recovery if called during initial transaction recovery procedure
440 * therefore undo log is stored under "committed" name already
441 */
442 void commit(Transaction t, boolean recovery) {
443 if (!store.isClosed()) {
444 int transactionId = t.transactionId;
445 // this is an atomic action that causes all changes
446 // made by this transaction, to be considered as "committed"
447 flipCommittingTransactionsBit(transactionId, true);
448
449 CommitDecisionMaker commitDecisionMaker = new CommitDecisionMaker();
450 try {
451 MVMap<Long, Object[]> undoLog = undoLogs[transactionId];
452 if(!recovery) {
453 store.renameMap(undoLog, getUndoLogName(true, transactionId));
454 }
455 try {
456 Cursor<Long, Object[]> cursor = undoLog.cursor(null);
457 while (cursor.hasNext()) {
458 Long undoKey = cursor.next();
459 Object[] op = cursor.getValue();
460 int mapId = (Integer) op[0];
461 MVMap<Object, VersionedValue> map = openMap(mapId);
462 if (map != null) { // might be null if map was removed later
463 Object key = op[1];
464 commitDecisionMaker.setUndoKey(undoKey);
465 // although second parameter (value) is not really
466 // used by CommitDecisionMaker, MVRTreeMap has weird
467 // traversal logic based on it, and any non-null
468 // value will do, to signify update, not removal
469 map.operate(key, VersionedValue.DUMMY, commitDecisionMaker);
470 }
471 }
472 undoLog.clear();
473 } finally {
474 store.renameMap(undoLog, getUndoLogName(false, transactionId));
475 }
476 } finally {
477 flipCommittingTransactionsBit(transactionId, false);
478 }
479 }
480 }
481
482 private void flipCommittingTransactionsBit(int transactionId, boolean flag) {
483 boolean success;
484 do {
485 BitSet original = committingTransactions.get();
486 assert original.get(transactionId) != flag : flag ? "Double commit" : "Mysterious bit's disappearance";
487 BitSet clone = (BitSet) original.clone();
488 clone.set(transactionId, flag);
489 success = committingTransactions.compareAndSet(original, clone);
490 } while(!success);
491 }
492
493 /**
494 * Open the map with the given name.
495 *
496 * @param <K> the key type
497 * @param name the map name
498 * @param keyType the key type
499 * @param valueType the value type
500 * @return the map
501 */
502 <K> MVMap<K, VersionedValue> openMap(String name,
503 DataType keyType, DataType valueType) {
504 if (keyType == null) {
505 keyType = new ObjectDataType();
506 }
507 if (valueType == null) {
508 valueType = new ObjectDataType();
509 }
510 VersionedValueType vt = new VersionedValueType(valueType);
511 MVMap<K, VersionedValue> map;
512 MVMap.Builder<K, VersionedValue> builder =
513 new MVMap.Builder<K, VersionedValue>().
514 keyType(keyType).valueType(vt);
515 map = store.openMap(name, builder);
516 return map;
517 }
518
519 /**
520 * Open the map with the given id.
521 *
522 * @param mapId the id
523 * @return the map
524 */
525 MVMap<Object, VersionedValue> openMap(int mapId) {
526 MVMap<Object, VersionedValue> map = store.getMap(mapId);
527 if (map == null) {
528 String mapName = store.getMapName(mapId);
529 if (mapName == null) {
530 // the map was removed later on
531 return null;
532 }
533 map = store.openMap(mapName, mapBuilder);
534 }
535 return map;
536 }
537
538 /**
539 * End this transaction. Change status to CLOSED and vacate transaction slot.
540 * Will try to commit MVStore if autocommitDelay is 0 or if database is idle
541 * and amount of unsaved changes is sizable.
542 *
543 * @param t the transaction
544 * @param hasChanges true if transaction has done any updates
545 * (even if they are fully rolled back),
546 * false if it just performed a data access
547 */
548 void endTransaction(Transaction t, boolean hasChanges) {
549 t.closeIt();
550 int txId = t.transactionId;
551 transactions.set(txId, null);
552
553 boolean success;
554 do {
555 VersionedBitSet original = openTransactions.get();
556 assert original.get(txId);
557 VersionedBitSet clone = original.clone();
558 clone.clear(txId);
559 success = openTransactions.compareAndSet(original, clone);
560 } while(!success);
561
562 if (hasChanges) {
563 boolean wasStored = t.wasStored;
564 if (wasStored && !preparedTransactions.isClosed()) {
565 preparedTransactions.remove(txId);
566 }
567
568 if (wasStored || store.getAutoCommitDelay() == 0) {
569 store.tryCommit();
570 } else {
571 if (isUndoEmpty()) {
572 // to avoid having to store the transaction log,
573 // if there is no open transaction,
574 // and if there have been many changes, store them now
575 int unsaved = store.getUnsavedMemory();
576 int max = store.getAutoCommitMemory();
577 // save at 3/4 capacity
578 if (unsaved * 4 > max * 3) {
579 store.tryCommit();
580 }
581 }
582 }
583 }
584 }
585
586 private boolean isUndoEmpty() {
587 BitSet openTrans = openTransactions.get();
588 for (int i = openTrans.nextSetBit(0); i >= 0; i = openTrans.nextSetBit(i + 1)) {
589 MVMap<Long, Object[]> undoLog = undoLogs[i];
590 if (undoLog != null && !undoLog.isEmpty()) {
591 return false;
592 }
593 }
594 return true;
595 }
596
597 /**
598 * Get Transaction object for a transaction id.
599 *
600 * @param transactionId id for an open transaction
601 * @return Transaction object.
602 */
603 Transaction getTransaction(int transactionId) {
604 return transactions.get(transactionId);
605 }
606
607 /**
608 * Rollback to an old savepoint.
609 *
610 * @param t the transaction
611 * @param maxLogId the last log id
612 * @param toLogId the log id to roll back to
613 */
614 void rollbackTo(Transaction t, long maxLogId, long toLogId) {
615 int transactionId = t.getId();
616 MVMap<Long, Object[]> undoLog = undoLogs[transactionId];
617 RollbackDecisionMaker decisionMaker = new RollbackDecisionMaker(this, transactionId, toLogId, t.listener);
618 for (long logId = maxLogId - 1; logId >= toLogId; logId--) {
619 Long undoKey = getOperationId(transactionId, logId);
620 undoLog.operate(undoKey, null, decisionMaker);
621 decisionMaker.reset();
622 }
623 }
624
625 /**
626 * Get the changes of the given transaction, starting from the latest log id
627 * back to the given log id.
628 *
629 * @param t the transaction
630 * @param maxLogId the maximum log id
631 * @param toLogId the minimum log id
632 * @return the changes
633 */
634 Iterator<Change> getChanges(final Transaction t, final long maxLogId,
635 final long toLogId) {
636
637 final MVMap<Long, Object[]> undoLog = undoLogs[t.getId()];
638 return new Iterator<Change>() {
639
640 private long logId = maxLogId - 1;
641 private Change current;
642
643 private void fetchNext() {
644 int transactionId = t.getId();
645 while (logId >= toLogId) {
646 Long undoKey = getOperationId(transactionId, logId);
647 Object[] op = undoLog.get(undoKey);
648 logId--;
649 if (op == null) {
650 // partially rolled back: load previous
651 undoKey = undoLog.floorKey(undoKey);
652 if (undoKey == null || getTransactionId(undoKey) != transactionId) {
653 break;
654 }
655 logId = getLogId(undoKey);
656 continue;
657 }
658 int mapId = (int)op[0];
659 MVMap<Object, VersionedValue> m = openMap(mapId);
660 if (m != null) { // could be null if map was removed later on
661 VersionedValue oldValue = (VersionedValue) op[2];
662 current = new Change(m.getName(), op[1], oldValue == null ? null : oldValue.getCurrentValue());
663 return;
664 }
665 }
666 current = null;
667 }
668
669 @Override
670 public boolean hasNext() {
671 if(current == null) {
672 fetchNext();
673 }
674 return current != null;
675 }
676
677 @Override
678 public Change next() {
679 if(!hasNext()) {
680 throw DataUtils.newUnsupportedOperationException("no data");
681 }
682 Change result = current;
683 current = null;
684 return result;
685 }
686
687 @Override
688 public void remove() {
689 throw DataUtils.newUnsupportedOperationException("remove");
690 }
691
692 };
693 }
694
695 /**
696 * A change in a map.
697 */
698 public static class Change {
699
700 /**
701 * The name of the map where the change occurred.
702 */
703 public final String mapName;
704
705 /**
706 * The key.
707 */
708 public final Object key;
709
710 /**
711 * The value.
712 */
713 public final Object value;
714
715 public Change(String mapName, Object key, Object value) {
716 this.mapName = mapName;
717 this.key = key;
718 this.value = value;
719 }
720 }
721
722 /**
723 * This listener can be registered with the transaction to be notified of
724 * every compensating change during transaction rollback.
725 * Normally this is not required, if no external resources were modified,
726 * because state of all transactional maps will be restored automatically.
727 * Only state of external resources, possibly modified by triggers
728 * need to be restored.
729 */
730 public interface RollbackListener {
731
732 /**
733 * Notified of a single map change (add/update/remove)
734 * @param map modified
735 * @param key of the modified entry
736 * @param existingValue value in the map (null if delete is rolled back)
737 * @param restoredValue value to be restored (null if add is rolled back)
738 */
739 void onRollback(MVMap<Object,VersionedValue> map, Object key,
740 VersionedValue existingValue, VersionedValue restoredValue);
741 }
742
743 private static final RollbackListener ROLLBACK_LISTENER_NONE = new RollbackListener() {
744 @Override
745 public void onRollback(MVMap<Object, VersionedValue> map, Object key,
746 VersionedValue existingValue, VersionedValue restoredValue) {
747 // do nothing
748 }
749 };
750
751 /**
752 * A data type that contains an array of objects with the specified data
753 * types.
754 */
755 public static class ArrayType implements DataType {
756
757 private final int arrayLength;
758 private final DataType[] elementTypes;
759
760 ArrayType(DataType[] elementTypes) {
761 this.arrayLength = elementTypes.length;
762 this.elementTypes = elementTypes;
763 }
764
765 @Override
766 public int getMemory(Object obj) {
767 Object[] array = (Object[]) obj;
768 int size = 0;
769 for (int i = 0; i < arrayLength; i++) {
770 DataType t = elementTypes[i];
771 Object o = array[i];
772 if (o != null) {
773 size += t.getMemory(o);
774 }
775 }
776 return size;
777 }
778
779 @Override
780 public int compare(Object aObj, Object bObj) {
781 if (aObj == bObj) {
782 return 0;
783 }
784 Object[] a = (Object[]) aObj;
785 Object[] b = (Object[]) bObj;
786 for (int i = 0; i < arrayLength; i++) {
787 DataType t = elementTypes[i];
788 int comp = t.compare(a[i], b[i]);
789 if (comp != 0) {
790 return comp;
791 }
792 }
793 return 0;
794 }
795
796 @Override
797 public void read(ByteBuffer buff, Object[] obj,
798 int len, boolean key) {
799 for (int i = 0; i < len; i++) {
800 obj[i] = read(buff);
801 }
802 }
803
804 @Override
805 public void write(WriteBuffer buff, Object[] obj,
806 int len, boolean key) {
807 for (int i = 0; i < len; i++) {
808 write(buff, obj[i]);
809 }
810 }
811
812 @Override
813 public void write(WriteBuffer buff, Object obj) {
814 Object[] array = (Object[]) obj;
815 for (int i = 0; i < arrayLength; i++) {
816 DataType t = elementTypes[i];
817 Object o = array[i];
818 if (o == null) {
819 buff.put((byte) 0);
820 } else {
821 buff.put((byte) 1);
822 t.write(buff, o);
823 }
824 }
825 }
826
827 @Override
828 public Object read(ByteBuffer buff) {
829 Object[] array = new Object[arrayLength];
830 for (int i = 0; i < arrayLength; i++) {
831 DataType t = elementTypes[i];
832 if (buff.get() == 1) {
833 array[i] = t.read(buff);
834 }
835 }
836 return array;
837 }
838
839 }
840 }