Welcome!

Java IoT Authors: Yeshim Deniz, Elizabeth White, Pat Romanski, Liz McMillan, Chris Schwarz

Related Topics: Java IoT

Java IoT: Article

Building Applications with Berkeley DB Java Edition

High-performance database goes pure Java

Berkeley DB is a database with a long history. First released in 1991 as a replacement for various dbm implementations, it was soon included in BSD Unix releases. Requests for new features and commercial support led to the formation of Sleepycat Software in 1996. Using a dual license model, Berkeley DB became very popular for both open source and commercial applications. Recently, Sleepycat announced Berkeley DB Java Edition (JE), a 100% Java implementation that runs on any J2SE 1.4.2 or later JVM.

This article introduces JE's features and classes and uses a sample electronic voting application to illustrate its use.

Berkeley DB and JE
The original Berkeley DB is used in a wide variety of open source and commercial applications in telecom, Internet infrastructure, storage, security, financial services, and other industries. Sleepycat estimates that there are over 200 million copies deployed, but most people are not even aware they touched Berkeley DB. (See "Where's the Sleeping Cat?" available at the URL listed in References.)

Berkeley DB is a nonrelational database that stores key/value pairs. Databases can be configured to store multiple values under a single key. Secondary databases can be created that use different keys to access the same values. Searches and joins can be performed using a specific key or a range of keys.

The original Berkeley DB (not JE) is written in C, though there are bindings for other languages, including Java. JE brings to Java developers the features of Berkeley DB and adds better integration with the Java world through Java data type support while avoiding the performance penalty of JNI.

Like its C ancestor, JE is small. The database's footprint is less than 435K. It supports full ACID transactions (meaning its characteristics include Atomicity, Consistency, Isolation, and Durability), performs record-level locking for high concurrency, and can handle huge amounts of data: hundreds of terabytes in a single table, with record sizes up to two gigabytes. Frequently used data is cached in memory. JE has better concurrency than the C Berkeley DB for some applications because, unlike DB, it has record-level locking that allows applications to continue accessing other parts of the database when a record is locked.

JE databases are stored as files on the file system. Backing up a database is accomplished by copying the files. To restore a database, move the copied files into the database directory and restart the application. When an application uses a database with transactions (that group database operations together in order to treat them atomically), checkpoints are periodically saved to the file system by a separate JE thread in order to make recovery faster. Applications without transactions may need to perform manual syncs that tell the database to flush data in memory to the file system, depending upon their requirements.

Technology Overview
Databases
JE databases are B+Trees whose records are key/value pairs. The keys and values are byte arrays. Databases are stored as files within a single directory. An in-memory cache stores as much as it can of the B+Tree structure and frequently accessed data.

The class DatabaseStats provides information about a database, such as the number of records in the database or the depth of the B+Tree.

Environments
A database environment coordinates one or more databases. It manages transactions, allowing them to work across databases. The environment provides the in-memory cache used by an application. It also facilitates administrative operations such as renaming or deleting databases.

Records and Binding
Each record in a database is an instance of DatabaseEntry, essentially a wrapper around a byte array. Since storing Java objects is a common operation, JE provides ways to translate between them and byte arrays. This process is called binding. JE provides classes for binding simple numeric and string objects.

There are two approaches to creating DatabaseEntry values from more complex Java objects: serialization or creating a custom class that translates the objects to and from byte arrays. When serializing objects to be stored in separate database records, each serialized instance carries with it duplicate information: the descriptions of the classes involved in the serialization. JE provides binding APIs that perform the serialization and store the duplicate information only once, in a separate database (see Figure 1).

A custom binding that maps objects to byte arrays must subclass TupleBinding, which implements the EntryBinding interface. This interface consists of two methods: objectToEntry and entryToObject.

Cursors and Iterators
To look up a single key, call myDatabase.get(), passing in the key as a DatabaseEntry and another DatabaseEntry to hold the returned data.

To iterate through the database or a subset of the database, both a cursor and iterators are available. They operate the same way, searching for a (possibly partial) key and iterating over the returned values. The difference is that iteration uses flavors of the Java collection classes called StoredMap, StoredSet, and StoredIterator. Unlike java.util.Iterators, StoredIterators must be closed explicitly. There are two ways to close a StoredIterator: call its close method or call the static method StoredIterator.close. The latter approach avoids casting when the iterator is stored in a variable of type Iterator.

The JE collection classes implement all of the collection methods except for size (for example, get, put, and containsValue) and a few extras. See the Javadocs for details.

Secondary Databases
To perform searches using keys that are different than those used to store the data, a secondary database must be created. The values in the secondary database are the same as those in the primary database. Multiple secondary databases may be created.

When a primary database is modified, JE updates all of its secondary databases. All writing takes place through the primary database. The one exception to this rule is that records may be deleted from a secondary database. The records in the primary database are also deleted, as are all corresponding records in all other secondary databases.

Creating a secondary database requires three things: a primary database, a binding for the keys, and a binding for the values. The value binding will be the same one used by the primary database. The key creator it must implement is the SecondaryKeyCreator interface, which has the single method createSecondaryKey.

Transactions
Transactions are enabled by an application when an environment and its databases are created or opened. Once enabled, they must be used for all database modifications. Methods such as Database.get and Database.put take a transaction object as an argument. If the transaction argument is null and transactions are enabled, the method may either use autocommit (committing the data when the operation is finished) as does "put" or it may not use a transaction at all, as with "get", which does not modify the database.

The TransactionRunner class and TransactionWorker interface can make using transactions easier by handling retries and exceptions. A TransactionRunner creates a transaction and calls TransactionWorker.doWork. The runner can retry the work any number of times.

A Sample Application
A pair of electronic voting applications - one that simulates election day and another that runs reports against the collected data - will help illustrate the use of JE. While developing this application, I made heavy use of Sleepycat's JE Javadocs and "Getting Started with Berkeley DB Java Edition," included in the documentation that comes with JE.

The two applications share much of their code. To create the data, the election day simulator creates voting booths, then generates votes and sends them to the vote server. The vote server stores information about the booths and their votes into multiple primary and secondary databases. The reporting application performs queries about the booths and the votes.

The three main classes for these applications are Booth, Vote, and VoteServer. A booth is identified by an IP address and knows what state, city, and district it is in. The booth assigns each vote a sequence number. A vote's unique identifier is a combination of the booth's IP address and the vote's sequence number. A vote holds a few more fields like the race (President, State Assembly, Dog Catcher), political party (Democrat, Republican, Silly), and candidate.

After thinking about the queries I wanted to be able to run, I decided that in addition to the primary databases for Booth and Vote, I would need three secondary databases: for booths using state as the key, for votes using race as the key, and for votes using race plus political party.

Bindings
Before creating databases, bindings for Booth and Vote need to be created. For the primary databases, I chose to use custom binding classes. Listing 1 contains the two methods implemented by BoothBinding. The JE classes TupleInput and TupleOutput know how to read and write strings and intrinsics (ints, longs, etc.).

Bindings for the keys in the primary databases are unnecessary because the keys are so simple: the booth database's key is the IP address byte array that needs no translation, and the vote database's key is a string from which we can retrieve a byte array.

Each secondary database needs a SecondaryKeyCreator. One of the vote secondary databases is indexed by race and party. Listing 2 shows the method that, given a vote and its primary key, fills in the secondary key DatabaseEntry.

Databases
When opening a database for writing, it is created if it does not exist. A flag is set that determines if the database is transactional. Listing 3 shows this process.

Storing Votes
The code in Listing 4 creates a transaction, calls the method that stores the booth and its votes, and commits the transaction. (Listings 4-9 can be downloaded from www.sys-con.com/java/sourcec.cfm.) This code commits without synchronizing the change to the log file, which is risky (the data is held in memory until the next sync) but faster.

Booth and vote data are written to the primary database. The secondary databases are updated automatically. The code in Listing 5 stores a vote into the vote primary database.

Reports
The VoteServer runs five different reports, each using a different technique.

Total Votes
The following code retrieves the total number of votes in the primary vote database.


// try/catch not shown
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Database db = dbEnvironment.getVoteDb();
Cursor cursor =
  db.openCursor(null, null);

DatabaseEntry foundKey =
  new DatabaseEntry();
DatabaseEntry foundData =
  new DatabaseEntry();
int numRecords = 0;
while (cursor.getNext(foundKey,
                      foundData,
                      LockMode.DEFAULT)
    == OperationStatus.SUCCESS)
  ++numRecords;
cursor.close();
[DELETE:
int nRecs = dbEnvironment.getVoteDb()
  .getStats(null).getLnCount();
END DELETE]
// (print number of records here)

Single Vote
Database.get is used to find a single vote by its primary key (see Listing 6).

Booths by State
This report selects a state from the database, then prints all of the booths in that state. It runs the same query two different ways: with a cursor (see Listing 7) and with a JE Iterator (see Listing 8). The Iterator code is shorter. In both listings, error handling code and try/catch blocks are not shown.

Total Presidential Race Vote Count
To count how many votes were cast in the presidential race, a StoredMap is opened on the proper secondary database. The duplicate records (votes) for the presidential race are retrieved and the number of votes is reported (see Listing 9).

Presidential Race Results
The last report prints the total votes per party for the presidential race and declares a winner. As in the previous report, a map is created on a secondary database and the map's size method returns the vote count.

Conclusion
The electronic voting application source code contains plenty of comments and deals with all the details ignored in this article such as error handling. The code and properties files that configure the databases and transactions have not been tuned for performance.

To get started with the Berkeley DB Java Edition, download it from Sleepycat Software. Read "Getting Started with Berkeley DB Java Edition," browse the example code that comes with JE, and refer to the JE Javadocs.

JE is available under a dual license. The open source license is online at www.sleepycat.com/download/oslicense.html. Pricing starts at $40,000 for a buyout license, which enables the customer to redistribute JE within a specific product/service in any volume into perpetuity.

Resources
Sleepycat Software's site is www.sleepycat.com. There you can download the Berkeley DB Java Edition. The documentation and example code that comes with JE are great starting points. The site also contains a number of technical articles and white papers at www.sleepycat.com/company/technical.shtml.

The paper "Where's the Sleeping Cat?" is available at www.sleepycat.com/pdfs/index.php?paper=jdj_wheresthecat.

The latest version of the electronic voting application code can be found at www.io.com/~jimm/writing/evote.tar.gz.

SIDEBAR

Configuration
While creating or opening databases, JE allows you to specify many optional database configuration parameters, including but not limited to:

  • Maximum database file size
  • Whether transactions are allowed
  • Transaction timeout length
  • Cache size
  • Whether duplications are allowed
  • How frequently to perform checkpoints
  • How to sort duplicate records
All of this is done through the Java API. You don't need a database administrator to create or maintain your databases.

SIDEBAR 2

Why Berkeley DB Java Edition?
Where should you use Berkeley DB Java Edition? Consider using JE if:

  • Speed and size are issues. JE is fast and can handle huge amounts of data.
  • It makes sense to embed the database into your application. Some applications are delivered to platforms that don't have a database installed or can't connect to a database server.
  • You know what questions you will be asking of the data. Writing queries involves writing Java code and designing the database structure to allow access to the data based on keys other than the primary key.
JE may not be the solution if:
  • The application needs to perform ad-hoc queries. For this you need to write Java code to perform searches; there is no other query language. Searches that use keys other than the primary key used to store the data require a secondary database, discussed later in this article.
  • Data must be shared with non-Java applications. The original Berkeley DB data format is different than the JE format. Berkeley DB supports bindings to many languages, including Java.
SIDEBAR 3

Database Log Files
Databases are stored as a series of log files. When data is written to a disk, it's always appended to an existing log file. This enables very fast writes since the disk head does not need to move. Log files are never overwritten or modified; those operations are slower than appends. When the log file in use by a database reaches a maximum size, a new log file is created. A background "cleaner" thread organizes the log files, moving active records from older log files to newer ones and deleting old log files that contain no active data.

More Stories By Jim Menard

Jim Menard is a senior technologist with over 20 years of experience in software development, design, and management. He has developed many open source projects including the Java GUI report writer DataVision (http://datavision.sourceforge.net). Jim likes shiny things (http://www.io.com/~jimm).

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Jim Menard 10/06/04 04:31:59 PM EDT

Lars,

I haven't tried creating a hierarchical structure using Berkeley DB. I imagine you could by containing the key of one database within the value of another.

I highly recommend the Sleepycat email lists. The "bdbje" email list is read by users and Sleepycat people (Sleepycats?) alike. See http://www.sleepycat.com/supports/index.shtml for the list of mailing lists. To join the bdbje list, send an email to [email protected].

Lars Borup Jensen 10/06/04 04:16:17 AM EDT

Hi Jim,

Ive been looking for articles regarding berkeley db, IMHO a underused product. I've been wondering for a looong time now, how it would be possible to create a hierarchical structure using bdb. Ive looked at openldap (their bdb and hdb backends) but still "designing" as this task does NOT seem trivial. Have you had any experience regarding this??

Jim Menard 09/08/04 02:02:26 PM EDT

Please ignore the text between "[DELETE" and "END DELETE]" in the sample code here online. It's the artifact of a last-minute change. I haven't yet seen the article in its print form, so I'm not sure if the printed code has the same issue.

I look forward to your comments on this article. Thanks for reading it.

@ThingsExpo Stories
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, has been named "Bronze Sponsor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
"We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that EnterpriseTech has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and ...
SYS-CON Events announced today that CHEETAH Training & Innovation will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CHEETAH Training & Innovation is a cloud consulting and IT training firm specializing in improving clients cloud strategies and infrastructures for medium to large companies.
SYS-CON Events announced today that Datanami has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datanami is a communication channel dedicated to providing insight, analysis and up-to-the-minute information about emerging trends and solutions in Big Data. The publication sheds light on all cutting-edge technologies including networking, storage and applications, and thei...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...