|
| 1 | +# jni_leveldb |
| 2 | + |
| 3 | +A sample command-line application demonstrating how to create an idiomatic Dart wrapper around a Java implementation of LevelDB, a fast key-value storage library. This project showcases the evolution of a LevelDB wrapper from raw JNI bindings to a safe, clean, and Dart-native API using `jnigen`. |
| 4 | + |
| 5 | +## Prerequisites |
| 6 | + |
| 7 | +- Java Development Kit (JDK) version 1.8 or later must be installed, and the `JAVA_HOME` environment variable must be set to its location. |
| 8 | + |
| 9 | +## Setup and Running |
| 10 | + |
| 11 | +1. **Generate Bindings and Build JNI code:** |
| 12 | + |
| 13 | + Run `jnigen` to download the required Java libraries, generate Dart bindings, and build the JNI glue code. |
| 14 | + |
| 15 | + ```bash |
| 16 | + dart run jni:setup |
| 17 | + dart run jnigen:setup |
| 18 | + dart run jnigen --config jnigen.yaml |
| 19 | + ``` |
| 20 | + |
| 21 | +2. **Run the application:** |
| 22 | + |
| 23 | + ```bash |
| 24 | + dart run bin/jni_leveldb.dart |
| 25 | + ``` |
| 26 | + |
| 27 | +## From Raw Bindings to an Idiomatic Dart API |
| 28 | + |
| 29 | +The initial output of `jnigen` provides a low-level, direct mapping of the Java API. Using this directly in application code can be verbose, unsafe, and unidiomatic. This project demonstrates how to build a better wrapper by addressing common pitfalls. |
| 30 | + |
| 31 | +### 1. Resource Management |
| 32 | + |
| 33 | +JNI objects are handles to resources in the JVM. Failing to release them causes memory leaks. |
| 34 | + |
| 35 | +**The Problem:** Forgetting to call `release()` on JNI objects. |
| 36 | +
|
| 37 | +**The Solution:** The best practice is to use the `using(Arena arena)` block, which automatically manages releasing all objects allocated within it, making your code safer and cleaner. For objects that live longer, you must manually call `release()`. |
| 38 | +
|
| 39 | +*Example from the wrapper:* |
| 40 | +```dart |
| 41 | +void putBytes(Uint8List key, Uint8List value) { |
| 42 | + using((arena) { |
| 43 | + final jKey = JByteArray.from(key)..releasedBy(arena); |
| 44 | + final jValue = JByteArray.from(value)..releasedBy(arena); |
| 45 | + _db.put(jKey, jValue); |
| 46 | + }); |
| 47 | +} |
| 48 | +``` |
| 49 | +
|
| 50 | +### 2. Idiomatic API Design and Type Handling |
| 51 | +
|
| 52 | +Raw bindings expose Java's conventions and require manual, repetitive type conversions. A wrapper class should expose a clean, Dart-like API. |
| 53 | +
|
| 54 | +**The Problem:** Java method names (`createIfMissing$1`) and types (`JString`, `JByteArray`) are exposed directly to the application code. |
| 55 | +
|
| 56 | +**The Solution:** Create a wrapper class that exposes methods with named parameters and standard Dart types (`String`, `Uint8List`), handling all the JNI conversions internally. |
| 57 | +
|
| 58 | +*The Improved API:* |
| 59 | +```dart |
| 60 | +static LevelDB open(String path, {bool createIfMissing = true}) { ... } |
| 61 | +void put(String key, String value) { ... } |
| 62 | +String? get(String key) { ... } |
| 63 | +``` |
| 64 | +
|
| 65 | +This allows for clean, simple iteration in the application code: |
| 66 | +```dart |
| 67 | +for (var entry in db.entries) { |
| 68 | + print('${entry.key}, ${entry.value}'); |
| 69 | +} |
| 70 | +``` |
| 71 | +
|
| 72 | +### 3. JVM Initialization |
| 73 | +
|
| 74 | +The JVM is a process-level resource and should be initialized only once when the application starts. |
| 75 | +
|
| 76 | +**The Problem:** Calling `Jni.spawn()` inside library code. |
| 77 | +
|
| 78 | +**The Solution:** `Jni.spawn()` belongs in a locatio where it will be called once, like your application's `main()` function, not in the library. In this example, the library code should assume the JVM is already running. |
| 79 | +
|
| 80 | +*Correct Usage in `bin/jni_leveldb.dart`:* |
| 81 | +```dart |
| 82 | +void main(List<String> arguments) { |
| 83 | + // ... find JARs ... |
| 84 | + Jni.spawn(classPath: jars); // Spawn the JVM once. |
| 85 | + db(); // Run the application logic. |
| 86 | +} |
| 87 | +``` |
| 88 | +
|
| 89 | +### The Final Result |
| 90 | +
|
| 91 | +By applying these principles, the application logic becomes simple, readable, and free of JNI-specific details. |
| 92 | +
|
| 93 | +*Final Application Code:* |
| 94 | +```dart |
| 95 | +import 'package:jni_leveldb/src/leveldb.dart'; |
| 96 | +
|
| 97 | +void db() { |
| 98 | + final db = LevelDB.open('example.db'); |
| 99 | + try { |
| 100 | + db.put('Akron', 'Ohio'); |
| 101 | + db.put('Tampa', 'Florida'); |
| 102 | + db.put('Cleveland', 'Ohio'); |
| 103 | +
|
| 104 | + print('Tampa is in ${db.get('Tampa')}'); |
| 105 | +
|
| 106 | + db.delete('Akron'); |
| 107 | +
|
| 108 | + print('\nEntries in database:'); |
| 109 | + for (var entry in db.entries) { |
| 110 | + print('${entry.key}, ${entry.value}'); |
| 111 | + } |
| 112 | + } finally { |
| 113 | + db.close(); |
| 114 | + } |
| 115 | +} |
| 116 | +``` |
0 commit comments