Berkeley DB Java Edition
version 3.2.76

com.sleepycat.je
Class Environment

java.lang.Object
  extended by com.sleepycat.je.Environment
Direct Known Subclasses:
XAEnvironment

public class Environment
extends Object

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 in the example.properties file included at the top of the distribution.

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, regardless of whether or not it throws an exception.


Field Summary
static String CHECKPOINTER_NAME
          The name of the Checkpointer daemon thread.
static String CLEANER_NAME
          The name of the cleaner daemon thread.
static String INCOMP_NAME
          The name of the IN Compressor daemon thread.
 
Constructor Summary
Environment(File envHome, EnvironmentConfig envConfig)
          Create a database environment handle.
 
Method Summary
 Transaction beginTransaction(Transaction parent, TransactionConfig txnConfig)
          Create a new transaction in the database environment.
 void checkpoint(CheckpointConfig checkpointConfig)
          Synchronously checkpoint the database environment.
 int cleanLog()
          Synchronously invoke database environment log cleaning.
 void close()
          The Environment.close method closes the Berkeley DB environment.
 void compress()
          Synchronously invoke the compressor mechanism which compacts in memory data structures after delete operations.
 void evictMemory()
          Synchronously invoke the mechanism for keeping memory usage within the cache size boundaries.
 EnvironmentConfig getConfig()
          Return this object's configuration.
 List getDatabaseNames()
          Return a List of database names for the database environment.
 File getHome()
          Return the database environment's home directory.
 LockStats getLockStats(StatsConfig config)
          Return the database environment's locking statistics.
 EnvironmentMutableConfig getMutableConfig()
          Return database environment attributes.
 EnvironmentStats getStats(StatsConfig config)
          Return the general database environment statistics.
 Transaction getThreadTransaction()
          Returns the transaction associated with this thread if implied transactions are being used.
 TransactionStats getTransactionStats(StatsConfig config)
          Return the database environment's transactional statistics.
 Database openDatabase(Transaction txn, String databaseName, DatabaseConfig dbConfig)
          Open, and optionally create, a Database.
 SecondaryDatabase openSecondaryDatabase(Transaction txn, String databaseName, Database primaryDatabase, SecondaryConfig secConfig)
          Open and optionally create a SecondaryDatabase.
 void removeDatabase(Transaction txn, String databaseName)
          Remove a database.
 void renameDatabase(Transaction txn, String databaseName, String newName)
          Rename a database.
 boolean scanLog(long startPosition, long endPosition, LogScanConfig config, LogScanner scanner)
          Scans raw log entries in the JE log between two given points, passing all records for a given set of databases to the scanRecord method of the given LogScanner object.
 void setMutableConfig(EnvironmentMutableConfig envMutableConfig)
          Set database environment attributes.
 void setThreadTransaction(Transaction txn)
          Sets the transaction associated with this thread if implied transactions are being used.
 void sync()
          Synchronously flush database environment databases to stable storage.
 long truncateDatabase(Transaction txn, String databaseName, boolean returnCount)
          Empty the database, discarding all records it contains.
 boolean verify(VerifyConfig verifyConfig, PrintStream out)
          Return if the database environment is consistent and correct.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

CLEANER_NAME

public static final String CLEANER_NAME
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.

See Also:
Constant Field Values

INCOMP_NAME

public static final String INCOMP_NAME
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.

See Also:
Constant Field Values

CHECKPOINTER_NAME

public static final String CHECKPOINTER_NAME
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.

See Also:
Constant Field Values
Constructor Detail

Environment

public Environment(File envHome,
                   EnvironmentConfig envConfig)
            throws DatabaseException
Create a database environment handle.

Parameters:
envHome - The database environment's home directory.

envConfig - The database environment attributes. If null, default attributes are used.

Throws:
IllegalArgumentException - if an invalid parameter was specified.

DatabaseException - if a failure occurs.
Method Detail

getHome

public File getHome()
             throws DatabaseException
Return the database environment's home directory.

Returns:
The database environment's home directory.

Throws:
DatabaseException - if a failure occurs.

getConfig

public EnvironmentConfig getConfig()
                            throws DatabaseException
Return this object's configuration.

Returns:
This object's configuration.

Throws:
DatabaseException - if a failure occurs.

beginTransaction

public Transaction beginTransaction(Transaction parent,
                                    TransactionConfig txnConfig)
                             throws DatabaseException
Create 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:
DatabaseException - if a failure occurs.

checkpoint

public void checkpoint(CheckpointConfig checkpointConfig)
                throws DatabaseException
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.

Parameters:
checkpointConfig - The checkpoint attributes. If null, default attributes are used.

Throws:
DatabaseException - if a failure occurs.

getLockStats

public LockStats getLockStats(StatsConfig config)
                       throws DatabaseException
Return the database environment's locking statistics.

Parameters:
config - The locking statistics attributes. If null, default attributes are used.

Returns:
The database environment's locking statistics.

Throws:
DatabaseException - if a failure occurs.

getTransactionStats

public TransactionStats getTransactionStats(StatsConfig config)
                                     throws DatabaseException
Return the database environment's transactional statistics.

Parameters:
config - The transactional statistics attributes. If null, default attributes are used.

Returns:
The database environment's transactional statistics.

Throws:
DatabaseException - if a failure occurs.

close

public void close()
           throws DatabaseException
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.

In multithreaded applications, only a single thread should call Environment.close. Other callers will see a DatabaseException complaining that the handle is already closed.

After Environment.close has been called, regardless of its return, the Berkeley DB environment handle may not be accessed again.

Throws:
DatabaseException - if a failure occurs.

openDatabase

public Database openDatabase(Transaction txn,
                             String databaseName,
                             DatabaseConfig dbConfig)
                      throws DatabaseException
Open, and optionally create, 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:
DatabaseNotFoundException - if the database file does not exist.

DatabaseException - if a failure occurs.

openSecondaryDatabase

public SecondaryDatabase openSecondaryDatabase(Transaction txn,
                                               String databaseName,
                                               Database primaryDatabase,
                                               SecondaryConfig secConfig)
                                        throws DatabaseException
Open and optionally create 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.

secConfig - The secondary database attributes. If null, default attributes are used.

Returns:
Database handle.

Throws:
DatabaseNotFoundException - if the database file does not exist.

DatabaseException - if a failure occurs.

removeDatabase

public void removeDatabase(Transaction txn,
                           String databaseName)
                    throws DatabaseException
Remove a database.

Applications should never remove databases with open Database handles.

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:
DeadlockException - if the operation was selected to resolve a deadlock.

DatabaseNotFoundException - if the database file does not exist.

DatabaseException - if a failure occurs.

renameDatabase

public void renameDatabase(Transaction txn,
                           String databaseName,
                           String newName)
                    throws DatabaseException
Rename a database.

Applications should never rename databases with open Database handles.

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:
DeadlockException - if the operation was selected to resolve a deadlock.

DatabaseNotFoundException - if the database file does not exist.

DatabaseException - if a failure occurs.

truncateDatabase

public long truncateDatabase(Transaction txn,
                             String databaseName,
                             boolean returnCount)
                      throws DatabaseException
Empty the database, discarding all records it contains.

When called on a database configured with secondary indices, the application is responsible for also truncating all associated secondary indices.

Applications should never truncate databases with open Database handles.

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:
DeadlockException - if the operation was selected to resolve a deadlock.

DatabaseNotFoundException - if the database file does not exist.

DatabaseException - if a failure occurs.

sync

public void sync()
          throws DatabaseException
Synchronously flush database environment databases to stable storage.

Throws:
DatabaseException - if a failure occurs.

cleanLog

public int cleanLog()
             throws DatabaseException
Synchronously invoke 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 je.cleaner.minUtilization 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 a database environment owned background thread.

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

In the second use case, "batch cleaning", the application disables the cleaner thread 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);
      }

Returns:
The number of log files that were cleaned, and that will be deleted (or renamed) when a qualifying checkpoint occurs.

Throws:
DatabaseException - if a failure occurs.

evictMemory

public void evictMemory()
                 throws DatabaseException
Synchronously invoke 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:
DatabaseException - if a failure occurs.

compress

public void compress()
              throws DatabaseException
Synchronously invoke 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:
DatabaseException - if a failure occurs.

setMutableConfig

public void setMutableConfig(EnvironmentMutableConfig envMutableConfig)
                      throws DatabaseException
Set database environment attributes.

Attributes only apply to a specific Environment object and are not necessarily shared by other Environment objects accessing this database environment.

Parameters:
envMutableConfig - The database environment attributes. If null, default attributes are used.

Throws:
DatabaseException - if a failure occurs.

getMutableConfig

public EnvironmentMutableConfig getMutableConfig()
                                          throws DatabaseException
Return database environment attributes.

Returns:
Environment attributes

Throws:
DatabaseException - if a failure occurs.

getStats

public EnvironmentStats getStats(StatsConfig config)
                          throws DatabaseException
Return the general database environment statistics.

Parameters:
config - The general statistics attributes. If null, default attributes are used.

Returns:
The general database environment statistics.

Throws:
DatabaseException - if a failure occurs.

getDatabaseNames

public List getDatabaseNames()
                      throws DatabaseException
Return a List of database names for the database environment.

Each element in the list is a String.

Returns:
A List of database names for the database environment.

Throws:
DatabaseException - if a failure occurs.

scanLog

public boolean scanLog(long startPosition,
                       long endPosition,
                       LogScanConfig config,
                       LogScanner scanner)
                throws DatabaseException
Scans raw log entries in the JE log between two given points, passing all records for a given set of databases to the scanRecord method of the given LogScanner object.

EnvironmentStats.getEndOfLog should be used to get the end-of-log at a particular point in time. Values returned by that method can be passed for the startPostion and endPosition parameters.

WARNING: This interface is meant for low level processing of log records, not for application level queries. See LogScanner for further restrictions!

Parameters:
startPosition - the log position at which to start scanning. If no such log position exists, the first existing position greater or less (if forward is true or false) is used.

endPosition - the log position at which to stop scanning. If no such log position exists, the first existing position less or greater (if forward is true or false) is used.

config - the parameters for this scanLog invocation.

scanner - is an object of a class that implements the LogScanner interface, to process scanned records.

Returns:
true if the scan was completed, or false if the scan was canceled because LogScanner.scanRecord returned false.

Throws:
DatabaseException - if a failure occurs.

verify

public boolean verify(VerifyConfig verifyConfig,
                      PrintStream out)
               throws DatabaseException
Return if the database environment is consistent and correct.

Verification is an expensive operation that should normally only be used for troubleshooting and debugging.

Parameters:
verifyConfig - The verification attributes. If null, default attributes are used.

out - The stream to which verification debugging information is written.

Returns:
If the database environment is consistent and correct.

Throws:
DatabaseException - if a failure occurs.

getThreadTransaction

public Transaction getThreadTransaction()
                                 throws DatabaseException
Returns the transaction associated with this thread if implied transactions are being used. Implied transactions are used in an XA or JCA "Local Transaction" environment. In an XA environment the XAEnvironment.start() entrypoint causes a transaction to be created and become associated with the calling thread. Subsequent API calls implicitly use that transaction. XAEnvironment.end() causes the transaction to be disassociated with the thread. In a JCA Local Transaction environment, the call to JEConnectionFactory.getConnection() causes a new transaction to be created and associated with the calling thread.

Throws:
DatabaseException

setThreadTransaction

public void setThreadTransaction(Transaction txn)
Sets the transaction associated with this thread if implied transactions are being used. Implied transactions are used in an XA or JCA "Local Transaction" environment. In an XA environment the XAEnvironment.start() entrypoint causes a transaction to be created and become associated with the calling thread. Subsequent API calls implicitly use that transaction. XAEnvironment.end() causes the transaction to be disassociated with the thread. In a JCA Local Transaction environment, the call to JEConnectionFactory.getConnection() causes a new transaction to be created and associated with the calling thread.


Berkeley DB Java Edition
version 3.2.76

Copyright 1996,2008 Oracle. All rights reserved.