| 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.BitSet; |
| 9 |
import java.util.HashMap; |
| 10 |
import java.util.HashSet; |
| 11 |
import java.util.Iterator; |
| 12 |
import java.util.Map; |
| 13 |
import java.util.concurrent.atomic.AtomicLong; |
| 14 |
import org.h2.engine.IsolationLevel; |
| 15 |
import org.h2.mvstore.DataUtils; |
| 16 |
import org.h2.mvstore.MVMap; |
| 17 |
import org.h2.mvstore.MVStore; |
| 18 |
import org.h2.mvstore.RootReference; |
| 19 |
import org.h2.mvstore.type.DataType; |
| 20 |
import org.h2.value.VersionedValue; |
| 21 |
|
| 22 |
/** |
| 23 |
* A transaction. |
| 24 |
*/ |
| 25 |
public final class Transaction { |
| 26 |
|
| 27 |
/** |
| 28 |
* The status of a closed transaction (committed or rolled back). |
| 29 |
*/ |
| 30 |
public static final int STATUS_CLOSED = 0; |
| 31 |
|
| 32 |
/** |
| 33 |
* The status of an open transaction. |
| 34 |
*/ |
| 35 |
public static final int STATUS_OPEN = 1; |
| 36 |
|
| 37 |
/** |
| 38 |
* The status of a prepared transaction. |
| 39 |
*/ |
| 40 |
public static final int STATUS_PREPARED = 2; |
| 41 |
|
| 42 |
/** |
| 43 |
* The status of a transaction that has been logically committed or rather |
| 44 |
* marked as committed, because it might be still listed among prepared, |
| 45 |
* if it was prepared for commit. Undo log entries might still exists for it |
| 46 |
* and not all of it's changes within map's are re-written as committed yet. |
| 47 |
* Nevertheless, those changes should be already viewed by other |
| 48 |
* transactions as committed. |
| 49 |
* This transaction's id can not be re-used until all of the above is completed |
| 50 |
* and transaction is closed. |
| 51 |
* A transactions can be observed in this state when the store was |
| 52 |
* closed while the transaction was not closed yet. |
| 53 |
* When opening a store, such transactions will automatically |
| 54 |
* be processed and closed as committed. |
| 55 |
*/ |
| 56 |
public static final int STATUS_COMMITTED = 3; |
| 57 |
|
| 58 |
/** |
| 59 |
* The status of a transaction that currently in a process of rolling back |
| 60 |
* to a savepoint. |
| 61 |
*/ |
| 62 |
private static final int STATUS_ROLLING_BACK = 4; |
| 63 |
|
| 64 |
/** |
| 65 |
* The status of a transaction that has been rolled back completely, |
| 66 |
* but undo operations are not finished yet. |
| 67 |
*/ |
| 68 |
private static final int STATUS_ROLLED_BACK = 5; |
| 69 |
|
| 70 |
private static final String[] STATUS_NAMES = { |
| 71 |
"CLOSED", "OPEN", "PREPARED", "COMMITTED", "ROLLING_BACK", "ROLLED_BACK" |
| 72 |
}; |
| 73 |
/** |
| 74 |
* How many bits of the "operation id" we store in the transaction belong to the |
| 75 |
* log id (the rest belong to the transaction id). |
| 76 |
*/ |
| 77 |
static final int LOG_ID_BITS = 40; |
| 78 |
private static final int LOG_ID_BITS1 = LOG_ID_BITS + 1; |
| 79 |
private static final long LOG_ID_LIMIT = 1L << LOG_ID_BITS; |
| 80 |
private static final long LOG_ID_MASK = (1L << LOG_ID_BITS1) - 1; |
| 81 |
private static final int STATUS_BITS = 4; |
| 82 |
private static final int STATUS_MASK = (1 << STATUS_BITS) - 1; |
| 83 |
|
| 84 |
|
| 85 |
/** |
| 86 |
* The transaction store. |
| 87 |
*/ |
| 88 |
final TransactionStore store; |
| 89 |
|
| 90 |
/** |
| 91 |
* Listener for this transaction's rollback changes. |
| 92 |
*/ |
| 93 |
final TransactionStore.RollbackListener listener; |
| 94 |
|
| 95 |
/** |
| 96 |
* The transaction id. |
| 97 |
* More appropriate name for this field would be "slotId" |
| 98 |
*/ |
| 99 |
final int transactionId; |
| 100 |
|
| 101 |
/** |
| 102 |
* This is really a transaction identity, because it's not re-used. |
| 103 |
*/ |
| 104 |
final long sequenceNum; |
| 105 |
|
| 106 |
/* |
| 107 |
* Transaction state is an atomic composite field: |
| 108 |
* bit 45 : flag whether transaction had rollback(s) |
| 109 |
* bits 44-41 : status |
| 110 |
* bits 40 : overflow control bit, 1 indicates overflow |
| 111 |
* bits 39-0 : log id of the last entry in the undo log map |
| 112 |
*/ |
| 113 |
private final AtomicLong statusAndLogId; |
| 114 |
|
| 115 |
/** |
| 116 |
* Reference to a counter for an earliest store version used by this transaction. |
| 117 |
* Referenced version and all newer ones can not be discarded |
| 118 |
* at least until this transaction ends. |
| 119 |
*/ |
| 120 |
private MVStore.TxCounter txCounter; |
| 121 |
|
| 122 |
/** |
| 123 |
* Transaction name. |
| 124 |
*/ |
| 125 |
private String name; |
| 126 |
|
| 127 |
/** |
| 128 |
* Indicates whether this transaction was stored in preparedTransactions map |
| 129 |
*/ |
| 130 |
boolean wasStored; |
| 131 |
|
| 132 |
/** |
| 133 |
* How long to wait for blocking transaction to commit or rollback. |
| 134 |
*/ |
| 135 |
int timeoutMillis; |
| 136 |
|
| 137 |
/** |
| 138 |
* Identification of the owner of this transaction, |
| 139 |
* usually the owner is a database session. |
| 140 |
*/ |
| 141 |
private final int ownerId; |
| 142 |
|
| 143 |
/** |
| 144 |
* Blocking transaction, if any |
| 145 |
*/ |
| 146 |
private volatile Transaction blockingTransaction; |
| 147 |
|
| 148 |
/** |
| 149 |
* Map on which this transaction is blocked. |
| 150 |
*/ |
| 151 |
private String blockingMapName; |
| 152 |
|
| 153 |
/** |
| 154 |
* Key in blockingMap on which this transaction is blocked. |
| 155 |
*/ |
| 156 |
private Object blockingKey; |
| 157 |
|
| 158 |
/** |
| 159 |
* Whether other transaction(s) are waiting for this to close. |
| 160 |
*/ |
| 161 |
private volatile boolean notificationRequested; |
| 162 |
|
| 163 |
/** |
| 164 |
* RootReferences for undo log snapshots |
| 165 |
*/ |
| 166 |
private RootReference<Long,Record<?,?>>[] undoLogRootReferences; |
| 167 |
|
| 168 |
/** |
| 169 |
* Map of transactional maps for this transaction |
| 170 |
*/ |
| 171 |
private final Map<Integer, TransactionMap<?,?>> transactionMaps = new HashMap<>(); |
| 172 |
|
| 173 |
/** |
| 174 |
* The current isolation level. |
| 175 |
*/ |
| 176 |
final IsolationLevel isolationLevel; |
| 177 |
|
| 178 |
|
| 179 |
Transaction(TransactionStore store, int transactionId, long sequenceNum, int status, |
| 180 |
String name, long logId, int timeoutMillis, int ownerId, |
| 181 |
IsolationLevel isolationLevel, TransactionStore.RollbackListener listener) { |
| 182 |
this.store = store; |
| 183 |
this.transactionId = transactionId; |
| 184 |
this.sequenceNum = sequenceNum; |
| 185 |
this.statusAndLogId = new AtomicLong(composeState(status, logId, false)); |
| 186 |
this.name = name; |
| 187 |
setTimeoutMillis(timeoutMillis); |
| 188 |
this.ownerId = ownerId; |
| 189 |
this.isolationLevel = isolationLevel; |
| 190 |
this.listener = listener; |
| 191 |
} |
| 192 |
|
| 193 |
public int getId() { |
| 194 |
return transactionId; |
| 195 |
} |
| 196 |
|
| 197 |
public long getSequenceNum() { |
| 198 |
return sequenceNum; |
| 199 |
} |
| 200 |
|
| 201 |
public int getStatus() { |
| 202 |
return getStatus(statusAndLogId.get()); |
| 203 |
} |
| 204 |
|
| 205 |
RootReference<Long,Record<?,?>>[] getUndoLogRootReferences() { |
| 206 |
return undoLogRootReferences; |
| 207 |
} |
| 208 |
|
| 209 |
/** |
| 210 |
* Changes transaction status to a specified value |
| 211 |
* @param status to be set |
| 212 |
* @return transaction state as it was before status change |
| 213 |
*/ |
| 214 |
private long setStatus(int status) { |
| 215 |
while (true) { |
| 216 |
long currentState = statusAndLogId.get(); |
| 217 |
long logId = getLogId(currentState); |
| 218 |
int currentStatus = getStatus(currentState); |
| 219 |
boolean valid; |
| 220 |
switch (status) { |
| 221 |
case STATUS_ROLLING_BACK: |
| 222 |
valid = currentStatus == STATUS_OPEN; |
| 223 |
break; |
| 224 |
case STATUS_PREPARED: |
| 225 |
valid = currentStatus == STATUS_OPEN; |
| 226 |
break; |
| 227 |
case STATUS_COMMITTED: |
| 228 |
valid = currentStatus == STATUS_OPEN || |
| 229 |
currentStatus == STATUS_PREPARED || |
| 230 |
// this case is only possible if called |
| 231 |
// from endLeftoverTransactions() |
| 232 |
currentStatus == STATUS_COMMITTED; |
| 233 |
break; |
| 234 |
case STATUS_ROLLED_BACK: |
| 235 |
valid = currentStatus == STATUS_OPEN || |
| 236 |
currentStatus == STATUS_PREPARED || |
| 237 |
currentStatus == STATUS_ROLLING_BACK; |
| 238 |
break; |
| 239 |
case STATUS_CLOSED: |
| 240 |
valid = currentStatus == STATUS_COMMITTED || |
| 241 |
currentStatus == STATUS_ROLLED_BACK; |
| 242 |
break; |
| 243 |
case STATUS_OPEN: |
| 244 |
default: |
| 245 |
valid = false; |
| 246 |
break; |
| 247 |
} |
| 248 |
if (!valid) { |
| 249 |
throw DataUtils.newMVStoreException( |
| 250 |
DataUtils.ERROR_TRANSACTION_ILLEGAL_STATE, |
| 251 |
"Transaction was illegally transitioned from {0} to {1}", |
| 252 |
getStatusName(currentStatus), getStatusName(status)); |
| 253 |
} |
| 254 |
long newState = composeState(status, logId, hasRollback(currentState)); |
| 255 |
if (statusAndLogId.compareAndSet(currentState, newState)) { |
| 256 |
return currentState; |
| 257 |
} |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
/** |
| 262 |
* Determine if any database changes were made as part of this transaction. |
| 263 |
* |
| 264 |
* @return true if there are changes to commit, false otherwise |
| 265 |
*/ |
| 266 |
public boolean hasChanges() { |
| 267 |
return hasChanges(statusAndLogId.get()); |
| 268 |
} |
| 269 |
|
| 270 |
public void setName(String name) { |
| 271 |
checkNotClosed(); |
| 272 |
this.name = name; |
| 273 |
store.storeTransaction(this); |
| 274 |
} |
| 275 |
|
| 276 |
public String getName() { |
| 277 |
return name; |
| 278 |
} |
| 279 |
|
| 280 |
public int getBlockerId() { |
| 281 |
Transaction blocker = this.blockingTransaction; |
| 282 |
return blocker == null ? 0 : blocker.ownerId; |
| 283 |
} |
| 284 |
|
| 285 |
/** |
| 286 |
* Create a new savepoint. |
| 287 |
* |
| 288 |
* @return the savepoint id |
| 289 |
*/ |
| 290 |
public long setSavepoint() { |
| 291 |
return getLogId(); |
| 292 |
} |
| 293 |
|
| 294 |
/** |
| 295 |
* Returns whether statement dependencies are currently set. |
| 296 |
* |
| 297 |
* @return whether statement dependencies are currently set |
| 298 |
*/ |
| 299 |
public boolean hasStatementDependencies() { |
| 300 |
return !transactionMaps.isEmpty(); |
| 301 |
} |
| 302 |
|
| 303 |
/** |
| 304 |
* Returns the isolation level of this transaction. |
| 305 |
* |
| 306 |
* @return the isolation level of this transaction |
| 307 |
*/ |
| 308 |
public IsolationLevel getIsolationLevel() { |
| 309 |
return isolationLevel; |
| 310 |
} |
| 311 |
|
| 312 |
boolean isReadCommitted() { |
| 313 |
return isolationLevel == IsolationLevel.READ_COMMITTED; |
| 314 |
} |
| 315 |
|
| 316 |
/** |
| 317 |
* Whether this transaction has isolation level READ_COMMITTED or below. |
| 318 |
* @return true if isolation level is READ_COMMITTED or READ_UNCOMMITTED |
| 319 |
*/ |
| 320 |
public boolean allowNonRepeatableRead() { |
| 321 |
return isolationLevel.allowNonRepeatableRead(); |
| 322 |
} |
| 323 |
|
| 324 |
/** |
| 325 |
* Mark an entry into a new SQL statement execution within this transaction. |
| 326 |
* |
| 327 |
* @param maps |
| 328 |
* set of maps used by transaction or statement is about to be executed |
| 329 |
*/ |
| 330 |
@SuppressWarnings({"unchecked","rawtypes"}) |
| 331 |
public void markStatementStart(HashSet<MVMap<Object,VersionedValue<Object>>> maps) { |
| 332 |
markStatementEnd(); |
| 333 |
if (txCounter == null && store.store.isVersioningRequired()) { |
| 334 |
txCounter = store.store.registerVersionUsage(); |
| 335 |
} |
| 336 |
|
| 337 |
if (maps != null && !maps.isEmpty()) { |
| 338 |
// The purpose of the following loop is to get a coherent picture |
| 339 |
// In order to get such a "snapshot", we wait for a moment of silence, |
| 340 |
// when no new transaction were committed / closed. |
| 341 |
BitSet committingTransactions; |
| 342 |
do { |
| 343 |
committingTransactions = store.committingTransactions.get(); |
| 344 |
for (MVMap<Object,VersionedValue<Object>> map : maps) { |
| 345 |
TransactionMap<?,?> txMap = openMapX(map); |
| 346 |
txMap.setStatementSnapshot(new Snapshot(map.flushAndGetRoot(), committingTransactions)); |
| 347 |
} |
| 348 |
if (isReadCommitted()) { |
| 349 |
undoLogRootReferences = store.collectUndoLogRootReferences(); |
| 350 |
} |
| 351 |
} while (committingTransactions != store.committingTransactions.get()); |
| 352 |
// Now we have a snapshot, where each map RootReference point to state of the map, |
| 353 |
// undoLogRootReferences captures the state of undo logs |
| 354 |
// and committingTransactions mask tells us which of seemingly uncommitted changes |
| 355 |
// should be considered as committed. |
| 356 |
// Subsequent processing uses this snapshot info only. |
| 357 |
for (MVMap<Object,VersionedValue<Object>> map : maps) { |
| 358 |
TransactionMap<?,?> txMap = openMapX(map); |
| 359 |
txMap.promoteSnapshot(); |
| 360 |
} |
| 361 |
} |
| 362 |
} |
| 363 |
|
| 364 |
/** |
| 365 |
* Mark an exit from SQL statement execution within this transaction. |
| 366 |
*/ |
| 367 |
public void markStatementEnd() { |
| 368 |
if (allowNonRepeatableRead()) { |
| 369 |
releaseSnapshot(); |
| 370 |
} |
| 371 |
for (TransactionMap<?, ?> transactionMap : transactionMaps.values()) { |
| 372 |
transactionMap.setStatementSnapshot(null); |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
private void markTransactionEnd() { |
| 377 |
if (!allowNonRepeatableRead()) { |
| 378 |
releaseSnapshot(); |
| 379 |
} |
| 380 |
} |
| 381 |
|
| 382 |
private void releaseSnapshot() { |
| 383 |
transactionMaps.clear(); |
| 384 |
undoLogRootReferences = null; |
| 385 |
MVStore.TxCounter counter = txCounter; |
| 386 |
if (counter != null) { |
| 387 |
txCounter = null; |
| 388 |
store.store.deregisterVersionUsage(counter); |
| 389 |
} |
| 390 |
} |
| 391 |
|
| 392 |
/** |
| 393 |
* Add a log entry. |
| 394 |
* |
| 395 |
* @param logRecord to append |
| 396 |
* |
| 397 |
* @return key for the newly added undo log entry |
| 398 |
*/ |
| 399 |
long log(Record<?,?> logRecord) { |
| 400 |
long currentState = statusAndLogId.getAndIncrement(); |
| 401 |
long logId = getLogId(currentState); |
| 402 |
if (logId >= LOG_ID_LIMIT) { |
| 403 |
throw DataUtils.newMVStoreException( |
| 404 |
DataUtils.ERROR_TRANSACTION_TOO_BIG, |
| 405 |
"Transaction {0} has too many changes", |
| 406 |
transactionId); |
| 407 |
} |
| 408 |
int currentStatus = getStatus(currentState); |
| 409 |
checkOpen(currentStatus); |
| 410 |
long undoKey = store.addUndoLogRecord(transactionId, logId, logRecord); |
| 411 |
return undoKey; |
| 412 |
} |
| 413 |
|
| 414 |
/** |
| 415 |
* Remove the last log entry. |
| 416 |
*/ |
| 417 |
void logUndo() { |
| 418 |
long currentState = statusAndLogId.decrementAndGet(); |
| 419 |
long logId = getLogId(currentState); |
| 420 |
if (logId >= LOG_ID_LIMIT) { |
| 421 |
throw DataUtils.newMVStoreException( |
| 422 |
DataUtils.ERROR_TRANSACTION_CORRUPT, |
| 423 |
"Transaction {0} has internal error", |
| 424 |
transactionId); |
| 425 |
} |
| 426 |
int currentStatus = getStatus(currentState); |
| 427 |
checkOpen(currentStatus); |
| 428 |
store.removeUndoLogRecord(transactionId); |
| 429 |
} |
| 430 |
|
| 431 |
/** |
| 432 |
* Open a data map. |
| 433 |
* |
| 434 |
* @param <K> the key type |
| 435 |
* @param <V> the value type |
| 436 |
* @param name the name of the map |
| 437 |
* @return the transaction map |
| 438 |
*/ |
| 439 |
public <K, V> TransactionMap<K, V> openMap(String name) { |
| 440 |
return openMap(name, null, null); |
| 441 |
} |
| 442 |
|
| 443 |
/** |
| 444 |
* Open the map to store the data. |
| 445 |
* |
| 446 |
* @param <K> the key type |
| 447 |
* @param <V> the value type |
| 448 |
* @param name the name of the map |
| 449 |
* @param keyType the key data type |
| 450 |
* @param valueType the value data type |
| 451 |
* @return the transaction map |
| 452 |
*/ |
| 453 |
public <K, V> TransactionMap<K, V> openMap(String name, |
| 454 |
DataType<K> keyType, |
| 455 |
DataType<V> valueType) { |
| 456 |
MVMap<K, VersionedValue<V>> map = store.openVersionedMap(name, keyType, valueType); |
| 457 |
return openMapX(map); |
| 458 |
} |
| 459 |
|
| 460 |
/** |
| 461 |
* Open the transactional version of the given map. |
| 462 |
* |
| 463 |
* @param <K> the key type |
| 464 |
* @param <V> the value type |
| 465 |
* @param map the base map |
| 466 |
* @return the transactional map |
| 467 |
*/ |
| 468 |
@SuppressWarnings("unchecked") |
| 469 |
public <K, V> TransactionMap<K,V> openMapX(MVMap<K,VersionedValue<V>> map) { |
| 470 |
checkNotClosed(); |
| 471 |
int id = map.getId(); |
| 472 |
TransactionMap<K,V> transactionMap = (TransactionMap<K,V>)transactionMaps.get(id); |
| 473 |
if (transactionMap == null) { |
| 474 |
transactionMap = new TransactionMap<>(this, map); |
| 475 |
transactionMaps.put(id, transactionMap); |
| 476 |
} |
| 477 |
return transactionMap; |
| 478 |
} |
| 479 |
|
| 480 |
/** |
| 481 |
* Prepare the transaction. Afterwards, the transaction can only be |
| 482 |
* committed or completely rolled back. |
| 483 |
*/ |
| 484 |
public void prepare() { |
| 485 |
setStatus(STATUS_PREPARED); |
| 486 |
store.storeTransaction(this); |
| 487 |
} |
| 488 |
|
| 489 |
/** |
| 490 |
* Commit the transaction. Afterwards, this transaction is closed. |
| 491 |
*/ |
| 492 |
public void commit() { |
| 493 |
assert store.openTransactions.get().get(transactionId); |
| 494 |
markTransactionEnd(); |
| 495 |
Throwable ex = null; |
| 496 |
boolean hasChanges = false; |
| 497 |
int previousStatus = STATUS_OPEN; |
| 498 |
try { |
| 499 |
long state = setStatus(STATUS_COMMITTED); |
| 500 |
hasChanges = hasChanges(state); |
| 501 |
previousStatus = getStatus(state); |
| 502 |
if (hasChanges) { |
| 503 |
store.commit(this, previousStatus == STATUS_COMMITTED); |
| 504 |
} |
| 505 |
} catch (Throwable e) { |
| 506 |
ex = e; |
| 507 |
throw e; |
| 508 |
} finally { |
| 509 |
if (isActive(previousStatus)) { |
| 510 |
try { |
| 511 |
store.endTransaction(this, hasChanges); |
| 512 |
} catch (Throwable e) { |
| 513 |
if (ex == null) { |
| 514 |
throw e; |
| 515 |
} else { |
| 516 |
ex.addSuppressed(e); |
| 517 |
} |
| 518 |
} |
| 519 |
} |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
/** |
| 524 |
* Roll back to the given savepoint. This is only allowed if the |
| 525 |
* transaction is open. |
| 526 |
* |
| 527 |
* @param savepointId the savepoint id |
| 528 |
*/ |
| 529 |
public void rollbackToSavepoint(long savepointId) { |
| 530 |
long lastState = setStatus(STATUS_ROLLING_BACK); |
| 531 |
long logId = getLogId(lastState); |
| 532 |
boolean success; |
| 533 |
try { |
| 534 |
store.rollbackTo(this, logId, savepointId); |
| 535 |
} finally { |
| 536 |
notifyAllWaitingTransactions(); |
| 537 |
long expectedState = composeState(STATUS_ROLLING_BACK, logId, hasRollback(lastState)); |
| 538 |
long newState = composeState(STATUS_OPEN, savepointId, true); |
| 539 |
do { |
| 540 |
success = statusAndLogId.compareAndSet(expectedState, newState); |
| 541 |
} while (!success && statusAndLogId.get() == expectedState); |
| 542 |
} |
| 543 |
// this is moved outside of finally block to avert masking original exception, if any |
| 544 |
if (!success) { |
| 545 |
throw DataUtils.newMVStoreException( |
| 546 |
DataUtils.ERROR_TRANSACTION_ILLEGAL_STATE, |
| 547 |
"Transaction {0} concurrently modified while rollback to savepoint was in progress", |
| 548 |
transactionId); |
| 549 |
} |
| 550 |
} |
| 551 |
|
| 552 |
/** |
| 553 |
* Roll the transaction back. Afterwards, this transaction is closed. |
| 554 |
*/ |
| 555 |
public void rollback() { |
| 556 |
markTransactionEnd(); |
| 557 |
Throwable ex = null; |
| 558 |
int status = STATUS_OPEN; |
| 559 |
try { |
| 560 |
long lastState = setStatus(STATUS_ROLLED_BACK); |
| 561 |
status = getStatus(lastState); |
| 562 |
long logId = getLogId(lastState); |
| 563 |
if (logId > 0) { |
| 564 |
store.rollbackTo(this, logId, 0); |
| 565 |
} |
| 566 |
} catch (Throwable e) { |
| 567 |
status = getStatus(); |
| 568 |
if (isActive(status)) { |
| 569 |
ex = e; |
| 570 |
throw e; |
| 571 |
} |
| 572 |
} finally { |
| 573 |
try { |
| 574 |
if (isActive(status)) { |
| 575 |
store.endTransaction(this, true); |
| 576 |
} |
| 577 |
} catch (Throwable e) { |
| 578 |
if (ex == null) { |
| 579 |
throw e; |
| 580 |
} else { |
| 581 |
ex.addSuppressed(e); |
| 582 |
} |
| 583 |
} |
| 584 |
} |
| 585 |
} |
| 586 |
|
| 587 |
private static boolean isActive(int status) { |
| 588 |
return status != STATUS_CLOSED |
| 589 |
&& status != STATUS_COMMITTED |
| 590 |
&& status != STATUS_ROLLED_BACK; |
| 591 |
} |
| 592 |
|
| 593 |
/** |
| 594 |
* Get the list of changes, starting with the latest change, up to the |
| 595 |
* given savepoint (in reverse order than they occurred). The value of |
| 596 |
* the change is the value before the change was applied. |
| 597 |
* |
| 598 |
* @param savepointId the savepoint id, 0 meaning the beginning of the |
| 599 |
* transaction |
| 600 |
* @return the changes |
| 601 |
*/ |
| 602 |
public Iterator<TransactionStore.Change> getChanges(long savepointId) { |
| 603 |
return store.getChanges(this, getLogId(), savepointId); |
| 604 |
} |
| 605 |
|
| 606 |
/** |
| 607 |
* Sets the new lock timeout. |
| 608 |
* |
| 609 |
* @param timeoutMillis the new lock timeout in milliseconds |
| 610 |
*/ |
| 611 |
public void setTimeoutMillis(int timeoutMillis) { |
| 612 |
this.timeoutMillis = timeoutMillis > 0 ? timeoutMillis : store.timeoutMillis; |
| 613 |
} |
| 614 |
|
| 615 |
private long getLogId() { |
| 616 |
return getLogId(statusAndLogId.get()); |
| 617 |
} |
| 618 |
|
| 619 |
/** |
| 620 |
* Check whether this transaction is open. |
| 621 |
*/ |
| 622 |
private void checkOpen(int status) { |
| 623 |
if (status != STATUS_OPEN) { |
| 624 |
throw DataUtils.newMVStoreException( |
| 625 |
DataUtils.ERROR_TRANSACTION_ILLEGAL_STATE, |
| 626 |
"Transaction {0} has status {1}, not OPEN", transactionId, getStatusName(status)); |
| 627 |
} |
| 628 |
} |
| 629 |
|
| 630 |
/** |
| 631 |
* Check whether this transaction is open or prepared. |
| 632 |
*/ |
| 633 |
private void checkNotClosed() { |
| 634 |
if (getStatus() == STATUS_CLOSED) { |
| 635 |
throw DataUtils.newMVStoreException( |
| 636 |
DataUtils.ERROR_CLOSED, "Transaction {0} is closed", transactionId); |
| 637 |
} |
| 638 |
} |
| 639 |
|
| 640 |
/** |
| 641 |
* Transition this transaction into a closed state. |
| 642 |
*/ |
| 643 |
void closeIt() { |
| 644 |
transactionMaps.clear(); |
| 645 |
long lastState = setStatus(STATUS_CLOSED); |
| 646 |
store.store.deregisterVersionUsage(txCounter); |
| 647 |
if((hasChanges(lastState) || hasRollback(lastState))) { |
| 648 |
notifyAllWaitingTransactions(); |
| 649 |
} |
| 650 |
} |
| 651 |
|
| 652 |
private void notifyAllWaitingTransactions() { |
| 653 |
if (notificationRequested) { |
| 654 |
synchronized (this) { |
| 655 |
notifyAll(); |
| 656 |
} |
| 657 |
} |
| 658 |
} |
| 659 |
|
| 660 |
/** |
| 661 |
* Make this transaction to wait for the specified transaction to be closed, |
| 662 |
* because both of them try to modify the same map entry. |
| 663 |
* |
| 664 |
* @param toWaitFor transaction to wait for |
| 665 |
* @param mapName name of the map containing blocking entry |
| 666 |
* @param key of the blocking entry |
| 667 |
* @param timeoutMillis timeout in milliseconds, {@code -1} for default |
| 668 |
* @return true if other transaction was closed and this one can proceed, false if timed out |
| 669 |
*/ |
| 670 |
public boolean waitFor(Transaction toWaitFor, String mapName, Object key, int timeoutMillis) { |
| 671 |
blockingTransaction = toWaitFor; |
| 672 |
blockingMapName = mapName; |
| 673 |
blockingKey = key; |
| 674 |
if (isDeadlocked(toWaitFor)) { |
| 675 |
tryThrowDeadLockException(false); |
| 676 |
} |
| 677 |
boolean result = toWaitFor.waitForThisToEnd(timeoutMillis == -1 ? this.timeoutMillis : timeoutMillis, this); |
| 678 |
blockingMapName = null; |
| 679 |
blockingKey = null; |
| 680 |
blockingTransaction = null; |
| 681 |
return result; |
| 682 |
} |
| 683 |
|
| 684 |
private boolean isDeadlocked(Transaction toWaitFor) { |
| 685 |
// use transaction sequence No as a tie-breaker |
| 686 |
// the youngest transaction should be selected as a victim |
| 687 |
Transaction youngest = toWaitFor; |
| 688 |
int backstop = store.getMaxTransactionId(); |
| 689 |
for(Transaction tx = toWaitFor, nextTx; |
| 690 |
(nextTx = tx.blockingTransaction) != null && tx.getStatus() == Transaction.STATUS_OPEN && backstop > 0; |
| 691 |
tx = nextTx, --backstop) { |
| 692 |
|
| 693 |
if (nextTx.sequenceNum > youngest.sequenceNum) { |
| 694 |
youngest = nextTx; |
| 695 |
} |
| 696 |
|
| 697 |
if (nextTx == this) { |
| 698 |
if (youngest == this) { |
| 699 |
return true; |
| 700 |
} |
| 701 |
Transaction btx = youngest.blockingTransaction; |
| 702 |
if (btx != null) { |
| 703 |
youngest.setStatus(STATUS_ROLLING_BACK); |
| 704 |
btx.notifyAllWaitingTransactions(); |
| 705 |
return false; |
| 706 |
} |
| 707 |
} |
| 708 |
} |
| 709 |
return false; |
| 710 |
} |
| 711 |
|
| 712 |
private void tryThrowDeadLockException(boolean throwIt) { |
| 713 |
BitSet visited = new BitSet(); |
| 714 |
StringBuilder details = new StringBuilder( |
| 715 |
String.format("Transaction %d has been chosen as a deadlock victim. Details:%n", transactionId)); |
| 716 |
for (Transaction tx = this, nextTx; |
| 717 |
!visited.get(tx.transactionId) && (nextTx = tx.blockingTransaction) != null; tx = nextTx) { |
| 718 |
visited.set(tx.transactionId); |
| 719 |
details.append(String.format( |
| 720 |
"Transaction %d attempts to update map <%s> entry with key <%s> modified by transaction %s%n", |
| 721 |
tx.transactionId, tx.blockingMapName, tx.blockingKey, tx.blockingTransaction)); |
| 722 |
if (nextTx == this) { |
| 723 |
throwIt = true; |
| 724 |
} |
| 725 |
} |
| 726 |
if (throwIt) { |
| 727 |
throw DataUtils.newMVStoreException(DataUtils.ERROR_TRANSACTIONS_DEADLOCK, "{0}", details.toString()); |
| 728 |
} |
| 729 |
} |
| 730 |
|
| 731 |
private synchronized boolean waitForThisToEnd(int millis, Transaction waiter) { |
| 732 |
long until = System.currentTimeMillis() + millis; |
| 733 |
notificationRequested = true; |
| 734 |
long state; |
| 735 |
int status; |
| 736 |
while((status = getStatus(state = statusAndLogId.get())) != STATUS_CLOSED |
| 737 |
&& status != STATUS_ROLLED_BACK && !hasRollback(state)) { |
| 738 |
if (waiter.getStatus() != STATUS_OPEN) { |
| 739 |
waiter.tryThrowDeadLockException(true); |
| 740 |
} |
| 741 |
long dur = until - System.currentTimeMillis(); |
| 742 |
if(dur <= 0) { |
| 743 |
return false; |
| 744 |
} |
| 745 |
try { |
| 746 |
wait(dur); |
| 747 |
} catch (InterruptedException ex) { |
| 748 |
return false; |
| 749 |
} |
| 750 |
} |
| 751 |
return true; |
| 752 |
} |
| 753 |
|
| 754 |
/** |
| 755 |
* Remove the map. |
| 756 |
* |
| 757 |
* @param <K> the key type |
| 758 |
* @param <V> the value type |
| 759 |
* @param map the map |
| 760 |
*/ |
| 761 |
public <K, V> void removeMap(TransactionMap<K, V> map) { |
| 762 |
store.removeMap(map); |
| 763 |
} |
| 764 |
|
| 765 |
@Override |
| 766 |
public String toString() { |
| 767 |
return transactionId + "(" + sequenceNum + ") " + stateToString(); |
| 768 |
} |
| 769 |
|
| 770 |
private String stateToString() { |
| 771 |
return stateToString(statusAndLogId.get()); |
| 772 |
} |
| 773 |
|
| 774 |
private static String stateToString(long state) { |
| 775 |
return getStatusName(getStatus(state)) + (hasRollback(state) ? "<" : "") + " " + getLogId(state); |
| 776 |
} |
| 777 |
|
| 778 |
|
| 779 |
private static int getStatus(long state) { |
| 780 |
return (int)(state >>> LOG_ID_BITS1) & STATUS_MASK; |
| 781 |
} |
| 782 |
|
| 783 |
private static long getLogId(long state) { |
| 784 |
return state & LOG_ID_MASK; |
| 785 |
} |
| 786 |
|
| 787 |
private static boolean hasRollback(long state) { |
| 788 |
return (state & (1L << (STATUS_BITS + LOG_ID_BITS1))) != 0; |
| 789 |
} |
| 790 |
|
| 791 |
private static boolean hasChanges(long state) { |
| 792 |
return getLogId(state) != 0; |
| 793 |
} |
| 794 |
|
| 795 |
private static long composeState(int status, long logId, boolean hasRollback) { |
| 796 |
assert logId < LOG_ID_LIMIT : logId; |
| 797 |
assert (status & ~STATUS_MASK) == 0 : status; |
| 798 |
|
| 799 |
if (hasRollback) { |
| 800 |
status |= 1 << STATUS_BITS; |
| 801 |
} |
| 802 |
return ((long)status << LOG_ID_BITS1) | logId; |
| 803 |
} |
| 804 |
|
| 805 |
private static String getStatusName(int status) { |
| 806 |
return status >= 0 && status < STATUS_NAMES.length ? STATUS_NAMES[status] : "UNKNOWN_STATUS_" + status; |
| 807 |
} |
| 808 |
} |