[java] Adding native library loader to SessionOptions and RunOptions static init (#16435)

### Description
Unlike most ORT classes `SessionOptions` and `RunOptions` don't trigger
native library loading of the JNI binding and ORT when the classes are
initialized (after class loading). This was initially because I thought
that loading an inner class would trigger the static initialization of
the outer class, but this is not true. So if you create a
`SessionOptions` instance before referencing `OrtEnvironment` then you
won't trigger library loading and you'll get an error saying it couldn't
link the native method that creates a `SessionOptions` object.

Note this doesn't prevent users from creating a `SessionOptions` and
modifying it before the `OrtEnvironment` is created, which can still
cause issues. It would be a breaking API change to modify the
`SessionOptions` constructor to take an environment, and it wouldn't
mirror the way it works in the C API which requires this by convention
rather than API design, but we can discuss making that modification
later.

### Motivation and Context
Reduces the occurrence of mysterious Java library loading errors. Helps
with #16434.
This commit is contained in:
Adam Pocock 2023-07-03 18:59:03 -04:00 committed by GitHub
parent 2e2e6aeff6
commit 13cc6192e5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -517,6 +517,14 @@ public class OrtSession implements AutoCloseable {
}
}
static {
try {
OnnxRuntime.init();
} catch (IOException e) {
throw new RuntimeException("Failed to load onnx-runtime library", e);
}
}
private final long nativeHandle;
private final List<Long> customLibraryHandles;
@ -1164,6 +1172,14 @@ public class OrtSession implements AutoCloseable {
/** Used to control logging and termination of a call to {@link OrtSession#run}. */
public static class RunOptions implements AutoCloseable {
static {
try {
OnnxRuntime.init();
} catch (IOException e) {
throw new RuntimeException("Failed to load onnx-runtime library", e);
}
}
private final long nativeHandle;
private boolean closed = false;