From 13cc6192e5d877d7c782eaaa7f9fd1544a1902f2 Mon Sep 17 00:00:00 2001 From: Adam Pocock Date: Mon, 3 Jul 2023 18:59:03 -0400 Subject: [PATCH] [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. --- .../src/main/java/ai/onnxruntime/OrtSession.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/java/src/main/java/ai/onnxruntime/OrtSession.java b/java/src/main/java/ai/onnxruntime/OrtSession.java index 536fd99598..3191e0b2e2 100644 --- a/java/src/main/java/ai/onnxruntime/OrtSession.java +++ b/java/src/main/java/ai/onnxruntime/OrtSession.java @@ -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 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;