Skip to main content

Java Inference API

The ONNX Runtime Java API enables high-performance inference in Java applications and Android development. This guide covers the complete Java API with real examples from the codebase.

Installation

Maven

Gradle

Quick Start

Here’s a minimal Java example:

OrtEnvironment

The environment manages global ONNX Runtime state. Create one per application.
Logging levels:

OrtSession

The session loads and runs ONNX models.

Creating a Session

From file path:
From byte array:
From ByteBuffer:

Session Metadata

Get model metadata:

Running Inference

Basic inference:
Multiple inputs:
Request specific outputs:
With RunOptions:

SessionOptions

Configure session behavior:

OnnxTensor

Create tensors for model inputs: From Java arrays:
From ByteBuffer:
From String array:
Get tensor information:

Execution Providers

Adding Execution Providers

CUDA:
TensorRT:
CoreML (macOS/iOS):
NNAPI (Android):
Check available providers:

Complete Example: MNIST Classification

From the ONNX Runtime codebase:

Android Example

Error Handling

Supported Data Types

Best Practices

Always use try-with-resources for OrtSession, OnnxTensor, and Result to ensure proper cleanup.
Create one OrtEnvironment per application and reuse it for all sessions.
Session creation is expensive. Create once and reuse for multiple inferences.
Use NNAPI on Android, CUDA on desktop with NVIDIA GPUs for best performance.
Set optimization level to ALL_OPT for production deployments.

Next Steps

Model Optimization

Optimize models for production deployment

Execution Providers

Configure hardware acceleration