November 2006: Getting To Know Berkeley DB Java Edition

Getting To Know Berkeley DB Java Edition

By Weiqi Gao, OCI Principal Software Engineer

November 2006


Introduction

Berkeley DB Java Edition is an embedded database written in pure Java. It allows efficient persistence of data into local disks. It provides full ACID transaction semantics for data storage. It uses an in-memory cache to speed up data reads when the working set can fit into memory. And its log-based storage system makes data writes very fast.

Berkeley DB Java Edition also supports Java Transaction API (JTA), J2EE Connector Architecture (JCA) and Java Management Extensions (JMX), making it easily integrated into many Java EE application servers.

The latest release of Berkeley DB Java Edition contains an API known as the Direct Persistence Layer (DPL), which is similar to the Java Persistence API (API). This layer is built on top of the lower-level byte array based Berkeley DB Java Edition engine. Berkeley DB Java Edition also contains an implementation of the Java Collections API that is backed by the same engine.

On the administrative side, Berkeley DB Java Edition uses an architecture-neutral file format and supports hot backups.

Licensing and History

The free software Berkeley DB (the C Edition, or the Core Edition, to distinguish from the Java Edition) has been in existence since 1991. The original authors of Berkeley DB founded the Sleepycat Software company in 1996 to further develop and support, both through a free software license and a commercial license, the Berkeley DB software. Software that redistributes Berkeley DB must be either itself available as free software or use a commercially licensed Berkeley DB.

A JNI-based Java binding for Berkeley DB (Core Edition) was introduced soon after the Java programming language become popular. Sleepycat released a pure Java version Berkeley DB in 2004.

Oracle Corporation acquired Sleepycat Software in February 2006 to expand its line of embeddable database products.

Oracle has continued both the development and the dual licensing model of Sleepycat's line of database products: Berkeley DB (Core Edition), Berkeley DB XML and Berkeley DB Java Edition.

Oracle Berkeley DB Java Edition 3.1.0 was released in September 2006.

Contrast with Other Kinds of Databases

When thinking about databases, the first thing that comes to a Java developer's mind is probably relational database servers. These servers have a communications layer that allows a remote application to connect to the database process, a SQL compiler that understands and executes SQL queries from the application, and an interactive shell that allows users and administrators to perform ad hoc queries. Berkeley DB Java Edition has none of these.

What it does have is a transaction engine that offers full ACID (Atomicity, Consistency, Isolation and Durability) semantics, an in-memory cache that manages the data using B+trees, and a persistence engine that writes log files to local disks. Everything Berkeley DB Java Edition does happens inside the same JVM instance where the application is hosted. In other words, the database is embedded within the application process as a jar file in the classpath.

These characteristics makes Berkeley DB Java Edition uniquely suitable for a wide class of applications that does not require the additional features from a full-fledged relational database server. These applications tend to have a relatively stable and small data schema, a very dynamic but usually bounded data set, and high throughput requirements.

In this article, I will take you though a Java application developer's tour of Oracle Berkeley DB Java Edition, henceforth referred to as JE, the shorthand name used in its documentation.

What's In the Download

JE is available for download from the Oracle Berkeley DB website. The download bundle can be unzipped or untarred into a single directory je-3.1.0 that contains the following files and subdirectories:

[weiqi@gao] $ ls je-3.1.0ant/              dist/               examples/            LICENSE  test/
build.properties  docs/               FindBugsExclude.xml  README
build.xml         example.properties  lib/                 src/

The src and test directories contain the source code and a set of tests for the JE product. The lib directory contains a single jar file named je-3.1.0.jar. This 1.1MB file is the only jar file needed to use JE. It does not depend on anything but the JDK. The Direct Persistence Layer (DPL) requires Java 5 or later. The rest of the JE requires Java 1.4.2 or later. The jar file contains a Main-Class manifest declaration and can be used to invoke administrative utilities.

The docs directory contains a rich set of documentation typical of the Berkeley DB family of products. Aside from the usual release notes, installation instructions and javadocs, four books are included, in both HTML and PDF format:

The examples directory contains example programs illustrating JE features. The release notes have detailed instructions on how to compile and use the example classes.

The online books are written in a tutorial style and does not assume any prior database programming experience. Together with the javadocs and the examples, they provide a thorough introduction to JE basics, its transaction engine and the two frameworks built on top of JE: the Direct Persistence Layer and the Java Collections API. And because of the availability of these excellent tutorials, I will try to simply highlight some of the interesting features of JE.

Let's Create A Database

JE's terminology is slightly different from those of the relational database world. To work with JE data, we use Environments. A JE Environment is roughly equivalent to what the relational database world calls a database or a schema, and a JE Database corresponds to an relational database table. However a JE database has only two columns: key and data. In this regard a JE database is more like a Java TreeMap.

  1. import com.sleepycat.je.Database;
  2. import com.sleepycat.je.DatabaseConfig;
  3. import com.sleepycat.je.DatabaseException;
  4. import com.sleepycat.je.Environment;
  5. import com.sleepycat.je.EnvironmentConfig;
  6.  
  7. import java.io.File;
  8.  
  9. public class CreateDatabase {
  10. public static void main(String[] args) throws DatabaseException {
  11. EnvironmentConfig envConfig = new EnvironmentConfig();
  12. envConfig.setAllowCreate(true);
  13. envConfig.setTransactional(true);
  14. Environment env =
  15. new Environment(new File("./envHome"), envConfig);
  16.  
  17. DatabaseConfig dbConfig = new DatabaseConfig();
  18. dbConfig.setAllowCreate(true);
  19. dbConfig.setTransactional(true);
  20. dbConfig.setSortedDuplicates(true);
  21. Database db =
  22. env.openDatabase(null, "randomBytes", dbConfig);
  23.  
  24. db.close();
  25. env.close();
  26. }
  27. }

This opens a JE environment in the directory ./envHome and a database named randomBytes within the environment. The variable env is called an environment handle and db a database handle. The environment handle is created with a constructor and it in turn is a factory of database handles.

JE supports many configuration properties for the various handles it creates. These properties are passed in to the constructors or factory methods of the handles as a configuration object parameter. The above example shows the usage of EnvironmentConfig and DatabaseConfig objects and later examples will show the usage of CursorConfig, TransactionConfig and SecondaryConfig objects. A null, or a *Config.DEFAULT object can be passed in if the default properties are desired. Properties can also be set in a je.properties file in the environment home directory. An example.properties file is available in the je-3.1.0 directory that lists all the properties, their default values, and whether they can be modified after creation.

The same *Config object can be reused in the creation of subsequent handles. Changes made to config objects will not affect handles already opened.

A subset of the environment configuration properties can be modified at run time through a EnvironmentMutableConfig object obtained from the environment handle.

The environment home directory must exist prior to opening an environment, or a DatabaseException is thrown. If the directory is empty and the allowCreate property is true, an environment will be created. If the directory is empty and allowCreate is false, a DatabaseException is thrown.

From the above example, one can see that the transactional properties can be turned on or off for the environment or for individual databases in the environment. However, if transaction is turned off for the environment then it must be off for all databases that are opened in that environment.

[weiqi@gao] $ java CreateDatabaseException in thread "main" com.sleepycat.je.DatabaseException: (JE 3.1.0) The En
vironment directory /home/weiqi/perm/JNB/berkeleydb/classes/production/berkeleyd
b/./envHome is not writable, but the Environment was opened for read-write acces
s.
        [Stacktrace ...]
[weiqi@gao] $ mkdir envHome[weiqi@gao] $ java CreateDatabase[weiqi@gao] $ ls envHome00000000.jdb  je.lck

When JE creates an environment, it simply creates a couple of files: a log file 00000000.jdb and a lock file je.lck. It is not obvious what JE databases are available in an environment by looking into the environment home directory. JE appends all persistent activities such as transactions, insertions, updates and deletions to the log file. When 00000000.jdb is full (the default size is 10MB), 00000001.jdb is created, etc., up to ffffffff.jdb. If an environment is opened as read-write, a log cleaning thread is started that monitors log files utilization. When most of the records in a particular log file have been obsoleted by updates or deletions in later log files, the log cleaning thread copies the remaining records to the end of the latest log file and deletes the old log file. The cleaner chooses which log file to operate based on the current space utilization within the log file.

The JE log file format is architecture neutral and can be copied from machine to machine regardless of processor types or operating systems. However this file format is not compatible with that of Berkeley DB Core Edition.

Byte Arrays Are the Key (and the Data)

At the lowest level, JE supports only one data type, the byte array type. It encapsulates byte arrays into the DatabaseEntry class. The following class inserts 100000 1k records into the randomBytes database:

  1. import com.sleepycat.je.Database;
  2. import com.sleepycat.je.DatabaseConfig;
  3. import com.sleepycat.je.DatabaseEntry;
  4. import com.sleepycat.je.DatabaseException;
  5. import com.sleepycat.je.Environment;
  6. import com.sleepycat.je.EnvironmentConfig;
  7. import com.sleepycat.je.Transaction;
  8.  
  9. import java.io.File;
  10. import java.util.Random;
  11.  
  12. public class CreateRandomBytes {
  13. private static final int NUM_RECORDS = 100000;
  14.  
  15. public static void main(String[] args) throws DatabaseException {
  16. EnvironmentConfig envConfig = new EnvironmentConfig();
  17. envConfig.setAllowCreate(true);
  18. envConfig.setTransactional(true);
  19. Environment env =
  20. new Environment(new File("./envHome"), envConfig);
  21.  
  22. DatabaseConfig dbConfig = new DatabaseConfig();
  23. dbConfig.setAllowCreate(true);
  24. dbConfig.setTransactional(true);
  25. dbConfig.setSortedDuplicates(true);
  26. Database db = env.openDatabase(null, "randomBytes", dbConfig);
  27.  
  28. Transaction txn = env.beginTransaction(null, null);
  29. byte[] key = new byte[4];
  30. byte[] data = new byte[1024];
  31. long startTime = System.currentTimeMillis();
  32.  
  33. for (int i = 0; i < NUM_RECORDS; i++) {
  34. fillKey(i, key);
  35. fillData(data);
  36. try {
  37. db.put(txn, new DatabaseEntry(key),
  38. new DatabaseEntry(data));
  39. } catch (DatabaseException e) {
  40. txn.abort();
  41. throw e;
  42. }
  43. }
  44. txn.commit();
  45.  
  46. long endTime = System.currentTimeMillis();
  47. System.out.println("Inserted " + NUM_RECORDS + " 1k records in " +
  48. (endTime - startTime) + " milliseconds");
  49. db.close();
  50. env.close();
  51. }
  52.  
  53. private static void fillKey(int i, byte[] key) {
  54. key[0] = (byte) i;
  55. key[1] = (byte) (i >> 8);
  56. key[2] = (byte) (i >> 16);
  57. key[3] = (byte) (i >> 24);
  58. }
  59.  
  60. private static void fillData(byte[] data) {
  61. Random random = new Random();
  62. random.nextBytes(data);
  63. }
  64. }

We obtain a transaction from the environment by calling the beginTransaction method, passing in two nulls as parameters. The first parameter is the parent transaction and must be set to null as JE does not yet support nested transactions. The second parameter is a TransactionConfig and we pass in null to use the default properties.

[weiqi@gao] $ mkdir envHome[weiqi@gao] $ java CreateRandomBytesInserted 100000 1k records in 8319 milliseconds
[weiqi@gao] $ ls -l envHometotal 112428
-rw-rw-r-- 1 weiqi weiqi 9999708 Oct 22 10:59 00000000.jdb
-rw-rw-r-- 1 weiqi weiqi 9999885 Oct 22 10:59 00000001.jdb
-rw-rw-r-- 1 weiqi weiqi 9998931 Oct 22 10:59 00000002.jdb
-rw-rw-r-- 1 weiqi weiqi 9999622 Oct 22 10:59 00000003.jdb
-rw-rw-r-- 1 weiqi weiqi 9998944 Oct 22 10:59 00000004.jdb
-rw-rw-r-- 1 weiqi weiqi 9999171 Oct 22 10:59 00000005.jdb
-rw-rw-r-- 1 weiqi weiqi 9999133 Oct 22 10:59 00000006.jdb
-rw-rw-r-- 1 weiqi weiqi 9999709 Oct 22 10:59 00000007.jdb
-rw-rw-r-- 1 weiqi weiqi 9999639 Oct 22 10:59 00000008.jdb
-rw-rw-r-- 1 weiqi weiqi 9999297 Oct 22 10:59 00000009.jdb
-rw-rw-r-- 1 weiqi weiqi 9999216 Oct 22 10:59 0000000a.jdb
-rw-rw-r-- 1 weiqi weiqi 4851872 Oct 22 10:59 0000000b.jdb
-rw-rw-r-- 1 weiqi weiqi       0 Oct 22 10:59 je.lck
[weiqi@gao] $ java CreateRandomBytesInserted 100000 1k records in 76100 milliseconds
[weiqi@gao] $ ls -l envHometotal 1186436
-rw-rw-r-- 1 weiqi weiqi 9999708 Oct 22 10:59 00000000.jdb
-rw-rw-r-- 1 weiqi weiqi 9999885 Oct 22 10:59 00000001.jdb
......
-rw-rw-r-- 1 weiqi weiqi 9998394 Oct 22 11:28 00000078.jdb
-rw-rw-r-- 1 weiqi weiqi 2255609 Oct 22 11:28 00000079.jdb
-rw-rw-r-- 1 weiqi weiqi       0 Oct 22 11:27 je.lck

The sortedDuplicates property of databases is saved on disk when a database is first created. All subsequent opens of the database must use the same property value. This property controls duplicate data in the database. If this property is false, putting a key-data pair with an existing key will overwrite the old data. If it is set to true, putting a key-data pair with an existing key will cause both the new data and the old data to be saved in the database.

Here are the numbers if sortedDuplicates is set to false:

[weiqi@gao] $ java CreateRandomBytesInserted 100000 1k records in 8243 milliseconds
[weiqi@gao] $ java CreateRandomBytesInserted 100000 1k records in 13532 milliseconds
[weiqi@gao] $ java CreateRandomBytesInserted 100000 1k records in 15955 milliseconds

For the remainder of these article, we will use a version of CreateRandomBytes where sortedDuplicates is false.

Turning Anything into a Byte Array (Data Binding)

As illustrated in the last section, JE stores only byte arrays. If you want to store anything other than byte arrays, you have to do the conversion when inserting or retrieving values.

JE provides a Bind API to help with this process. It defines the EntryBinding interface:

interface EntryBinding {
    Object entryToObject(DatabaseEntry entry);
    void objectToEntry(Object object, DatabaseEntry entry);
}

Implementations of this interface are provided in JE to handle Java primitive types, Strings and Serializable objects. An abstract class TupleBinding can be extended to handle other kinds of objects.

Here is what it takes to convert a long and String key-data pair into DatabaseEntrys (Notice that the TupleBinding abstract class is also the factory for concrete bindings for primitive types and String):

  1. import com.sleepycat.bind.EntryBinding;
  2. import com.sleepycat.bind.tuple.TupleBinding;
  3. import com.sleepycat.je.DatabaseEntry;
  4.  
  5. public class PrimitiveBinding {
  6. public static void main(String[] args) {
  7. long longKey = 1234567890L;
  8. String stringData = "This is a test.";
  9.  
  10. // Manufacture the bindings
  11. EntryBinding longBinding =
  12. TupleBinding.getPrimitiveBinding(Long.class);
  13. EntryBinding stringBinding =
  14. TupleBinding.getPrimitiveBinding(String.class);
  15.  
  16. // To entries
  17. DatabaseEntry key = new DatabaseEntry();
  18. DatabaseEntry data = new DatabaseEntry();
  19. longBinding.objectToEntry(longKey, key);
  20. stringBinding.objectToEntry(stringData, data);
  21.  
  22. // And back
  23. long outLongKey =
  24. (Long) longBinding.entryToObject(key);
  25. String outStringData =
  26. (String) stringBinding.entryToObject(data);
  27. assert longKey == outLongKey;
  28. assert stringData.equals(outStringData);
  29. }
  30. }

Here is what it takes to extend TupleBinding to handle a custom data structure. The Book class contains a couple of String fields:

  1. public class Book {
  2. public String title;
  3. public String author;
  4. }

The BookBinding extends TupleBinding and uses TupleInput and TupleOutput objects to convert Bookobjects to byte arrays:

  1. import com.sleepycat.bind.tuple.TupleBinding;
  2. import com.sleepycat.bind.tuple.TupleInput;
  3. import com.sleepycat.bind.tuple.TupleOutput;
  4.  
  5. public class BookBinding extends TupleBinding {
  6.  
  7. public Object entryToObject(TupleInput input) {
  8. Book book = new Book();
  9. book.title = input.readString();
  10. book.author = input.readString();
  11. return book;
  12. }
  13.  
  14. public void objectToEntry(Object object, TupleOutput output) {
  15. Book book = (Book) object;
  16. output.writeString(book.title);
  17. output.writeString(book.author);
  18. }
  19. }

One thing to note here is that the order that you read data from input must be exactly the same as the order in which it was written to output. Another thing to note is the lack of type safety in this approach. You can put a Book into a database and get out an object of another type that has the same structure as a Book.

JE also contains a SerialBinding class that works with any Serializable objects without having to write a custom TupleBinding. Since Java serialization format contains repetitive classes information, JE uses a revised scheme that puts the classes information into a separate database.

Navigation with Cursors

JE Database objects have a get method that allows you to retrieve the data based on a key. We can read back the random bytes from the randomBytes database using the following program:

  1. import com.sleepycat.je.Database;
  2. import com.sleepycat.je.DatabaseConfig;
  3. import com.sleepycat.je.DatabaseEntry;
  4. import com.sleepycat.je.DatabaseException;
  5. import com.sleepycat.je.Environment;
  6. import com.sleepycat.je.EnvironmentConfig;
  7. import com.sleepycat.je.LockMode;
  8. import com.sleepycat.je.OperationStatus;
  9. import com.sleepycat.je.Transaction;
  10.  
  11. import java.io.File;
  12.  
  13. public class RetrieveRandomBytes {
  14. private static final int NUM_RECORDS = 100000;
  15.  
  16. public static void main(String[] args) throws DatabaseException {
  17. EnvironmentConfig envConfig = new EnvironmentConfig();
  18. envConfig.setTransactional(true);
  19. envConfig.setReadOnly(true);
  20. Environment env =
  21. new Environment(new File("./envHome"), envConfig);
  22.  
  23. DatabaseConfig dbConfig = new DatabaseConfig();
  24. dbConfig.setTransactional(true);
  25. dbConfig.setSortedDuplicates(false);
  26. dbConfig.setReadOnly(true);
  27. Database db = env.openDatabase(null, "randomBytes", dbConfig);
  28.  
  29. Transaction txn = env.beginTransaction(null, null);
  30. byte[] keyBytes = new byte[4];
  31. DatabaseEntry data = new DatabaseEntry();
  32. long startTime = System.currentTimeMillis();
  33.  
  34. for (int i = 0; i < NUM_RECORDS; i++) {
  35. fillKey(i, keyBytes);
  36. DatabaseEntry key = new DatabaseEntry(keyBytes);
  37. try {
  38. if (db.get(txn, key, data, LockMode.DEFAULT) ==
  39. OperationStatus.SUCCESS) {
  40. byte[] dataBytes = data.getData();
  41. assert dataBytes.length == 1024;
  42. } else {
  43. throw new RuntimeException("db.get() failed.");
  44. }
  45. } catch (DatabaseException e) {
  46. txn.abort();
  47. throw e;
  48. }
  49. }
  50. txn.commit();
  51.  
  52. long endTime = System.currentTimeMillis();
  53. System.out.println("Retrieved " + NUM_RECORDS + " 1k records in " +
  54. (endTime - startTime) + " milliseconds");
  55.  
  56. db.close();
  57. env.close();
  58. }
  59.  
  60. private static void fillKey(int i, byte[] key) {
  61. key[0] = (byte) i;
  62. key[1] = (byte) (i >> 8);
  63. key[2] = (byte) (i >> 16);
  64. key[3] = (byte) (i >> 24);
  65. }
  66. }

We open the environment and database as read only, reconstructed each key and retrieved the the corresponding data from the database.

[weiqi@gao] $ java CreateRandomBytesInserted 100000 1k records in 8287 milliseconds
[weiqi@gao] $ java -ea RetrieveRandomBytesRetrieved 100000 1k records in 5646 milliseconds

To iterate over the data in a database without prior knowledge of the keys, we use the JECursor class.

  1. import com.sleepycat.je.Cursor;
  2. import com.sleepycat.je.Database;
  3. import com.sleepycat.je.DatabaseConfig;
  4. import com.sleepycat.je.DatabaseEntry;
  5. import com.sleepycat.je.DatabaseException;
  6. import com.sleepycat.je.Environment;
  7. import com.sleepycat.je.EnvironmentConfig;
  8. import com.sleepycat.je.LockMode;
  9. import com.sleepycat.je.OperationStatus;
  10. import com.sleepycat.je.Transaction;
  11.  
  12. import java.io.File;
  13.  
  14. public class IterateRandomBytes {
  15. public static void main(String[] args) throws DatabaseException {
  16. EnvironmentConfig envConfig = new EnvironmentConfig();
  17. envConfig.setTransactional(true);
  18. envConfig.setReadOnly(true);
  19. Environment env =
  20. new Environment(new File("./envHome"), envConfig);
  21.  
  22. DatabaseConfig dbConfig = new DatabaseConfig();
  23. dbConfig.setTransactional(true);
  24. dbConfig.setSortedDuplicates(false);
  25. dbConfig.setReadOnly(true);
  26. Database db = env.openDatabase(null, "randomBytes", dbConfig);
  27.  
  28. Transaction txn = env.beginTransaction(null, null);
  29. DatabaseEntry key = new DatabaseEntry();
  30. DatabaseEntry data = new DatabaseEntry();
  31. long startTime = System.currentTimeMillis();
  32. int recordsVisited = 0;
  33.  
  34. Cursor cursor = db.openCursor(txn, null);
  35. while (cursor.getNext(key, data, LockMode.DEFAULT) ==
  36. OperationStatus.SUCCESS) {
  37. byte[] dataBytes = data.getData();
  38. assert dataBytes.length == 1024;
  39. recordsVisited++;
  40. }
  41. cursor.close();
  42. txn.commit();
  43.  
  44. long endTime = System.currentTimeMillis();
  45. System.out.println("Retrieved " + recordsVisited + " 1k records in " +
  46. (endTime - startTime) + " milliseconds");
  47.  
  48. db.close();
  49. env.close();
  50. }
  51. }

Here we call the database handle's openCursor method to get a Cursor. Two parameters are passed in: a Transaction, and a null for CursorConfig to use the default properties. We then use the getNext method to walk through all the records in the database. Executing CreateRandomBytes followed by IterateRandomBytes yields the following results:

[weiqi@gao] $ java CreateRandomBytesInserted 100000 1k records in 7887 milliseconds
[weiqi@gao] $ java -ea IterateRandomBytesRetrieved 100000 1k records in 4761 milliseconds

Aside from the getNext method that moves the cursor to the next record in the database (a newly opened cursor points to one prior to the first record), the Cursor class also has the following cursor position methods:

 getPrev
 
  moves to the previous record (a newly opened cursor also points to one past the last record)  
 getFirst
 
  moves to the first record
 getLast
 
  moves to the last record
 getSearchKey
 
  moves to record with matching key
 getSearchKeyRange
 
  moves to first record at or just past the given key
 getSearchBoth
 
  moves to record with matching key and data
 getSearchBothRange
 
  moves to first record with matching key and data at or just past the given data)

The search methods account for duplicate data values with the same key.

You can also insert, update and delete records using the put, putCurrent and delete methods of the Cursor class. More elaborate methods exists to deal with duplicate data situations. Here is a little program that deletes all the random bytes that we created:

  1. import com.sleepycat.je.Cursor;
  2. import com.sleepycat.je.Database;
  3. import com.sleepycat.je.DatabaseConfig;
  4. import com.sleepycat.je.DatabaseEntry;
  5. import com.sleepycat.je.DatabaseException;
  6. import com.sleepycat.je.Environment;
  7. import com.sleepycat.je.EnvironmentConfig;
  8. import com.sleepycat.je.LockMode;
  9. import com.sleepycat.je.OperationStatus;
  10. import com.sleepycat.je.Transaction;
  11.  
  12. import java.io.File;
  13.  
  14. public class DeleteRandomBytes {
  15. public static void main(String[] args) throws DatabaseException {
  16. EnvironmentConfig envConfig = new EnvironmentConfig();
  17. envConfig.setTransactional(true);
  18. Environment env =
  19. new Environment(new File("./envHome"), envConfig);
  20.  
  21. DatabaseConfig dbConfig = new DatabaseConfig();
  22. dbConfig.setTransactional(true);
  23. dbConfig.setSortedDuplicates(false);
  24. Database db = env.openDatabase(null, "randomBytes", dbConfig);
  25.  
  26. Transaction txn = env.beginTransaction(null, null);
  27. DatabaseEntry key = new DatabaseEntry();
  28. DatabaseEntry data = new DatabaseEntry();
  29. long startTime = System.currentTimeMillis();
  30. int recordsDeleted = 0;
  31.  
  32. Cursor cursor = db.openCursor(txn, null);
  33. while (cursor.getNext(key, data, LockMode.DEFAULT) ==
  34. OperationStatus.SUCCESS) {
  35. cursor.delete();
  36. recordsDeleted++;
  37. }
  38. cursor.close();
  39. txn.commit();
  40.  
  41. long endTime = System.currentTimeMillis();
  42. System.out.println("Deleted " + recordsDeleted + " 1k records in " +
  43. (endTime - startTime) + " milliseconds");
  44.  
  45. db.close();
  46. env.cleanLog();
  47. env.close();
  48. }
  49. }

We simply delete each record as we iterate through the cursor. We also call the Environment.cleanLog() method right before we close the environment handle. In our scenario this causes some of the log files, which now contain deleted records, to be removed.

Executing CreateRandomBytes followed by DeleteRandomBytes yields the following numbers:

[weiqi@gao] $ java CreateRandomBytesInserted 100000 1k records in 8084 milliseconds
[weiqi@gao] $ java DeleteRandomBytesDeleted 100000 1k records in 5076 milliseconds
[weiqi@gao] $ java DeleteRandomBytes
Deleted 0 1k records in 951 milliseconds

Secondary Databases Are Indexes

The JE cursor allows us to search a database based on the keys of the records. Sometimes an application may wish to search the database using something other than the keys. The way to make this possible in JE is to use a secondary database (an index in relational database terminology.)

The data in secondary databases are the keys of its associated primary database and the keys are generated from data in the primary database. The primary database handle and the key creator are two pieces of information needed when a secondary database is opened. A primary database cannot allow duplicate records when a secondary database is used. However, a secondary database should generally allow duplicate records.

In the next example, we create a secondary database keyed off of the tenth byte of the byte array data in the primary database and then use that secondary database to find all primary data whose tenth byte is 42.

We first implement a TenthByteKeyCreator:

  1. import com.sleepycat.je.DatabaseEntry;
  2. import com.sleepycat.je.DatabaseException;
  3. import com.sleepycat.je.SecondaryDatabase;
  4. import com.sleepycat.je.SecondaryKeyCreator;
  5.  
  6. public class TenthByteKeyCreator implements SecondaryKeyCreator {
  7.  
  8. public boolean createSecondaryKey(SecondaryDatabase secondary,
  9. DatabaseEntry key,
  10. DatabaseEntry data,
  11. DatabaseEntry result)
  12. throws DatabaseException {
  13. byte[] tenthByte = new byte[1];
  14. tenthByte[0] = data.getData()[9];
  15. result.setData(tenthByte);
  16. return true;
  17. }
  18. }

The SecondaryKeyCreator interface has only one method createSecondaryKey(). We have access to the secondary database itself, the key-data pair of the primary database record, and a result that is to become the key in the secondary database. We simply grab the tenth byte out of the primary data and stuff it into the result.

  1. import com.sleepycat.je.Database;
  2. import com.sleepycat.je.DatabaseConfig;
  3. import com.sleepycat.je.DatabaseEntry;
  4. import com.sleepycat.je.DatabaseException;
  5. import com.sleepycat.je.Environment;
  6. import com.sleepycat.je.EnvironmentConfig;
  7. import com.sleepycat.je.LockMode;
  8. import com.sleepycat.je.OperationStatus;
  9. import com.sleepycat.je.SecondaryConfig;
  10. import com.sleepycat.je.SecondaryCursor;
  11. import com.sleepycat.je.SecondaryDatabase;
  12. import com.sleepycat.je.Transaction;
  13.  
  14. import java.io.File;
  15. import java.util.Random;
  16.  
  17. public class IndexRandomBytes {
  18. private static final int NUM_RECORDS = 100000;
  19.  
  20. public static void main(String[] args) throws DatabaseException {
  21. EnvironmentConfig envConfig = new EnvironmentConfig();
  22. envConfig.setAllowCreate(true);
  23. envConfig.setTransactional(true);
  24. Environment env =
  25. new Environment(new File("./envHome"), envConfig);
  26.  
  27. DatabaseConfig dbConfig = new DatabaseConfig();
  28. dbConfig.setAllowCreate(true);
  29. dbConfig.setTransactional(true);
  30. dbConfig.setSortedDuplicates(false);
  31. Database db = env.openDatabase(null, "randomBytes", dbConfig);
  32.  
  33. SecondaryConfig secondaryConfig = new SecondaryConfig();
  34. secondaryConfig.setAllowCreate(true);
  35. secondaryConfig.setAllowPopulate(true);
  36. secondaryConfig.setTransactional(true);
  37. secondaryConfig.setKeyCreator(new TenthByteKeyCreator());
  38. secondaryConfig.setSortedDuplicates(true);
  39. SecondaryDatabase index =
  40. env.openSecondaryDatabase(null, "tenth-byte",
  41. db, secondaryConfig);
  42.  
  43. populatePrimary(env, db);
  44.  
  45. searchIndex(env, index);
  46.  
  47. index.close();
  48. db.close();
  49. env.cleanLog();
  50. env.close();
  51. }
  52.  
  53. private static void populatePrimary(Environment env, Database db)
  54. throws DatabaseException {
  55. Transaction txn = env.beginTransaction(null, null);
  56. byte[] key = new byte[4];
  57. byte[] data = new byte[1024];
  58. long startTime = System.currentTimeMillis();
  59.  
  60. for (int i = 0; i < NUM_RECORDS; i++) {
  61. fillKey(i, key);
  62. fillData(data);
  63. try {
  64. db.put(txn, new DatabaseEntry(key),
  65. new DatabaseEntry(data));
  66. } catch (DatabaseException e) {
  67. txn.abort();
  68. throw e;
  69. }
  70. }
  71. txn.commit();
  72.  
  73. long endTime = System.currentTimeMillis();
  74. System.out.println("Inserted " + NUM_RECORDS + " 1k records in " +
  75. (endTime - startTime) + " milliseconds");
  76. }
  77.  
  78. private static void searchIndex(Environment env, SecondaryDatabase index)
  79. throws DatabaseException {
  80. Transaction txn = env.beginTransaction(null, null);
  81. SecondaryCursor cursor = index.openSecondaryCursor(txn, null);
  82. DatabaseEntry key2 = new DatabaseEntry(new byte[] {(byte) 42});
  83. DatabaseEntry data2 = new DatabaseEntry();
  84. int recordsFound = 0;
  85. long startTime = System.currentTimeMillis();
  86.  
  87. try {
  88. OperationStatus status =
  89. cursor.getSearchKey(key2, data2, LockMode.DEFAULT);
  90. if (status == OperationStatus.SUCCESS) {
  91. recordsFound++;
  92. while (cursor.getNextDup(key2, data2, LockMode.DEFAULT) ==
  93. OperationStatus.SUCCESS) {
  94. assert data2.getData()[9] == 42;
  95. recordsFound++;
  96. }
  97. }
  98. } catch (DatabaseException e) {
  99. txn.abort();
  100. throw e;
  101. }
  102. cursor.close();
  103. txn.commit();
  104.  
  105. long endTime = System.currentTimeMillis();
  106. System.out.println("Found " + recordsFound + " records whose tenth byte is 42 in " +
  107. (endTime - startTime) + " milliseconds");
  108. }
  109.  
  110. private static void fillKey(int i, byte[] key) {
  111. key[0] = (byte) i;
  112. key[1] = (byte) (i >> 8);
  113. key[2] = (byte) (i >> 16);
  114. key[3] = (byte) (i >> 24);
  115. }
  116.  
  117. private static void fillData(byte[] data) {
  118. Random random = new Random();
  119. random.nextBytes(data);
  120. }
  121. }

For this example we have to use a bigger heap size to avoid excessive garbage collections. Here are the numbers:

[weiqi@gao] $ java -Xmx800M IndexRandomBytesInserted 100000 1k records in 11724 milliseconds
Found 380 records whose tenth byte is 42 in 34 milliseconds
[weiqi@gao] $ java -Xmx800M IndexRandomBytesInserted 100000 1k records in 28330 milliseconds
Found 402 records whose tenth byte is 42 in 18 milliseconds

From a probability point of view, there should be around 100000/256 = 391 records whose tenth byte is 42. So our results are about right. It is worth pointing out that although the data writes are slowed down, the indexed search is a lot faster than a serial search through a primary database cursor.

The Cache, the OS IO Buffer, and the Physical Disk

One of the characteristics of embedded databases is the proximity of the data to the application—it's right there on a local disk. Consequently, a lot more can be done to tune the database with respect to its disk access behavior. This is markedly different from using an relational database server where the database is always a network call away and there is not a thing the application developer can do about it.

As a non-JE application writes data to the local disk, the data usually pass through three stages. First, the application gathers the data it wants to write out into an application buffer. Then the application buffer is written into a file system buffer. And finally, the operating system syncs the file system buffer onto the physical disk. And then there is the on-board disk hardware write cache, which needs to be disabled if we really want the data to reach the physical disk.

In order for a database to achieve the Durability part of the ACID transaction semantics, it is important that the data be synced to the physical disk. That step is expensive compared to writing to the file system.

JE allows the application developer to choose how far their data would go when a transaction is committed, trading a little bit durability of the data in the event of an operating system or an application failure for some usually dramatic throughput gains.

In JE terms, a transaction can be committed in one of three ways: commitSync, commitWriteNoSync, and commitNoSync. commitSync will take the data all the way to the disk and takes a long time. commitWriteNoSync takes the data to the operating system level but doesn't wait for all of it to be written to disk. The operating system will make sure it happens at a later time. commitNoSync writes the data to JE's cache, and the data will be written to the operating system when JE's write buffer is filled up or when a subsequent sync transaction happens.

How an application commits its transactions can be configured at different times in an JE application. It can be configured environment wide using EnvironmentConfig, at transaction creation time using TransactionConfig or at commit time by selecting from the different commit methods.

Wouldn't It Be Nice If...

Using the Bind API, the JE application developer can design the database schema with complex data structures and relationships. However writing custom bindings and complex queries still require quite a bit of work.

JE includes two higher level frameworks that ease this burden. The JE Java Collections API allows applications to access JE data through the standard Java Collections API interface. The newer Direct Persistence Layer allows applications to use a mechanism not unlike the Java Persistence API (JPA) to manipulate JE data.

We give a simple example that highlight some of the DPL features.

The DPL uses Java 5 annotations to define @Entity classes with @PrimaryKey and @SecondaryKey markings. An entity is an independent class that has a primary key and is accessed through a primary index. A secondary key can be one-to-one, many-to-one, one-to-many or many-to-many. A secondary key can also be a foreign key that relates one entity to another.

The DPL uses bytecode instrumentation to generate the low level code. The instrumentation can be performed either ahead of time using an Ant task, or at class loading time.

  1. import com.sleepycat.persist.model.Entity;
  2. import com.sleepycat.persist.model.PrimaryKey;
  3. import com.sleepycat.persist.model.Relationship;
  4. import com.sleepycat.persist.model.SecondaryKey;
  5.  
  6. @Entity
  7. public class Order {
  8. @PrimaryKey
  9. public int id;
  10. @SecondaryKey(relate = Relationship.MANY_TO_ONE)
  11. public int dept;
  12. public String name;
  13. public double price;
  14. public double quantity;
  15.  
  16. public String toString() {
  17. StringBuffer buffer = new StringBuffer("Order[");
  18. buffer.append("id=")
  19. .append(id)
  20. .append(",dept=")
  21. .append(dept)
  22. .append(",name=")
  23. .append(name)
  24. .append(",price=")
  25. .append(price)
  26. .append(",quantity=")
  27. .append(quantity)
  28. .append("]");
  29. return buffer.toString();
  30. }
  31. }

The DPL uses a high-level construct called an EntityStore instead of the low level Databases to manage persistence. The EntityStore is the factory for the generic PrimaryIndex and SecondaryIndex objects. An entity object can be persisted using PrimaryIndex objects and retrieved using PrimaryIndex, SecondaryIndex and EntityCursor objects. The primary and secondary index classes are like DAOs.

  1. import com.sleepycat.je.DatabaseException;
  2. import com.sleepycat.je.Environment;
  3. import com.sleepycat.je.EnvironmentConfig;
  4. import com.sleepycat.je.Transaction;
  5. import com.sleepycat.persist.EntityStore;
  6. import com.sleepycat.persist.PrimaryIndex;
  7. import com.sleepycat.persist.SecondaryIndex;
  8. import com.sleepycat.persist.StoreConfig;
  9.  
  10. import java.io.File;
  11.  
  12. public class PlaceOrder {
  13. public static void main(String[] args) throws DatabaseException {
  14. EnvironmentConfig envConfig = new EnvironmentConfig();
  15. envConfig.setAllowCreate(true);
  16. envConfig.setTransactional(true);
  17. Environment env =
  18. new Environment(new File("./envHome"), envConfig);
  19.  
  20. StoreConfig storeConfig = new StoreConfig();
  21. storeConfig.setAllowCreate(true);
  22. storeConfig.setTransactional(true);
  23. EntityStore store =
  24. new EntityStore(env, "OrderStore", storeConfig);
  25.  
  26. PrimaryIndex<Integer,Order> orderById =
  27. store.getPrimaryIndex(Integer.class, Order.class);
  28.  
  29. SecondaryIndex<Integer, Integer, Order> orderByDepartmentId =
  30. store.getSecondaryIndex(orderById, Integer.class, "dept");
  31.  
  32. Transaction txn = env.beginTransaction(null, null);
  33.  
  34. Order order = new Order();
  35. order.id = 100;
  36. order.dept = 3;
  37. order.name = "Random Order";
  38. order.price = 10.24;
  39. order.quantity = 3.0;
  40. orderById.put(order);
  41.  
  42. order = new Order();
  43. order.id = 101;
  44. order.dept = 3;
  45. order.name = "Random Order Again";
  46. order.price = 20.48;
  47. order.quantity = 6.0;
  48. orderById.put(order);
  49.  
  50. order = new Order();
  51. order.id = 102;
  52. order.dept = 4;
  53. order.name = "Another Random Order";
  54. order.price = 40.96;
  55. order.quantity = 12.0;
  56. orderById.put(order);
  57.  
  58. txn.commit();
  59.  
  60. store.close();
  61. env.close();
  62. }
  63. }

Executing this class' main method puts three orders into the JE environment.

  1. import com.sleepycat.je.DatabaseException;
  2. import com.sleepycat.je.Environment;
  3. import com.sleepycat.je.EnvironmentConfig;
  4. import com.sleepycat.persist.EntityCursor;
  5. import com.sleepycat.persist.EntityStore;
  6. import com.sleepycat.persist.PrimaryIndex;
  7. import com.sleepycat.persist.SecondaryIndex;
  8. import com.sleepycat.persist.StoreConfig;
  9.  
  10. import java.io.File;
  11.  
  12. public class ProcessOrder {
  13. public static void main(String[] args) throws DatabaseException {
  14. EnvironmentConfig envConfig = new EnvironmentConfig();
  15. envConfig.setAllowCreate(true);
  16. envConfig.setTransactional(true);
  17. Environment env =
  18. new Environment(new File("./envHome"), envConfig);
  19.  
  20. StoreConfig storeConfig = new StoreConfig();
  21. storeConfig.setAllowCreate(true);
  22. storeConfig.setTransactional(true);
  23. EntityStore store =
  24. new EntityStore(env, "OrderStore", storeConfig);
  25.  
  26. PrimaryIndex<Integer,Order> orderById =
  27. store.getPrimaryIndex(Integer.class, Order.class);
  28.  
  29. SecondaryIndex<Integer, Integer, Order> orderByDepartmentId =
  30. store.getSecondaryIndex(orderById, Integer.class, "dept");
  31.  
  32. EntityCursor<Order> orders = orderById.entities();
  33. inspectOrders(orders);
  34. orders.close();
  35.  
  36. orders = orderByDepartmentId.subIndex(3).entities();
  37. inspectOrders(orders);
  38. orders.close();
  39.  
  40. store.close();
  41. env.close();
  42. }
  43.  
  44. private static void inspectOrders(EntityCursor<Order> orders) {
  45. int orderCount = 0;
  46.  
  47. for (Order order : orders) {
  48. System.out.println(order);
  49. orderCount++;
  50. }
  51. System.out.println("Number of orders: " + orderCount);
  52. }
  53.  
  54. }

Executing this class' main method retrieves and displays the orders in the JE environment. The orders are retrieved twice. First, using the primary index to get all the orders, three orders were retrieved. Secondly, using the secondary index to get all orders with a department Id of 3, two orders were retrieved.

[weiqi@gao] $ java PlaceOrder[weiqi@gao] $ java ProcessOrderOrder[id=100,dept=3,name=Random Order,price=10.24,quantity=3.0]
Order[id=101,dept=3,name=Random Order Again,price=20.48,quantity=6.0]
Order[id=102,dept=4,name=Another Random Order,price=40.96,quantity=12.0]
Number of orders: 3
Order[id=100,dept=3,name=Random Order,price=10.24,quantity=3.0]
Order[id=101,dept=3,name=Random Order Again,price=20.48,quantity=6.0]
Number of orders: 2

Summary

Berkeley DB Java Edition brings the high performance, small footprint Berkeley DB Core Edition tradition into the Java world. By implementing the core engine in pure Java, the JE developers made it more attractive for Java developers.

JE and other Java-based embedded database engines makes writing a new class of applications feasible in the Java programming language.

The JE Direct Persistence Layer provides a JPA-like plain Java object persistence mechanism that is powerful and easy-to-use.

References

 

The Software Engineering Tech Trends is a monthly publication featuring emerging trends in software engineering.

Subscribe

© Copyright Object Computing, Inc. 1993, 2018. All rights reserved

secret