What it is
MapDB is an embedded Java database and caching library that provides fast, concurrent, and off-heap key-value storage. It supports maps, sets, queues, and other collections with optional persistence to disk or memory-mapped files.
MapDB provides concurrent collections (maps, sets, queues) with optional persistence. It supports transactions, snapshots, off-heap memory, and disk-backed storage. Developers can use it as an embedded database for small to medium-sized applications or as a high-performance cache for large datasets.
Installation
<dependency>
<groupId>org.mapdb</groupId>
<artifactId>mapdb</artifactId>
<version>3.0.9</version>
</dependency>Getting started
The smallest useful thing you can do with it, and what each part means.
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.concurrent.ConcurrentMap;
DB db = DBMaker.fileDB("data.db").make();
ConcurrentMap<String, String> map = db.hashMap("myMap").createOrOpen();
map.put("key1", "value1");
System.out.println(map.get("key1"));
db.close();ConcurrentMap<String, Integer> map = DBMaker.memoryDB().make().hashMap("numbers").createOrOpen();
map.put("one", 1);
System.out.println(map.get("one"));Advanced usage
Where the library earns its place over a simpler alternative.
DB db = DBMaker.fileDB("data.db").transactionEnable().make();
ConcurrentMap<String, String> map = db.hashMap("myMap").createOrOpen();
map.put("key2", "value2");
db.commit(); // persist changes
db.close();DB db = DBMaker.memoryDirectDB().make();
ConcurrentMap<String, String> map = db.hashMap("offHeapMap").createOrOpen();import org.mapdb.HTreeMap;
HTreeMap<String, String> map = db.hashMap("queueMap").createOrOpen();Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- IllegalArgumentException
- Thrown when invalid configuration is provided, such as duplicate map names. Ensure unique names for maps and collections.
- DBException
- Occurs when disk operations fail. Check file permissions, disk space, and paths.
- NullPointerException
- Ensure keys and values are not null unless explicitly allowed by collection type.
Best practices
- Always close the DB instance to release file handles.
- Use transactions for critical updates to prevent data corruption.
- Use off-heap memory for large in-memory datasets to reduce GC overhead.
- Regularly back up disk-based databases for safety.
- Leverage snapshots for consistent read views in concurrent environments.
Background
Why it exists, and what it was reacting to.
MapDB was created to offer a lightweight, fast, and thread-safe Java storage solution for applications needing persistent collections or in-memory caching. It combines features of a database and a cache, allowing developers to manage large datasets efficiently without relying on external database servers.
