Skip to content

Instantly share code, notes, and snippets.

@stantonk
Last active August 14, 2016 17:29
Show Gist options
  • Save stantonk/19c3e4c3b8809be2fc55 to your computer and use it in GitHub Desktop.
Save stantonk/19c3e4c3b8809be2fc55 to your computer and use it in GitHub Desktop.
Simple threadsafe LevelDB-backed key-value store for Java
/**
<dependency>
<groupId>org.fusesource.leveldbjni</groupId>
<artifactId>leveldbjni-all</artifactId>
<version>1.7</version>
</dependency>
*/
import com.google.common.base.Optional;
import org.iq80.leveldb.DB;
import org.iq80.leveldb.Options;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import static org.fusesource.leveldbjni.JniDBFactory.*;
public class KeyValueStore {
private static final Logger logger = LoggerFactory.getLogger(KeyValueStore.class);
private static DB db;
public KeyValueStore(final String dbName) throws IOException {
db = getDB(dbName);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("safely closing database...");
safeClose(db);
}
});
}
public synchronized void put(String key, String val) throws IOException {
db.put(bytes(key), bytes(val));
}
public synchronized Optional<String> get(String key) throws IOException {
String val = asString(db.get(bytes(key)));
return Optional.fromNullable(val);
}
private static DB getDB(final String dbName) {
final Options options = new Options();
options.createIfMissing(true);
try {
return factory.open(new File(dbName), options);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void safeClose(DB db) {
if (db != null) try {
db.close();
} catch (IOException e) {
logger.error("Exception caught:", e);
}
}
public static void main(String[] args) throws IOException {
final KeyValueStore exampledb = new KeyValueStore("exampledb");
for (int i=0; i<10000; i++) {
Optional<String> stringOptional = exampledb.get(String.valueOf(i));
System.out.println(stringOptional);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment