Make sure to use the correct Java classloader for loading the RocksDB

Native Library
main
Adam Retter 10 years ago
parent c3915abbae
commit 585c759cf3
  1. 30
      java/org/rocksdb/NativeLibraryLoader.java
  2. 2
      java/org/rocksdb/RocksDB.java

@ -11,11 +11,35 @@ import org.rocksdb.util.Environment;
* The shared library is extracted to a temp folder and loaded from there. * The shared library is extracted to a temp folder and loaded from there.
*/ */
public class NativeLibraryLoader { public class NativeLibraryLoader {
//singleton
private static final NativeLibraryLoader instance = new NativeLibraryLoader();
private static final String sharedLibraryName = Environment.getJniLibraryName("rocksdb"); private static final String sharedLibraryName = Environment.getJniLibraryName("rocksdb");
private static final String tempFilePrefix = "librocksdbjni"; private static final String tempFilePrefix = "librocksdbjni";
private static final String tempFileSuffix = "." + Environment.getJniLibraryExtension(); private static final String tempFileSuffix = "." + Environment.getJniLibraryExtension();
public static void loadLibraryFromJar(final String tmpDir) /**
* Get a reference to the NativeLibraryLoader
*
* @return The NativeLibraryLoader
*/
public static NativeLibraryLoader getInstance() {
return instance;
}
/**
* Attempts to extract the native RocksDB library
* from the classpath and load it
*
* @param tmpDir A temporary directory to use
* to copy the native library to. If null,
* or the empty string, we rely on Java's
* {@see java.io.File#createTempFile(String, String) }
* function to provide a temporary location.
* The temporary file will be registered for deletion
* on exit.
*/
public void loadLibraryFromJar(final String tmpDir)
throws IOException { throws IOException {
final File temp; final File temp;
if(tmpDir == null || tmpDir.equals("")) { if(tmpDir == null || tmpDir.equals("")) {
@ -30,8 +54,8 @@ public class NativeLibraryLoader {
temp.deleteOnExit(); temp.deleteOnExit();
} }
// attempt to copy the library from the JAR to the temp destination // attempt to copy the library from the Jar file to the temp destination
try(final InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(sharedLibraryName)) { try(final InputStream is = getClass().getClassLoader().getResourceAsStream(sharedLibraryName)) {
if (is == null) { if (is == null) {
throw new RuntimeException(sharedLibraryName + " was not found inside JAR."); throw new RuntimeException(sharedLibraryName + " was not found inside JAR.");
} else { } else {

@ -44,7 +44,7 @@ public class RocksDB extends RocksObject {
} }
try try
{ {
NativeLibraryLoader.loadLibraryFromJar(tmpDir); NativeLibraryLoader.getInstance().loadLibraryFromJar(tmpDir);
} }
catch (IOException e) catch (IOException e)
{ {

Loading…
Cancel
Save