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;
   
  import java.io.Closeable;
  import java.io.File;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Set;
  
  
A database environment. Environments include support for some or all of caching, locking, logging and transactions.

To open an existing environment with default attributes the application may use a default environment configuration object or null:

      // Open an environment handle with default attributes.
     Environment env = new Environment(home, new EnvironmentConfig());
     
or
     Environment env = new Environment(home, null);
 

Note that many Environment objects may access a single environment.

To create an environment or customize attributes, the application should customize the configuration class. For example:

     EnvironmentConfig envConfig = new EnvironmentConfig();
     envConfig.setTransactional(true);
     envConfig.setAllowCreate(true);
     envConfig.setCacheSize(1000000);
     Environment newlyCreatedEnv = new Environment(home, envConfig);
 

Note that environment configuration parameters can also be set through the <environment home>/je.properties file. This file takes precedence over any programmatically specified configuration parameters so that configuration changes can be made without recompiling. Environment configuration follows this order of precedence:

  1. Configuration parameters specified in <environment home>/je.properties take first precedence.
  2. Configuration parameters set in the EnvironmentConfig object used at Environment construction are next.
  3. Any configuration parameters not set by the application are set to system defaults, described along with the parameter name String constants in the EnvironmentConfig class.

An environment handle is an Environment instance. More than one Environment instance may be created for the same physical directory, which is the same as saying that more than one Environment handle may be open at one time for a given environment.

The Environment handle should not be closed while any other handle remains open that is using it as a reference (for example, Database or Transaction. Once Environment.close is called, this object may not be accessed again.
  
  public class Environment implements Closeable {

    

Hidden:
envImpl is a reference to the shared underlying environment.
  
      protected EnvironmentImpl envImpl;
     private final EnvironmentConfig appliedFinalConfig;
 
     private final Set<DatabasereferringDbs;
     private final Set<TransactionreferringDbTxns;

    

Hidden:
The name of the cleaner daemon thread. This constant is passed to an ExceptionEvent's threadName argument when an exception is thrown in the cleaner daemon thread.
 
     public static final String CLEANER_NAME = "Cleaner";

    

Hidden:
The name of the IN Compressor daemon thread. This constant is passed to an ExceptionEvent's threadName argument when an exception is thrown in the IN Compressor daemon thread.
 
     public static final String INCOMP_NAME = "INCompressor";

    

Hidden:
The name of the Checkpointer daemon thread. This constant is passed to an ExceptionEvent's threadName argument when an exception is thrown in the Checkpointer daemon thread.
 
     public static final String CHECKPOINTER_NAME = "Checkpointer";

    
Creates a database environment handle.

Parameters:
envHome The database environment's home directory.
configuration The database environment attributes. If null, default attributes are used.
Throws:
EnvironmentNotFoundException if the environment does not exist (does not contain at least one log file) and the EnvironmentConfig AllowCreate parameter is false.
EnvironmentLockedException when an environment cannot be opened for write access because another process has the same environment open for write access. Warning: This exception should be handled when an environment is opened by more than one process.
VersionMismatchException when the existing log is not compatible with the version of JE that is running. This occurs when a later version of JE was used to create the log. Warning: This exception should be handled when more than one version of JE may be used to access an environment.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.UnsupportedOperationException if this environment was previously opened for replication and is not being opened read-only.
java.lang.IllegalArgumentException if an invalid parameter is specified, for example, an invalid EnvironmentConfig parameter.
 
     public Environment(File envHomeEnvironmentConfig configuration)
         throws EnvironmentNotFoundException,
                EnvironmentLockedException,
                VersionMismatchException,
                DatabaseException,
                IllegalArgumentException {
 
         this(envHomeconfigurationtrue /*openIfNeeded*/,
              null /*repConfigProxy*/null /*envImplParam*/);
     }

    

Hidden:
Replication support.
 
     protected Environment(File envHome,
                           EnvironmentConfig configuration,
                           RepConfigProxy repConfigProxy,
                           EnvironmentImpl envImplParam) {
         this(envHomeconfigurationtrue /*openIfNeeded*/repConfigProxy,
              envImplParam);
     }

    
Gets an Environment for an existing EnvironmentImpl. Used by utilities such as the JMX MBean which don't want to open the environment or be reference counted. The calling application must take care not to retain
 
     Environment(File envHome) {
         this(envHomenull /*configuration*/false /*openIfNeeded*/,
              null /*repConfigProxy*/null /*envImplParam*/);
     }

    

Parameters:
envImpl is non-null only when used by EnvironmentIml to create an InternalEnvironment.
Hidden:
Internal common constructor.
 
     protected Environment(File envHome,
                           EnvironmentConfig envConfig,
                           boolean openIfNeeded,
                           RepConfigProxy repConfigProxy,
                           EnvironmentImpl envImplParam) {
 
         /* If openIfNeeded is false, then envConfig must be null. */
         assert openIfNeeded || envConfig == null || envImplParam != null;
 
          = null;
          = Collections.synchronizedSet(new HashSet<Database>());
          =
             Collections.synchronizedSet(new HashSet<Transaction>());
 
         DatabaseUtil.checkForNullParam(envHome"envHome");
 
          =
             setupHandleConfig(envHomeenvConfigrepConfigProxy);
 
         if (envImplParam != null) {
             /* We're creating an InternalEnvironment in EnvironmentImpl. */
              = envImplParam;
         } else {
             /* Open a new or existing environment in the shared pool. */
              = makeEnvironmentImpl(envHome,
                                           envConfig,
                                           openIfNeeded,
                                           repConfigProxy);
         }
     }

    

Hidden:
MakeEnvironmentImpl is called both by the Environment constructor and by the ReplicatedEnvironment constructor when recreating the environment for a hard recovery.
 
         (File envHome,
          EnvironmentConfig envConfig,
          boolean openIfNeeded,
          RepConfigProxy repConfigProxy) {
 
          = DbEnvPool.getInstance().getEnvironment
             (envHome,
              ,
              envConfig != null /*checkImmutableParams*/,
              openIfNeeded,
              setupRepConfig(envHomerepConfigProxyenvConfig));
 
         if ( != null) {
             .registerMBean(this);
         }
 
         return ;
     }

    
Validate the parameters specified in the environment config. Applies the configurations specified in the je.properties file to override any programmatically set configurations. Create a copy to save in this handle. The main reason to return a config instead of using the handleConfig field is to return an EnvironmentConfig instead of a EnvironmentMutableConfig.
 
     private EnvironmentConfig setupHandleConfig(File envHome,
                                                 EnvironmentConfig envConfig,
                                                 RepConfigProxy repConfig)
         throws IllegalArgumentException {
 
         /* If the user specified a null object, use the default */
         EnvironmentConfig baseConfig = (envConfig == null) ?
             . : envConfig;
 
         /* Make a copy, apply je.properties, and init the handle config. */
         EnvironmentConfig useConfig = baseConfig.clone();
 
         /* Apply the je.properties file. */
         if (useConfig.getLoadPropertyFile()) {
             DbConfigManager.applyFileConfig(envHome,
                                             DbInternal.getProps(useConfig),
                                             false);       // forReplication
         }
         copyToHandleConfig(useConfiguseConfigrepConfig);
         return useConfig;
     }

    

Hidden:
Obtain a validated replication configuration. In a non-HA environment, return null.
 
     protected RepConfigProxy
         setupRepConfig(final File envHome,
                        final RepConfigProxy repConfigProxy,
                        final EnvironmentConfig envConfig) {
 
         return null;
     }

    
The Environment.close method closes the Berkeley DB environment.

When the last environment handle is closed, allocated resources are freed, and daemon threads are stopped, even if they are performing work. For example, if the cleaner is still cleaning the log, it will be stopped at the next reasonable opportunity and perform no more cleaning operations.

The Environment handle should not be closed while any other handle that refers to it is not yet closed; for example, database environment handles must not be closed while database handles remain open, or transactions in the environment have not yet committed or aborted. Specifically, this includes Database, Cursor and Transaction handles.

If this handle has already been closed, this method does nothing and returns without throwing an exception.

In multithreaded applications, only a single thread should call Environment.close.

The environment handle may not be used again after this method has been called, regardless of the method's success or failure, with one exception: the close method itself may be called any number of times.

WARNING: To guard against memory leaks, the application should discard all references to the closed handle. While BDB makes an effort to discard references from closed objects to the allocated memory for an environment, this behavior is not guaranteed. The safe course of action for an application is to discard all references to closed BDB objects.

Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if any open databases or transactions refer to this handle.
 
     public synchronized void close()
         throws DatabaseException {
 
         if ( == null) {
             return;
         }
 
         if (!.isValid()) {
 
             /*
              * We're trying to close on an environment that has seen a fatal
              * exception. Try to do the minimum, such as closing file
              * descriptors, to support re-opening the environment in the same
              * JVM.
              */
             try {
                 .closeAfterInvalid();
             } finally {
                  = null;
             }
             return;
         }
 
         final StringBuilder errors = new StringBuilder();
         try {
             checkForCloseErrors(errors);
 
             try {
                 .close();
             } catch (RuntimeException e) {
                 if (!.isValid()) {
                     /* Propagate if env is invalidated. */
                     throw e;
                 }
                 errors.append
                   ("\nWhile closing Environment encountered exception: ");
                 errors.append(e).append("\n");
             }
 
             if (errors.length() > 0) {
                 throw new IllegalStateException(errors.toString());
             }
         } finally {
              = null;
         }
     }

    
Close an InternalEnvironment handle. We do not call EnvironmentImpl.close here, since an InternalEnvironment is not registered like a non-internal handle. However, we must call checkForCloseErrors to auto-close internal databases, as well as check for errors.
 
     synchronized void closeInternalHandle() {
         final StringBuilder errors = new StringBuilder();
         checkForCloseErrors(errors);
         if (errors.length() > 0) {
             throw new IllegalStateException(errors.toString());
         }
     }
 
     private void checkForCloseErrors(StringBuilder errors) {
 
         checkOpenDbs(errors);
 
         checkOpenTxns(errors);
 
         if (!isInternalHandle()) {
 
             /*
              * Only check for open XA transactions against user created
              * environment handles.
              */
             checkOpenXATransactions(errors);
         }
     }

    
Appends error messages to the errors argument if there are open XA transactions associated with the underlying EnvironmentImpl.
 
     private void checkOpenXATransactions(final StringBuilder errors) {
         Xid[] openXids = .getTxnManager().XARecover();
         if (openXids != null && openXids.length > 0) {
             errors.append("There ");
             int nXATxns = openXids.length;
             if (nXATxns == 1) {
                 errors.append("is 1 existing XA transaction opened");
                 errors.append(" in the Environment.\n");
                 errors.append("It");
             } else {
                 errors.append("are ");
                 errors.append(nXATxns);
                 errors.append(" existing transactions opened in");
                 errors.append(" the Environment.\n");
                 errors.append("They");
             }
             errors.append(" will be left open ...\n");
         }
     }

    
Appends error messages to the errors argument if there are open transactions associated with the environment.
 
     private void checkOpenTxns(final StringBuilder errors) {
         int nTxns = ( == null) ? 0 : .size();
         if (nTxns == 0) {
             return;
         }
 
         /*
          * Copy the referringDbTxns Set because txn.abort() modifies this Set,
          * potentially causing a ConcurrentModificationException.  Must do the
          * copy while synchronized. [#21279]
          */
         final Iterator<Transactioniter;
         synchronized () {
             iter = new HashSet<Transaction>().iterator();
         }
         errors.append("There ");
         if (nTxns == 1) {
             errors.append("is 1 existing transaction opened");
             errors.append(" against the Environment.\n");
         } else {
             errors.append("are ");
             errors.append(nTxns);
             errors.append(" existing transactions opened against");
             errors.append(" the Environment.\n");
         }
         errors.append("Aborting open transactions ...\n");
 
         while (iter.hasNext()) {
             Transaction txn = iter.next();
             try {
                 errors.append("aborting " + txn);
                 txn.abort();
             } catch (RuntimeException e) {
                 if (!.isValid()) {
                     /* Propagate if env is invalidated. */
                     throw e;
                 }
                 errors.append("\nWhile aborting transaction ");
                 errors.append(txn.getId());
                 errors.append(" encountered exception: ");
                 errors.append(e).append("\n");
             }
         }
     }

    
Appends error messages to the errors argument if there are open database handles associated with the environment.
 
     private void checkOpenDbs(final StringBuilder errors) {
 
         if (.isEmpty()) {
             return;
         }
 
         /*
          * Copy the referringDbs Set because db.close() modifies this Set,
          * potentially causing a ConcurrentModificationException.  Must do the
          * copy while synchronized. [#21279]
          */
         final Iterator<Databaseiter;
         synchronized () {
             iter = new HashSet<Database>().iterator();
         }
         int nOpenUserDbs = 0;
         while (iter.hasNext()) {
             String dbName = "";
             try {
                 Database db = iter.next();
 
                 /*
                  * Save the db name before we attempt the close, it's
                  * unavailable after the close.
                  */
                 dbName = db.getDebugName();
 
                 if (!db.getDatabaseImpl().isInternalDb()) {
                     nOpenUserDbs += 1;
                     errors.append("Unclosed Database: ");
                     errors.append(dbName).append("\n");
                 }
                 db.close();
             } catch (RuntimeException e) {
                 if (!.isValid()) {
                     /* Propagate if env is invalidated. */
                     throw e;
                 }
                 errors.append("\nWhile closing Database ");
                 errors.append(dbName);
                 errors.append(" encountered exception: ");
                 errors.append(e).append("\n");
             }
         }
 
         if (nOpenUserDbs > 0) {
             errors.append("Databases left open: ");
             errors.append(nOpenUserDbs).append("\n");
         }
     }

    
Opens, and optionally creates, a Database.

Parameters:
txn For a transactional database, an explicit transaction may be specified, or null may be specified to use auto-commit. For a non-transactional database, null must be specified.
databaseName The name of the database.
dbConfig The database attributes. If null, default attributes are used.
Returns:
Database handle.
Throws:
DatabaseExistsException if the database already exists and the DatabaseConfig ExclusiveCreate parameter is true.
DatabaseNotFoundException if the database does not exist and the DatabaseConfig AllowCreate parameter is false.
OperationFailureException if one of the Read Operation Failures occurs. If the database does not exist and the DatabaseConfig.setAllowCreate(boolean) parameter is true, then one of the Write Operation Failures may also occur.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if this handle or the underlying environment has been closed.
java.lang.IllegalArgumentException if an invalid parameter is specified, for example, an invalid DatabaseConfig property.
java.lang.IllegalStateException if DatabaseConfig properties are changed and there are other open handles for this database.
 
     public synchronized Database openDatabase(Transaction txn,
                                               String databaseName,
                                               DatabaseConfig dbConfig)
         throws DatabaseNotFoundException,
                DatabaseExistsException,
                IllegalArgumentException,
                IllegalStateException {
 
         checkHandleIsValid();
         checkEnv();
 
         try {
             if (dbConfig == null) {
                 dbConfig = .;
             }
 
             Database db = new Database(this);
             setupDatabase(txndbdatabaseNamedbConfig,
                           false /*isInternalDb*/);
             return db;
         } catch (Error E) {
             .invalidate(E);
             throw E;
         }
     }

    
Opens an internal database for internal JE use. - permits opening DBs with reserved (internal) names. - permits opening a transactional DB in a non-transactional env. DbConfig should not be null. Note that the dbConfig argument determines whether the database that is created is to be replicated or is standalone. The current default is for dbConfig to be replicated, so use DatabaseConfig.setReplicated(false) to create a local internal database.
 
     synchronized Database openInternalDatabase(Transaction txn,
                                                String databaseName,
                                                DatabaseConfig dbConfig)
 
         assert DbTree.isReservedDbName(databaseName) : databaseName;
         Database db = new Database(this);
         setupDatabase(txndbdatabaseNamedbConfigtrue /*isInternalDb*/);
         return db;
     }

    
Opens and optionally creates a SecondaryDatabase.

Note that the associations between primary and secondary databases are not stored persistently. Whenever a primary database is opened for write access by the application, the appropriate associated secondary databases should also be opened by the application. This is necessary to ensure data integrity when changes are made to the primary database.

Parameters:
txn For a transactional database, an explicit transaction may be specified, or null may be specified to use auto-commit. For a non-transactional database, null must be specified.
databaseName The name of the database.
primaryDatabase the primary database with which the secondary database will be associated. The primary database must not be configured for duplicates.
dbConfig The secondary database attributes. If null, default attributes are used.
Returns:
Database handle.
Throws:
DatabaseExistsException if the database already exists and the DatabaseConfig ExclusiveCreate parameter is true.
DatabaseNotFoundException if the database does not exist and the DatabaseConfig AllowCreate parameter is false.
OperationFailureException if one of the Read Operation Failures occurs. If the database does not exist and the DatabaseConfig.setAllowCreate(boolean) parameter is true, then one of the Write Operation Failures may also occur.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if this handle or the underlying environment has been closed.
java.lang.IllegalArgumentException if an invalid parameter is specified, for example, an invalid SecondaryConfig property.
java.lang.IllegalStateException if DatabaseConfig properties are changed and there are other open handles for this database.
 
     public synchronized
                                                 String databaseName,
                                                 Database primaryDatabase,
                                                 SecondaryConfig dbConfig)
         throws DatabaseNotFoundException,
                DatabaseExistsException,
                DatabaseException,
                IllegalArgumentException,
                IllegalStateException {
 
         checkHandleIsValid();
         checkEnv();
         try {
             if (dbConfig == null) {
                 dbConfig = .;
             }
             SecondaryDatabase db =
                 new SecondaryDatabase(thisdbConfigprimaryDatabase);
 
             setupDatabase(txndbdatabaseNamedbConfig,
                           false /*isInternalDb*/);
             return db;
         } catch (Error E) {
             .invalidate(E);
             throw E;
         }
     }

    
The meat of open database processing.

Parameters:
txn may be null
newDb is the Database handle which houses this database
Throws:
java.lang.IllegalArgumentException via openDatabase and openSecondaryDatabase
See also:
com.sleepycat.je.txn.HandleLocker
 
     private void setupDatabase(Transaction txn,
                                Database newDb,
                                String databaseName,
                                DatabaseConfig dbConfig,
                                boolean isInternalDb)
 
         checkEnv();
         DatabaseUtil.checkForNullParam(databaseName"databaseName");
 
         LoggerUtils.envLogMsg(.,
                               "Environment.open: " + " name=" + databaseName +
                               " dbConfig=" + dbConfig);
 
         final boolean autoTxnIsReplicated =
             DbInternal.getReplicated(dbConfig) && .isReplicated();
 
         /*
          * Check that the open configuration is valid and doesn't conflict with
          * the envImpl configuration.
          */
         dbConfig.validateOnDbOpen(databaseNameautoTxnIsReplicated);
         validateDbConfigAgainstEnv(dbConfigdatabaseNameisInternalDb);
 
         /* Perform eviction before each operation that allocates memory. */
         .criticalEviction(false /*backgroundIO*/);
 
         DatabaseImpl database = null;
         boolean operationOk = false;
         HandleLocker handleLocker = null;
         final Locker locker = LockerFactory.getWritableLocker
             (thistxnisInternalDbdbConfig.getTransactional(),
              autoTxnIsReplicatednull);
         try {
 
             /*
              * Create the handle locker and lock the NameLN of an existing
              * database.  A read lock on the NameLN is acquired for both locker
              * and handleLocker.  Note: getDb may return a deleted database.
              */
             handleLocker = newDb.initHandleLocker(locker);
             database = .getDbTree().getDb(lockerdatabaseName,
                                                  handleLocker);
 
             boolean dbCreated = false;
             final boolean databaseExists =
                 (database != null) && !database.isDeleted();
 
             if (databaseExists) {
                 if (dbConfig.getAllowCreate() &&
                     dbConfig.getExclusiveCreate()) {
                     throw new DatabaseExistsException
                         ("Database " + databaseName + " already exists");
                 }
 
                 newDb.initExisting(thislockerdatabasedatabaseName,
                                    dbConfig);
             } else {
                 /* Release deleted DB. [#13415] */
                 .getDbTree().releaseDb(database);
                 database = null;
 
                 if (!isInternalDb &&
                     DbTree.isReservedDbName(databaseName)) {
                     throw new IllegalArgumentException
                         (databaseName + " is a reserved database name.");
                 }
 
                 if (!dbConfig.getAllowCreate()) {
                     throw new DatabaseNotFoundException("Database " +
                                                         databaseName +
                                                         " not found.");
                 }
 
                 /*
                  * Init a new DB. This calls DbTree.createDb and the new
                  * database is returned.  A write lock on the NameLN is
                  * acquired by locker and a read lock by the handleLocker.
                  */
                 database = newDb.initNew(thislockerdatabaseNamedbConfig);
                 dbCreated = true;
             }
 
             /*
              * The open is successful.  We add the opened database handle to
              * this environment to track open handles in general, and to the
              * locker so that it can be invalidated by a user txn abort.
              */
             operationOk = true;
             addReferringHandle(newDb);
             locker.addOpenedDatabase(newDb);
 
             /* Run triggers before any subsequent auto commits. */
             final boolean firstWriteHandle =
                 newDb.isWritable() &&
                 (newDb.getDatabaseImpl().noteWriteHandleOpen() == 1);
 
             if (dbCreated || firstWriteHandle) {
                 TriggerManager.runOpenTriggers(lockernewDbdbCreated);
             }
         } finally {
 
             /*
              * If the open fails, decrement the DB usage count and release
              * handle locks.  In other cases this is done by Database.close()
              * or invalidate(), the latter in the case of a user txn abort.
              */
             if (!operationOk) {
                 .getDbTree().releaseDb(database);
                 if (handleLocker != null) {
                     handleLocker.operationEnd(false);
                 }
             }
 
             /*
              * Tell the locker that this operation is over. Some types of
              * lockers (BasicLocker and auto Txn) will actually finish.
              */
             locker.operationEnd(operationOk);
         }
     }

    

Throws:
java.lang.IllegalArgumentException via openDatabase and openSecondaryDatabase
 
     private void validateDbConfigAgainstEnv(DatabaseConfig dbConfig,
                                             String databaseName,
                                             boolean isInternalDb)
         throws IllegalArgumentException {
 
         /*
          * R/W database handles on a replicated database must be transactional,
          * for now. In the future we may support non-transactional database
          * handles.
          */
         if (.isReplicated() &&
             dbConfig.getReplicated() &&
             !dbConfig.getReadOnly()) {
             if (!dbConfig.getTransactional()) {
                 throw new IllegalArgumentException
                 ("Read/Write Database instances for replicated " +
                  "database " + databaseName + " must be transactional.");
             }
         }
 
         /* Check operation's transactional status against the Environment */
         if (!isInternalDb &&
             dbConfig.getTransactional() &&
             !(.isTransactional())) {
             throw new IllegalArgumentException
                 ("Attempted to open Database " + databaseName +
                  " transactionally, but parent Environment is" +
                  " not transactional");
         }
 
         /* Check read/write status */
         if (.isReadOnly() && (!dbConfig.getReadOnly())) {
             throw new IllegalArgumentException
                 ("Attempted to open Database " + databaseName +
                  " as writable but parent Environment is read only ");
         }
     }

    
Removes a database from the environment, discarding all records in the database and removing the database name itself.

Compared to deleting all the records in a database individually, removeDatabase is a very efficient operation. Some internal housekeeping information is updated, but the database records are not read or written, and very little I/O is needed.

When called on a database configured with secondary indices, the application is responsible for also removing all associated secondary indices. To guarantee integrity, a primary database and all of its secondary databases should be removed atomically using a single transaction.

Applications should not remove a database with open Database handles. If the database is open with the same transaction as passed in the txn parameter, java.lang.IllegalStateException is thrown by this method. If the database is open using a different transaction, this method will block until all database handles are closed, or until the conflict is resolved by throwing LockConflictException.

Parameters:
txn For a transactional environment, an explicit transaction may be specified or null may be specified to use auto-commit. For a non-transactional environment, null must be specified.
databaseName The database to be removed.
Throws:
DatabaseNotFoundException if the database does not exist.
OperationFailureException if one of the Write Operation Failures occurs.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.UnsupportedOperationException if this is a read-only environment.
java.lang.IllegalStateException if the database is currently open using the transaction passed in the txn parameter, or if this handle or the underlying environment has been closed.
java.lang.IllegalArgumentException if an invalid parameter is specified.
 
     public void removeDatabase(Transaction txnString databaseName)
         throws DatabaseNotFoundException {
 
         checkHandleIsValid();
         DatabaseUtil.checkForNullParam(databaseName"databaseName");
         checkEnv();
         checkWritable();
 
         final boolean autoTxnIsReplicated = .isReplicated();
         Locker locker = null;
         DatabaseImpl dbImpl = null;
         try {
 
             /*
              * Note: use env level isTransactional as proxy for the db
              * isTransactional.
              */
             locker = LockerFactory.getWritableLocker
                 (this,
                  txn,
                  false /*isInternalDb*/,
                  .isTransactional(),
                  autoTxnIsReplicated,
                  null);
             dbImpl = .getDbTree().dbRemove(locker,
                                          databaseName,
                                          null /*checkId*/);
         } catch (Error E) {
             .invalidate(E);
             throw E;
         } finally {
             if (dbImpl != null) {
                 TriggerManager.runRemoveTriggers(lockerdbImpl);
             }
             if (locker != null) {
                 locker.operationEnd(dbImpl != null);
             }
         }
     }

    
Renames a database, without removing the records it contains.

Applications should not rename a database with open Database handles. If the database is open with the same transaction as passed in the txn parameter, java.lang.IllegalStateException is thrown by this method. If the database is open using a different transaction, this method will block until all database handles are closed, or until the conflict is resolved by throwing LockConflictException.

Parameters:
txn For a transactional environment, an explicit transaction may be specified or null may be specified to use auto-commit. For a non-transactional environment, null must be specified.
databaseName The new name of the database.
Throws:
DatabaseNotFoundException if the database does not exist.
OperationFailureException if one of the Write Operation Failures occurs.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.UnsupportedOperationException if this is a read-only environment.
java.lang.IllegalStateException if the database is currently open using the transaction passed in the txn parameter, or if this handle or the underlying environment has been closed.
java.lang.IllegalArgumentException if an invalid parameter is specified.
    public void renameDatabase(Transaction txn,
                               String databaseName,
                               String newName)
        throws DatabaseNotFoundException {
        DatabaseUtil.checkForNullParam(databaseName"databaseName");
        DatabaseUtil.checkForNullParam(newName"newName");
        checkHandleIsValid();
        checkEnv();
        checkWritable();
        Locker locker = null;
        DatabaseImpl dbImpl = null;
        try {
            /*
             * Note: use env level isTransactional as proxy for the db
             * isTransactional.
             */
            locker = LockerFactory.getWritableLocker
                (thistxn,
                 false /*isInternalDb*/,
                 .isTransactional(),
                 .isReplicated(),  // autoTxnIsReplicated
                 null);
            dbImpl = .getDbTree().
                dbRename(lockerdatabaseNamenewName);
        } catch (Error E) {
            .invalidate(E);
            throw E;
        } finally {
            if (dbImpl != null) {
                TriggerManager.runRenameTriggers(lockerdbImplnewName);
            }
            if (locker != null) {
                locker.operationEnd(dbImpl != null);
            }
        }
    }

    
Empties the database, discarding all the records it contains, without removing the database name.

Compared to deleting all the records in a database individually, truncateDatabase is a very efficient operation. Some internal housekeeping information is updated, but the database records are not read or written, and very little I/O is needed.

When called on a database configured with secondary indices, the application is responsible for also truncating all associated secondary indices. To guarantee integrity, a primary database and all of its secondary databases should be truncated atomically using a single transaction.

Applications should not truncate a database with open Database handles. If the database is open with the same transaction as passed in the txn parameter, java.lang.IllegalStateException is thrown by this method. If the database is open using a different transaction, this method will block until all database handles are closed, or until the conflict is resolved by throwing LockConflictException.

Parameters:
txn For a transactional environment, an explicit transaction may be specified or null may be specified to use auto-commit. For a non-transactional environment, null must be specified.
databaseName The database to be truncated.
returnCount If true, count and return the number of records discarded.
Returns:
The number of records discarded, or -1 if returnCount is false.
Throws:
DatabaseNotFoundException if the database does not exist.
OperationFailureException if one of the Write Operation Failures occurs.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.UnsupportedOperationException if this is a read-only environment.
java.lang.IllegalStateException if the database is currently open using the transaction passed in the txn parameter, or if this handle or the underlying environment has been closed.
java.lang.IllegalArgumentException if an invalid parameter is specified.
    public long truncateDatabase(Transaction txn,
                                 String databaseName,
                                 boolean returnCount)
        throws DatabaseNotFoundException {
        checkHandleIsValid();
        DatabaseUtil.checkForNullParam(databaseName"databaseName");
        checkEnv();
        checkWritable();
        final boolean autoTxnIsReplicated = .isReplicated();
        Locker locker = null;
        TruncateDbResult result = null;
        try {
            /*
             * Note: use env level isTransactional as proxy for the db
             * isTransactional.
             */
            locker = LockerFactory.getWritableLocker
                (thistxn,
                 false /*isInternalDb*/,
                 .isTransactional(),
                 autoTxnIsReplicated,
                 null);
            result = .getDbTree().truncate(locker,
                                                 databaseName,
                                                 returnCount);
        } catch (Error E) {
            .invalidate(E);
            throw E;
        } finally {
            if (result != null) {
                TriggerManager.runTruncateTriggers(lockerresult.newDb);
            }
            if (locker != null) {
                locker.operationEnd(result != null);
            }
        }
        if (result == null) {
            /* Added to suppress compiler warnings. */
            throw EnvironmentFailureException.unexpectedState(,
                                                              "Cannot happen");
        }
        return result.recordCount;
    }

    
For unit testing. Returns the current memory usage in bytes for all btrees in the envImpl.
    long getMemoryUsage()
        throws DatabaseException {
        checkHandleIsValid();
        checkEnv();
        return .getMemoryBudget().getCacheMemoryUsage();
    }

    
Returns the database environment's home directory.

Returns:
The database environment's home directory.
Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if this handle or the underlying environment has been closed.
    public File getHome()
        throws DatabaseException {
        checkHandleIsValid();
        return .getEnvironmentHome();
    }
    /*
     * Transaction management
     */

    
Returns the default txn config for this environment handle.
        return ;
    }

    
Copies the handle properties out of the config properties, and initializes the default transaction config.
    private void copyToHandleConfig(EnvironmentMutableConfig useConfig,
                                    EnvironmentConfig initStaticConfig,
                                    RepConfigProxy    initRepConfig) {
        /*
         * Create the new objects, initialize them, then change the instance
         * fields.  This avoids synchronization issues.
         */
        EnvironmentMutableConfig newHandleConfig =
            new EnvironmentMutableConfig();
        useConfig.copyHandlePropsTo(newHandleConfig);
        this. = newHandleConfig;
        TransactionConfig newTxnConfig =
            ..clone();
        newTxnConfig.setNoSync(.getTxnNoSync());
        newTxnConfig.setWriteNoSync(.getTxnWriteNoSync());
        newTxnConfig.setDurability(.getDurability());
        if (initStaticConfig != null) {
            newTxnConfig.setSerializableIsolation
                (initStaticConfig.getTxnSerializableIsolation());
            newTxnConfig.setReadCommitted
                (initStaticConfig.getTxnReadCommitted());
        } else {
            newTxnConfig.setSerializableIsolation
                (.getSerializableIsolation());
            newTxnConfig.setReadCommitted
                (.getReadCommitted());
            newTxnConfig.setConsistencyPolicy
                (.getConsistencyPolicy());
        }
        if (initRepConfig != null) {
            newTxnConfig.setConsistencyPolicy
                (initRepConfig.getConsistencyPolicy());
        }
        this. = newTxnConfig;
    }

    
Creates a new transaction in the database environment.

Transaction handles are free-threaded; transactions handles may be used concurrently by multiple threads.

Cursors may not span transactions; that is, each cursor must be opened and closed within a single transaction. The parent parameter is a placeholder for nested transactions, and must currently be null.

Parameters:
txnConfig The transaction attributes. If null, default attributes are used.
Returns:
The newly created transaction's handle.
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.ReplicaConsistencyException if a replica in a replicated environment cannot become consistent within the timeout period.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.UnsupportedOperationException if this is not a transactional environment.
java.lang.IllegalStateException if this handle or the underlying environment has been closed.
java.lang.IllegalArgumentException if an invalid parameter is specified, for example, an invalid TransactionConfig parameter.
    public Transaction beginTransaction(Transaction parent,
                                        TransactionConfig txnConfig)
        throws DatabaseException,
               IllegalArgumentException {
        try {
            return beginTransactionInternal(parenttxnConfig,
                                            false /*isInternalTxn*/);
        } catch (Error E) {
            if ( != null) {
                .invalidate(E);
            }
            throw E;
        }
    }

    
Like beginTransaction, but does not require that the Environment is transactional.
        return beginTransactionInternal(null /*parent*/txnConfig,
                                        true /*isInternalTxn*/);
    }

    

Throws:
java.lang.IllegalArgumentException via beginTransaction.
java.lang.UnsupportedOperationException via beginTransaction.
                                                 TransactionConfig txnConfig,
                                                 boolean isInternalTxn )
        throws DatabaseException {
        checkHandleIsValid();
        checkEnv();
        if (parent != null) {
            throw new IllegalArgumentException
                ("Parent txn is non-null. " +
                 "Nested transactions are not supported.");
        }
        if (!isInternalTxn && !.isTransactional()) {
            throw new UnsupportedOperationException
                ("Transactions can not be used in a non-transactional " +
                 "environment");
        }
        checkTxnConfig(txnConfig);
        /*
         * Apply txn config defaults.  We don't need to clone unless we have to
         * apply the env default, since we don't hold onto a txn config
         * reference.
         */
        TransactionConfig useConfig = null;
        if (txnConfig == null) {
            useConfig = ;
        } else {
            if (.getNoSync() ||
                .getWriteNoSync()) {
                /*
                 * The environment sync settings have been set, check if any
                 * were set in the user's txn config. If none were set in the
                 * user's config, apply the environment defaults
                 */
                if (!txnConfig.getNoSync() &&
                    !txnConfig.getSync() &&
                    !txnConfig.getWriteNoSync()) {
                    useConfig = txnConfig.clone();
                    if (.getWriteNoSync()) {
                        useConfig.setWriteNoSync(true);
                    } else {
                        useConfig.setNoSync(true);
                    }
                }
            }
            if ((.getDurability() != null) &&
                 (txnConfig.getDurability() == null)) {
                /*
                 * Inherit transaction durability from the environment in the
                 * absence of an explicit transaction config durability.
                 */
                if (useConfig == null) {
                    useConfig = txnConfig.clone();
                }
                useConfig.setDurability(.getDurability());
            }
            if ((.getConsistencyPolicy() != null) &&
                (txnConfig.getConsistencyPolicy() == null)) {
                   if (useConfig == null) {
                       useConfig = txnConfig.clone();
                   }
                   useConfig.setConsistencyPolicy
                       (.getConsistencyPolicy());
            }
            /* Apply isolation level default. */
            if (!txnConfig.getSerializableIsolation() &&
                !txnConfig.getReadCommitted() &&
                !txnConfig.getReadUncommitted()) {
                if (.getSerializableIsolation()) {
                    if (useConfig == null) {
                        useConfig = txnConfig.clone();
                    }
                    useConfig.setSerializableIsolation(true);
                } else if (.getReadCommitted()) {
                    if (useConfig == null) {
                        useConfig = txnConfig.clone();
                    }
                    useConfig.setReadCommitted(true);
                }
            }
            /* No environment level defaults applied. */
            if (useConfig == null) {
                useConfig = txnConfig;
            }
        }
        Txn internalTxn = .txnBegin(parentuseConfig);
        Transaction txn = new Transaction(thisinternalTxn);
        addReferringHandle(txn);
        return txn;
    }

    
Checks the txnConfig object to ensure that its correctly configured and is compatible with the configuration of the Environment.

Parameters:
txnConfig the configuration being checked.
Throws:
java.lang.IllegalArgumentException via beginTransaction
    private void checkTxnConfig(TransactionConfig txnConfig)
        throws IllegalArgumentException {
        if (txnConfig == null) {
            return;
        }
        if ((txnConfig.getSerializableIsolation() &&
             txnConfig.getReadUncommitted()) ||
            (txnConfig.getSerializableIsolation() &&
             txnConfig.getReadCommitted()) ||
            (txnConfig.getReadUncommitted() &&
             txnConfig.getReadCommitted())) {
            throw new IllegalArgumentException
                ("Only one may be specified: SerializableIsolation, " +
                "ReadCommitted or ReadUncommitted");
        }
        if ((txnConfig.getDurability() != null) &&
            ((.getSync() ||
              .getNoSync() ||
              .getWriteNoSync()))) {
           throw new IllegalArgumentException
               ("Mixed use of deprecated durability API for the " +
                "Environment with the new durability API for " +
                "TransactionConfig.setDurability()");
        }
        if ((.getDurability() != null) &&
            ((txnConfig.getSync() ||
              txnConfig.getNoSync() ||
              txnConfig.getWriteNoSync()))) {
            throw new IllegalArgumentException
                   ("Mixed use of new durability API for the " +
                    "Environment with the deprecated durability API for " +
                    "TransactionConfig.");
        }
    }

    
Synchronously checkpoint the database environment.

This is an optional action for the application since this activity is, by default, handled by a database environment owned background thread.

A checkpoint has the side effect of flushing all preceding non-transactional write operations, as well as any preceding transactions that were committed with Durability.SyncPolicy.NO_SYNC. However, for best performance, checkpoints should be used only to bound recovery time. flushLog(boolean) can be used to write buffered data for durability purposes.

Parameters:
ckptConfig The checkpoint attributes. If null, default attributes are used.
Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if this handle or the underlying environment has been closed.
    public void checkpoint(CheckpointConfig ckptConfig)
        throws DatabaseException {
        try {
            checkHandleIsValid();
            checkEnv();
            CheckpointConfig useConfig =
                (ckptConfig == null) ? . : ckptConfig;
            .invokeCheckpoint(useConfig"api");
        } catch (Error E) {
            if ( != null) {
                .invalidate(E);
            }
            throw E;
        }
    }

    
Synchronously flushes database environment databases to stable storage. Calling this method is equivalent to forcing a checkpoint and setting CheckpointConfig.setMinimizeRecoveryTime(boolean) to true.

A checkpoint has the side effect of flushing all preceding non-transactional write operations, as well as any preceding transactions that were committed with Durability.SyncPolicy.NO_SYNC. However, for best performance, checkpoints should be used only to bound recovery time. flushLog(boolean) can be used to write buffered data for durability purposes.

Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if this handle or the underlying environment has been closed.
    public void sync()
        throws DatabaseException {
        try {
            checkHandleIsValid();
            checkEnv();
            CheckpointConfig config = new CheckpointConfig();
            config.setForce(true);
            config.setMinimizeRecoveryTime(true);
            .invokeCheckpoint(config"sync");
        } catch (Error E) {
            if ( != null) {
                .invalidate(E);
            }
            throw E;
        }
    }

    
Writes buffered data to the log, and optionally performs an fsync to guarantee that data is written to the physical device.

This method is used to make durable, by writing to the log, all preceding non-transactional write operations, as well as any preceding transactions that were committed with Durability.SyncPolicy.NO_SYNC. If the fsync parameter is true, it can also be used to flush all logged data to the physical storage device, by performing an fsync.

Note that this method does not flush previously unwritten data in deferred-write databases; that is done by calling Database.sync() or performing a checkpoint.

Parameters:
fsync is true to perform an fsync as well as a file write, or false to perform only a file write.
Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if this handle or the underlying environment has been closed.
    public void flushLog(boolean fsync) {
        try {
            checkHandleIsValid();
            checkEnv();
            .flushLog(fsync);
        } catch (Error E) {
            if ( != null) {
                .invalidate(E);
            }
            throw E;
        }
    }

    
Synchronously invokes database environment log cleaning. This method is called periodically by the cleaner daemon thread.

Zero or more log files will be cleaned as necessary to bring the disk space utilization of the environment above the configured minimum utilization threshold. The threshold is determined by the EnvironmentConfig.CLEANER_MIN_UTILIZATION configuration setting.

Note that cleanLog does not perform the complete task of cleaning a log file. Eviction and checkpointing migrate records that are marked by the cleaner, and a full checkpoint is necessary following cleaning before cleaned files will be deleted (or renamed). Checkpoints normally occur periodically and when the environment is closed.

This is an optional action for the application since this activity is, by default, handled by one or more database environment owned background threads.

There are two intended use cases for the cleanLog method. The first case is where the application wishes to disable the built-in cleaner threads using the EnvironmentConfig.ENV_RUN_CLEANER property. To replace the functionality of the cleaner threads, the application should call cleanLog periodically.

In the second use case, "batch cleaning", the application disables the cleaner threads for maximum performance during active periods, and calls cleanLog during periods when the application is quiescent or less active than usual. If the cleaner has a large number of files to clean, cleanLog may stop without reaching the target utilization; to ensure that the target utilization is reached, cleanLog should be called in a loop until it returns zero. And to complete the work of cleaning, a checkpoint is necessary. An example of performing batch cleaning follows.

       Environment env;
       boolean anyCleaned = false;
       while (env.cleanLog() > 0) {
           anyCleaned = true;
       }
       if (anyCleaned) {
           CheckpointConfig force = new CheckpointConfig();
           force.setForce(true);
           env.checkpoint(force);
       }
 

WARNING:If batch cleaning (shown above) is performed immediately before closing the environment, then the built-in cleaner threads should normally be disabled using EnvironmentConfig.ENV_RUN_CLEANER during the batch cleaning process. If the built-in cleaner threads are actively working on one or more log files, then those files will not be processed by the cleanLog method. Closing the environment will abort the work being done by the built-in cleaner threads, and log cleaning may be incomplete.

Returns:
The number of log files that were cleaned, and that will be deleted (or renamed) when a qualifying checkpoint occurs.
Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.UnsupportedOperationException if this is a read-only or memory-only environment.
java.lang.IllegalStateException if this handle or the underlying environment has been closed.
    public int cleanLog()
        throws DatabaseException {
        try {
            checkHandleIsValid();
            checkEnv();
            return .invokeCleaner();
        } catch (Error E) {
            if ( != null) {
                .invalidate(E);
            }
            throw E;
        }
    }

    
Synchronously invokes the mechanism for keeping memory usage within the cache size boundaries.

This is an optional action for the application since this activity is, by default, handled by a database environment owned background thread.

Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if this handle or the underlying environment has been closed.
    public void evictMemory()
        throws DatabaseException {
        try {
            checkHandleIsValid();
            checkEnv();
            .invokeEvictor();
        } catch (Error E) {
            if ( != null) {
                .invalidate(E);
            }
            throw E;
        }
    }

    
Synchronously invokes the compressor mechanism which compacts in memory data structures after delete operations.

This is an optional action for the application since this activity is, by default, handled by a database environment owned background thread.

Throws:
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if this handle or the underlying environment has been closed.
    public void compress()
        throws DatabaseException {
        try {
            checkHandleIsValid();
            checkEnv();
            .invokeCompressor();
        } catch (Error E) {
            if ( != null) {
                .invalidate(E);
            }
            throw E;
        }
    }

    
Preloads the cache with multiple databases. This method should only be called when there are no operations being performed on the specified databases in other threads. Executing preload during concurrent updates of the specified databases may result in some or all of the tree being loaded into the JE cache. Executing preload during any other types of operations may result in JE exceeding its allocated cache size. preload() effectively locks all of the specified database and therefore will lock out the checkpointer, cleaner, and compressor, as well as not allow eviction to occur.

Parameters:
config The PreloadConfig object that specifies the parameters of the preload.
Returns:
A PreloadStats object with the result of the preload operation and various statistics about the preload() operation.
Throws:
OperationFailureException if one of the Read Operation Failures occurs.
EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalStateException if any of the databases has been closed.
See also:
Database.preload(com.sleepycat.je.PreloadConfig)
    public PreloadStats preload(final Database[] databases,
                                final PreloadConfig config)
        throws DatabaseException {
        try {
            checkHandleIsValid();
            checkEnv();
            DatabaseUtil.checkForZeroLengthArrayParam(databases"databases");
            PreloadConfig useConfig =
                (config == null) ? new PreloadConfig() : config;
            int nDbs = databases.length;
            DatabaseImpl[] dbImpls = new DatabaseImpl[nDbs];
            for (int i = 0; i < nDbsi += 1) {
                dbImpls[i] = DbInternal.getDatabaseImpl(databases[i]);
            }