Closing Database Environments
Prev | Chapter 2. Database Environments | Next

## Closing Database Environments

You close your environment by calling the `Environment.close()` method. This method performs a checkpoint, so it is not necessary to perform a sync or a checkpoint explicitly before calling it. For information on checkpoints, see the Berkeley DB Java Edition Getting Started with Transaction Processing guide. For information on syncs, see Database Modifications and Syncs.

    import com.sleepycat.je.DatabaseException;

    import com.sleepycat.je.Environment;

    ...

    try {
        if (myDbEnvironment != null) {
            myDbEnvironment.close();
        }
    } catch (DatabaseException dbe) {
        // Exception handling goes here
    }

You should close your environment(s) only after all other database activities have completed and you have closed any databases currently opened in the environment.

### Note

It is possible for the environment to close before JE's cleaner thread has finished its work. This happens if you perform a large number of deletes immediately before shutting down your environment. The result is that your log files may be quit a lot larger than you expect them to be because the cleaner thread has not had a chance to finish its work.

See The Cleaner Thread for details on the cleaner threads.

See the Getting Started with Berkeley DB Java Edition guide for information on the cleaner threads.

If want to make sure that the cleaner has finished running before the environment is closed, call `Environment.cleanLog()` before calling `Environment.close()`:

    import com.sleepycat.je.DatabaseException;

    import com.sleepycat.je.Environment;

    ...

    try {
        if (myDbEnvironment != null) {
            myDbEnvironment.cleanLog(); // Clean the log before closing
            myDbEnvironment.close();
        }
    } catch (DatabaseException dbe) {
        // Exception handling goes here
    }

Closing the last environment handle in your application causes all internal data structures to be released and the background threads to be stopped. If there are any opened databases, then JE will complain before closing them as well. At this time, any open cursors are also closed, and any on-going transactions are aborted. At this time, and any on-going transactions are aborted.

Prev | Up | Next
Chapter 2. Database Environments | Home | Environment Properties