|By Jim Menard||
|September 7, 2004 12:00 AM EDT||
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.
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.
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.
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 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.
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.
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.
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.
The VoteServer runs five different reports, each using a different technique.
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)
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.
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.
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.
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
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.
- 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.
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.
|Jim Menard 10/06/04 04:31:59 PM EDT|
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|
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.
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
Apr. 25, 2017 06:15 AM EDT Reads: 747
SYS-CON Events announced today that CollabNet, a global leader in enterprise software development, release automation and DevOps solutions, will be a Bronze Sponsor of SYS-CON's 20th International Cloud Expo®, taking place from June 6-8, 2017, at the Javits Center in New York City, NY. CollabNet offers a broad range of solutions with the mission of helping modern organizations deliver quality software at speed. The company’s latest innovation, the DevOps Lifecycle Manager (DLM), supports Value S...
Apr. 25, 2017 05:00 AM EDT Reads: 135
The 20th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held June 6-8, 2017, at the Javits Center in New York City, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Containers, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal ...
Apr. 25, 2017 05:00 AM EDT Reads: 792
SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in compute, storage and networking technologies, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology, is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/...
Apr. 25, 2017 04:30 AM EDT Reads: 1,982
Amazon has gradually rolled out parts of its IoT offerings in the last year, but these are just the tip of the iceberg. In addition to optimizing their back-end AWS offerings, Amazon is laying the ground work to be a major force in IoT – especially in the connected home and office. Amazon is extending its reach by building on its dominant Cloud IoT platform, its Dash Button strategy, recently announced Replenishment Services, the Echo/Alexa voice recognition control platform, the 6-7 strategic...
Apr. 25, 2017 04:15 AM EDT Reads: 4,990
@GonzalezCarmen has been ranked the Number One Influencer and @ThingsExpo has been named the Number One Brand in the “M2M 2016: Top 100 Influencers and Brands” by Analytic. Onalytica analyzed tweets over the last 6 months mentioning the keywords M2M OR “Machine to Machine.” They then identified the top 100 most influential brands and individuals leading the discussion on Twitter.
Apr. 25, 2017 03:45 AM EDT Reads: 796
With billions of sensors deployed worldwide, the amount of machine-generated data will soon exceed what our networks can handle. But consumers and businesses will expect seamless experiences and real-time responsiveness. What does this mean for IoT devices and the infrastructure that supports them? More of the data will need to be handled at - or closer to - the devices themselves.
Apr. 25, 2017 03:45 AM EDT Reads: 178
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists will examine how DevOps helps to meet th...
Apr. 25, 2017 03:45 AM EDT Reads: 943
Judith Hurwitz is president and CEO of Hurwitz & Associates, a Needham, Mass., research and consulting firm focused on emerging technology, including big data, cognitive computing and governance. She is co-author of the book Cognitive Computing and Big Data Analytics, published in 2015. Her Cloud Expo session, "What Is the Business Imperative for Cognitive Computing?" is scheduled for Wednesday, June 8, at 8:40 a.m. In it, she puts cognitive computing into perspective with its value to the busin...
Apr. 25, 2017 03:30 AM EDT Reads: 3,560
Five years ago development was seen as a dead-end career, now it’s anything but – with an explosion in mobile and IoT initiatives increasing the demand for skilled engineers. But apart from having a ready supply of great coders, what constitutes true ‘DevOps Royalty’? It’ll be the ability to craft resilient architectures, supportability, security everywhere across the software lifecycle. In his keynote at @DevOpsSummit at 20th Cloud Expo, Jeffrey Scheaffer, GM and SVP, Continuous Delivery Busine...
Apr. 25, 2017 03:15 AM EDT Reads: 510
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Apr. 25, 2017 03:00 AM EDT Reads: 5,831
SYS-CON Events announced today that Juniper Networks (NYSE: JNPR), an industry leader in automated, scalable and secure networks, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Juniper Networks challenges the status quo with products, solutions and services that transform the economics of networking. The company co-innovates with customers and partners to deliver automated, scalable and secure network...
Apr. 25, 2017 02:15 AM EDT Reads: 931
Cognitive Computing is becoming the foundation for a new generation of solutions that have the potential to transform business. Unlike traditional approaches to building solutions, a cognitive computing approach allows the data to help determine the way applications are designed. This contrasts with conventional software development that begins with defining logic based on the current way a business operates. In her session at 18th Cloud Expo, Judith S. Hurwitz, President and CEO of Hurwitz & ...
Apr. 25, 2017 02:15 AM EDT Reads: 9,032
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
Apr. 25, 2017 01:15 AM EDT Reads: 1,311
Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the USA and Europe, we work with a variety of customers from emerging startups to Fortune 1000 companies.
Apr. 24, 2017 11:30 PM EDT Reads: 2,177
Financial Technology has become a topic of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 20th Cloud Expo at the Javits Center in New York, June 6-8, 2017, will find fresh new content in a new track called FinTech.
Apr. 24, 2017 11:15 PM EDT Reads: 2,283
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Apr. 24, 2017 11:00 PM EDT Reads: 896
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
Apr. 24, 2017 10:45 PM EDT Reads: 1,767
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
Apr. 24, 2017 09:45 PM EDT Reads: 3,629
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists will look at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deli...
Apr. 24, 2017 07:45 PM EDT Reads: 2,173