Skip to main content
The OrtEnvironment class is the main entry point for ONNX Runtime in Java. It manages the runtime environment and session creation.

Package

Class Declaration

Singleton Pattern

OrtEnvironment follows a singleton pattern - only one instance can exist per JVM.

Getting the Environment

getEnvironment()

Gets the default environment instance.
Example:

getEnvironment(String)

Gets environment with custom name.
Example:

getEnvironment(OrtLoggingLevel)

Gets environment with custom log level.
Example:

getEnvironment(OrtLoggingLevel, String)

Gets environment with custom log level and name.
Example:

Logging Levels

Example:

Creating Sessions

createSession(String, SessionOptions)

Creates a session from a model file.
Example:

createSession(byte[], SessionOptions)

Creates a session from a byte array.
Example:

createSession(ByteBuffer, SessionOptions)

Creates a session from a ByteBuffer.
Example:

Thread Pool Configuration

getEnvironment with ThreadingOptions

Creates environment with custom global thread pool.
Example:

ThreadingOptions

Configure global thread pool settings.

Resource Management

close()

Closes the environment and releases resources.
Note: The environment is automatically closed via JVM shutdown hook. Calling close() is optional but harmless. Example:

Singleton Behavior

Once created, the environment cannot be reconfigured:

Complete Examples

Basic Setup

Production Configuration

Multi-Session Application

Environment Singleton Manager

Custom Logging

Thread Safety

The OrtEnvironment class is thread-safe:
  • Environment creation is synchronized
  • Multiple threads can safely call getEnvironment()
  • Sessions created from environment are thread-safe for inference

Best Practices

  1. Create early: Initialize environment at application startup
  2. Single instance: Leverage singleton pattern, don’t try to recreate
  3. Configure once: Set logging and threading on first creation
  4. Reuse sessions: Create sessions once, use many times
  5. Proper cleanup: Close sessions before environment (or use try-with-resources)
  6. Thread configuration: Set global thread pool if needed

Common Patterns

Application Lifecycle

Dependency Injection

Error Handling

See Also