Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*-
   * See the file LICENSE for redistribution information.
   *
   * Copyright (c) 2002, 2013 Oracle and/or its affiliates.  All rights reserved.
   *
   */
  
  package com.sleepycat.je;
  
 
The Transaction object is the handle for a transaction. Methods off the transaction handle are used to configure, abort and commit the transaction. Transaction handles are provided to other Berkeley DB methods in order to transactionally protect those operations.

A single Transaction may be used to protect operations for any number of Databases in a given environment. However, a single Transaction may not be used for operations in more than one distinct environment.

Transaction handles are free-threaded; transactions handles may be used concurrently by multiple threads. Once the Transaction.abort or Transaction.commit method is called, the handle may not be accessed again, regardless of the success or failure of the method, with one exception: the abort method may be called any number of times to simplify error handling.

To obtain a transaction with default attributes:

     Transaction txn = myEnvironment.beginTransaction(null, null);
 

To customize the attributes of a transaction:

     TransactionConfig config = new TransactionConfig();
     config.setReadUncommitted(true);
     Transaction txn = myEnvironment.beginTransaction(null, config);
 
 
 public class Transaction {

    
The current state of the transaction.

Since:
5.0.48
 
     public enum State {

        
The transaction has not been committed or aborted, and can be used for performing operations. This state is also indicated if Transaction.isValid() returns true. For all other states, Transaction.isValid() will return false.
 
         OPEN,

        
An exception was thrown by the commit method due to an error that occurred while attempting to make the transaction durable. The transaction may or may not be locally durable, according to the local SyncPolicy requested.

This is an unusual situation and is normally due to a system failure, storage device failure, disk full condition, thread interrupt, or a bug of some kind. When a transaction is in this state, the Environment will have been invalidated by the error.

In a replicated environment, a transaction in this state is not transferred to replicas. If it turns out that the transaction is indeed durable, it will be transferred to replicas via normal replication mechanisms when the Environment is re-opened.

When the commit method throws an exception and the transaction is in the POSSIBLY_COMMITTED state, some applications may wish to perform a data query to determine whether the transaction is durable or not. Note that in the event of a system level failure, the reads themselves may be unreliable, e.g. the data may be in the file system cache but not on disk. Other applications may wish to repeat the transaction unconditionally, after resolving the error condition, particularly when the set of operations in the transaction is designed to be idempotent.

 
         POSSIBLY_COMMITTED,

        
The transaction has been committed and is locally durable according to the local SyncPolicy requested.

Note that a transaction may be in this state even when an exception is thrown by the commit method. For example, in a replicated environment, an com.sleepycat.je.rep.InsufficientAcksException may be thrown after the transaction is committed locally.

        COMMITTED,

        
The transaction has been invalidated by an exception and cannot be committed. See OperationFailureException for a description of how a transaction can become invalid. The application is responsible for aborting the transaction.
        MUST_ABORT,

        
The transaction has been aborted.
        ABORTED,
    }
    private Txn txn;
    private final Environment env;
    private final long id;
    private String name;
    /*
     * It's set upon a successful updating replicated commit and identifies the
     * VLSN associated with the commit entry.
     */
    private CommitToken commitToken = null;
    /*
     * Is null until setTxnNull is called, and then it holds the state at the
     * time the txn was closed.
     */
    private State finalState = null;
    /*
     * Commit and abort methods are synchronized to prevent them from running
     * concurrently with operations using the transaction.  See
     * Cursor.getTxnSynchronizer.
     */

    
For internal use.

Hidden:
Creates a transaction.
    protected Transaction(Environment envTxn txn) {
        this. = env;
        this. = txn;
        txn.setTransaction(this);
        /*
         * Copy the id to this wrapper object so the id will be available
         * after the transaction is closed and the txn field is nulled.
         */
        this. = txn.getId();
    }

    
Cause an abnormal termination of the transaction.

The log is played backward, and any necessary undo operations are done. Before Transaction.abort returns, any locks held by the transaction will have been released.

In the case of nested transactions, aborting a parent transaction causes all children (unresolved or not) of the parent transaction to be aborted.

All cursors opened within the transaction must be closed before the transaction is aborted.

After this method has been called, regardless of its return, the Transaction handle may not be accessed again, with one exception: the abort method itself may be called any number of times to simplify error handling.

Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if the environment has been closed, or cursors associated with the transaction are still open.
    public synchronized void abort()
        throws DatabaseException {
        try {
            /*
             * If the transaction is already closed, do nothing.  Do not call
             * checkOpen in order to support any number of calls to abort().
             */
            if ( == null) {
                return;
            }
            /*
             * Check env only after checking for closed txn, to mimic close()
             * behavior for Cursors, etc, and avoid unnecessary exception
             * handling.  [#21264]
             */
            checkEnv();
            .removeReferringHandle(this);
            .abort();
            /* Remove reference to internal txn, so we can reclaim memory. */
            setTxnNull();
        } catch (Error E) {
            DbInternal.getEnvironmentImpl().invalidate(E);
            throw E;
        }
    }

    
Return the transaction's unique ID.

Returns:
The transaction's unique ID.
    public long getId() {
        return ;
    }

    
This method is intended for use with a replicated environment.

It returns the commitToken associated with a successful replicated commit. A null value is returned if the txn was not associated with a replicated environment, or the txn did not result in any changes to the environment. This method should only be called after the transaction has finished.

This method is typically used in conjunction with the CommitPointConsistencyPolicy.

Returns:
the token used to identify the replicated commit. Return null if the transaction has aborted, or has committed without making any updates.
Throws:
java.lang.IllegalStateException if the method is called before the transaction has committed or aborted.
See also:
com.sleepycat.je.rep.CommitPointConsistencyPolicy
    public CommitToken getCommitToken() 
        throws IllegalStateException {
        if ( == null) {
            /* 
             * The commit token is only legitimate after the transaction is
             * closed. A null txn field means the transaction is closed.
             */
            return 
        }
        
        throw new IllegalStateException
           ("This transaction is still in progress and a commit token " +
            "is not available");
    }

    
End the transaction. If the environment is configured for synchronous commit, the transaction will be committed synchronously to stable storage before the call returns. This means the transaction will exhibit all of the ACID (atomicity, consistency, isolation, and durability) properties.

If the environment is not configured for synchronous commit, the commit will not necessarily have been committed to stable storage before the call returns. This means the transaction will exhibit the ACI (atomicity, consistency, and isolation) properties, but not D (durability); that is, database integrity will be maintained, but it is possible this transaction may be undone during recovery.

All cursors opened within the transaction must be closed before the transaction is committed.

If the method encounters an error, the transaction will have been aborted when the call returns.

After this method has been called, regardless of its return, the Transaction handle may not be accessed again, with one exception: the abort method may be called any number of times to simplify error handling.

Throws:
com.sleepycat.je.rep.InsufficientReplicasException if the master in a replicated environment could not contact a quorum of replicas as determined by the Durability.ReplicaAckPolicy.
com.sleepycat.je.rep.InsufficientAcksException if the master in a replicated environment did not receive enough replica acknowledgments, although the commit succeeded locally.
com.sleepycat.je.rep.ReplicaWriteException if a write operation was performed with this transaction, but this node is now a Replica.
OperationFailureException if this exception occurred earlier and caused the transaction to be invalidated.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if the transaction or environment has been closed, or cursors associated with the transaction are still open.
    public synchronized void commit()
        throws DatabaseException {
        try {
            checkEnv();
            checkOpen();
            .removeReferringHandle(this);
            .commit();
             = .getCommitToken();
            /* Remove reference to internal txn, so we can reclaim memory. */
            setTxnNull();
        } catch (Error E) {
            DbInternal.getEnvironmentImpl().invalidate(E);
            throw E;
        }
    }

    
End the transaction using the specified durability requirements. This requirement overrides any default durability requirements associated with the environment. If the durability requirements cannot be satisfied, an exception is thrown to describe the problem. Please see Durability for specific exceptions that could result when the durability requirements cannot be satisfied.

All cursors opened within the transaction must be closed before the transaction is committed.

If the method encounters an error, the transaction will have been aborted when the call returns.

After this method has been called, regardless of its return, the Transaction handle may not be accessed again, with one exception: the abort method may be called any number of times to simplify error handling.

Parameters:
durability the durability requirements for this transaction
Throws:
com.sleepycat.je.rep.InsufficientReplicasException if the master in a replicated environment could not contact enough replicas to initiate the commit.
com.sleepycat.je.rep.InsufficientAcksException if the master in a replicated environment did not receive enough replica acknowledgments, althought the commit succeeded locally.
com.sleepycat.je.rep.ReplicaWriteException if a write operation was performed with this transaction, but this node is now a Replica.
OperationFailureException if this exception occurred earlier and caused the transaction to be invalidated.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if the transaction or environment has been closed, or cursors associated with the transaction are still open.
java.lang.IllegalArgumentException if an invalid parameter is specified.
    public synchronized void commit(Durability durability)
        throws DatabaseException {
        doCommit(durabilityfalse /* explicitSync */);
    }

    
End the transaction, writing to stable storage and committing synchronously. This means the transaction will exhibit all of the ACID (atomicity, consistency, isolation, and durability) properties.

This behavior is the default for database environments unless otherwise configured using the EnvironmentMutableConfig.setTxnNoSync(boolean) method. This behavior may also be set for a single transaction using the Environment.beginTransaction(com.sleepycat.je.Transaction,com.sleepycat.je.TransactionConfig) method. Any value specified to this method overrides both of those settings.

All cursors opened within the transaction must be closed before the transaction is committed.

If the method encounters an error, the transaction will have been aborted when the call returns.

After this method has been called, regardless of its return, the Transaction handle may not be accessed again, with one exception: the abort method may be called any number of times to simplify error handling.

Throws:
com.sleepycat.je.rep.InsufficientReplicasException if the master in a replicated environment could not contact enough replicas to initiate the commit.
com.sleepycat.je.rep.InsufficientAcksException if the master in a replicated environment did not receive enough replica acknowledgments, althought the commit succeeded locally.
com.sleepycat.je.rep.ReplicaWriteException if a write operation was performed with this transaction, but this node is now a Replica.
OperationFailureException if this exception occurred earlier and caused the transaction to be invalidated.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if the transaction or environment has been closed, or cursors associated with the transaction are still open.
    public synchronized void commitSync()
        throws DatabaseException {
        doCommit(.true /* explicitSync */);
    }

    
End the transaction, not writing to stable storage and not committing synchronously. This means the transaction will exhibit the ACI (atomicity, consistency, and isolation) properties, but not D (durability); that is, database integrity will be maintained, but it is possible this transaction may be undone during recovery.

This behavior may be set for a database environment using the EnvironmentMutableConfig.setTxnNoSync(boolean) method or for a single transaction using the Environment.beginTransaction method. Any value specified to this method overrides both of those settings.

All cursors opened within the transaction must be closed before the transaction is committed.

If the method encounters an error, the transaction will have been aborted when the call returns.

After this method has been called, regardless of its return, the Transaction handle may not be accessed again, with one exception: the abort method may be called any number of times to simplify error handling.

Throws:
com.sleepycat.je.rep.InsufficientReplicasException if the master in a replicated environment could not contact enough replicas to initiate the commit.
com.sleepycat.je.rep.InsufficientAcksException if the master in a replicated environment did not receive enough replica acknowledgments, althought the commit succeeded locally.
com.sleepycat.je.rep.ReplicaWriteException if a write operation was performed with this transaction, but this node is now a Replica.
OperationFailureException if this exception occurred earlier and caused the transaction to be invalidated.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if the transaction or environment has been closed, or cursors associated with the transaction are still open.
    public synchronized void commitNoSync()
        throws DatabaseException {
        doCommit(.true /* explicitSync */);
    }

    
End the transaction, writing to stable storage but not committing synchronously. This means the transaction will exhibit the ACI (atomicity, consistency, and isolation) properties, but not D (durability); that is, database integrity will be maintained, but it is possible this transaction may be undone during recovery.

This behavior is the default for database environments unless otherwise configured using the EnvironmentMutableConfig.setTxnNoSync(boolean) method. This behavior may also be set for a single transaction using the Environment.beginTransaction(com.sleepycat.je.Transaction,com.sleepycat.je.TransactionConfig) method. Any value specified to this method overrides both of those settings.

All cursors opened within the transaction must be closed before the transaction is committed.

If the method encounters an error, the transaction will have been aborted when the call returns.

After this method has been called, regardless of its return, the Transaction handle may not be accessed again, with one exception: the abort method may be called any number of times to simplify error handling.

Throws:
com.sleepycat.je.rep.InsufficientReplicasException if the master in a replicated environment could not contact enough replicas to initiate the commit.
com.sleepycat.je.rep.InsufficientAcksException if the master in a replicated environment did not receive enough replica acknowledgments, althought the commit succeeded locally.
com.sleepycat.je.rep.ReplicaWriteException if a write operation was performed with this transaction, but this node is now a Replica.
OperationFailureException if this exception occurred earlier and caused the transaction to be invalidated.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if the transaction or environment has been closed, or cursors associated with the transaction are still open.
    public synchronized void commitWriteNoSync()
        throws DatabaseException {
        doCommit(.true /* explicitSync */);
    }

    
For internal use.

Hidden:
    public boolean getPrepared() {
        return .getPrepared();
    }

    
Perform error checking and invoke the commit on Txn.

Parameters:
durability the durability to use for the commit
explicitSync true if the method was invoked from one of the sync-specific APIs, false if durability was used explicitly. This parameter exists solely to support mixed mode api usage checks.
Throws:
java.lang.IllegalArgumentException via commit(Durability)
    private void doCommit(Durability durabilityboolean explicitSync) {
        try {
            checkEnv();
            checkOpen();
            .removeReferringHandle(this);
            if (explicitSync) {
                /* A sync-specific api was invoked. */
                if (.getExplicitDurabilityConfigured()) {
                    throw new IllegalArgumentException
                        ("Mixed use of deprecated durability API for the " +
                         "transaction commit with the new durability API for" +
                         " TransactionConfig or MutableEnvironmentConfig");
                }
            } else if (.getExplicitSyncConfigured()) {
                /* Durability was explicitly configured for commit */
                throw new IllegalArgumentException
                    ("Mixed use of new durability API for the " +
                      "transaction commit with deprecated durability API for" +
                      " TransactionConfig or MutableEnvironmentConfig");
            }
            .commit(durability);
             = .getCommitToken();
            /* Remove reference to internal txn, so we can reclaim memory. */
            setTxnNull();
        } catch (Error E) {
            DbInternal.getEnvironmentImpl().invalidate(E);
            throw E;
        }
    }

    
Returns the timeout value for the transaction lifetime.

If setTxnTimeout(long,java.util.concurrent.TimeUnit) has not been called to configure the timeout, the environment configuration value (EnvironmentConfig.TXN_TIMEOUT )is returned.

Parameters:
unit the TimeUnit of the returned value. May not be null.
Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if the transaction or environment has been closed.
java.lang.IllegalArgumentException if the unit is null.
Since:
4.0
    public long getTxnTimeout(TimeUnit unit)
        throws EnvironmentFailureException,
               IllegalStateException,
               IllegalArgumentException {
        checkEnv();
        checkOpen();
        return PropUtil.millisToDuration((int.getTxnTimeout(), unit);
    }

    
Configures the timeout value for the transaction lifetime.

If the transaction runs longer than this time, the transaction may throw TransactionTimeoutException.

Transaction timeouts are checked whenever a thread of control blocks on a lock or when deadlock detection is performed. For this reason, the accuracy of the timeout depends on the length of the lock timeout and how often deadlock detection is performed.

Parameters:
timeOut The timeout value for the transaction lifetime. A value of 0 disables timeouts for the transaction, meaning that no limit on the duration of the transaction is enforced.
unit the TimeUnit of the timeOut value. May be null only if timeOut is zero.
Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if the transaction or environment has been closed.
java.lang.IllegalArgumentException if timeOut or unit is invalid.
Since:
4.0
    public void setTxnTimeout(long timeOutTimeUnit unit)
        throws IllegalArgumentExceptionDatabaseException {
        checkEnv();
        checkOpen();
        .setTxnTimeout(PropUtil.durationToMillis(timeOutunit));
    }

    
Configures the timeout value for the transaction lifetime, with the timeout value specified in microseconds. This method is equivalent to:
setTxnTimeout(long, TimeUnit.MICROSECONDS);

Deprecated:
as of 4.0, replaced by setTxnTimeout(long,java.util.concurrent.TimeUnit).
    public void setTxnTimeout(long timeOut)
        throws IllegalArgumentExceptionDatabaseException {
        setTxnTimeout(timeOut.);
    }

    
Returns the lock request timeout value for the transaction.

If setLockTimeout(long,java.util.concurrent.TimeUnit) has not been called to configure the timeout, the environment configuration value (EnvironmentConfig.LOCK_TIMEOUT) is returned.

Parameters:
unit the TimeUnit of the returned value. May not be null.
Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if the transaction or environment has been closed.
java.lang.IllegalArgumentException if the unit is null.
Since:
4.0
    public long getLockTimeout(TimeUnit unit)
        throws EnvironmentFailureException,
               IllegalStateException,
               IllegalArgumentException {
        checkEnv();
        checkOpen();
        return PropUtil.millisToDuration((int.getLockTimeout(), unit);
    }

    
Configures the lock request timeout value for the transaction.

If a lock request cannot be granted in this time, the transaction may throw LockTimeoutException.

This method may be called at any time during the life of the application.

Parameters:
timeOut The lock request timeout value for this transaction. A value of zero turns off transaction timeouts, meaning that no lock wait time limit is enforced and a deadlocked operation will block indefinitely. We strongly recommend that a large timeout value, rather than a zero value, is used when deadlocks are not expected. That way, a timeout exception will be thrown when an unexpected deadlock occurs.
unit the TimeUnit of the timeOut value. May be null only if timeOut is zero.
Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if the transaction or environment has been closed.
java.lang.IllegalArgumentException if timeOut or unit is invalid.
Since:
4.0
    public void setLockTimeout(long timeOutTimeUnit unit)
        throws IllegalArgumentExceptionDatabaseException {
        checkEnv();
        checkOpen();
        .setLockTimeout(PropUtil.durationToMillis(timeOutunit));
    }

    
Configures the lock request timeout value for the transaction, with the timeout value specified in microseconds. This method is equivalent to:
setLockTimeout(long, TimeUnit.MICROSECONDS);

Deprecated:
as of 4.0, replaced by setLockTimeout(long,java.util.concurrent.TimeUnit).
    public void setLockTimeout(long timeOut)
        throws IllegalArgumentExceptionDatabaseException {
        setLockTimeout(timeOut.);
    }

    
Set the user visible name for the transaction.

Parameters:
name The user visible name for the transaction.
    public void setName(String name) {
        this. = name;
    }

    
Get the user visible name for the transaction.

Returns:
The user visible name for the transaction.
    public String getName() {
        return ;
    }

    
For internal use.

Hidden:
    @Override
    public int hashCode() {
        return (int;
    }

    
For internal use.

Hidden:
    @Override
    public boolean equals(Object o) {
        if (o == null) {
            return false;
        }
        if (!(o instanceof Transaction)) {
            return false;
        }
        if (((Transactiono). == ) {
            return true;
        }
        return false;
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("<Transaction id=\"");
        sb.append().append("\"");
        if ( != null) {
            sb.append(" name=\"");
            sb.append().append("\"");
            }
        sb.append(">");
        return sb.toString();
    }

    
This method should only be called by the LockerFactory.getReadableLocker and getWritableLocker methods. The locker returned does not enforce the readCommitted isolation setting.

Throws:
java.lang.IllegalArgumentException via all API methods with a txn param
    Locker getLocker()
        throws DatabaseException {
        if ( == null) {
            throw new IllegalArgumentException
                ("Transaction " +  +
                 " has been closed and is no longer usable.");
        }
        return ;
    }
    /*
     * Helpers
     */
    Txn getTxn() {
        return ;
    }
        return ;
    }

    

Throws:
EnvironmentFailureException if the underlying environment is invalid, via all methods.
java.lang.IllegalStateException via all methods.
    private void checkEnv() {
        EnvironmentImpl envImpl =  .getEnvironmentImpl();
        if (envImpl == null) {
            throw new IllegalStateException
                ("The environment has been closed. " +
                 "This transaction is no longer usable.");
        }
        envImpl.checkIfInvalid();
    }

    

Throws:
java.lang.IllegalStateException via all methods except abort.
    void checkOpen() {
        if ( == null || .isClosed()) {
            throw new IllegalStateException("Transaction Id " +  +
                                            " has been closed.");
        }
    }

    
Returns whether this Transaction is open, which is equivalent to when getState() returns Transaction.State.OPEN. See Transaction.State.OPEN for more information.

When an OperationFailureException, or one of its subclasses, is caught, the isValid method may be called to determine whether the Transaction can continue to be used, or should be aborted.

    public boolean isValid() {
        return  != null &&
               .isValid();
    }

    
Remove reference to internal txn, so we can reclaim memory. Before setting it null, save the final State value, so we can return it from getState.
    private void setTxnNull() {
         = .getState();
         = null;
    }

    
Returns the current state of the transaction.

Since:
5.0.48
    public State getState() {
        if ( != null) {
            assert  == null;
            return .getState();
        } else {
            assert  != null;
            return ;
        }
    }
New to GrepCode? Check out our FAQ X