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.getEnvironment(String)
Gets environment with custom name.getEnvironment(OrtLoggingLevel)
Gets environment with custom log level.getEnvironment(OrtLoggingLevel, String)
Gets environment with custom log level and name.Logging Levels
Creating Sessions
createSession(String, SessionOptions)
Creates a session from a model file.createSession(byte[], SessionOptions)
Creates a session from a byte array.createSession(ByteBuffer, SessionOptions)
Creates a session from a ByteBuffer.Thread Pool Configuration
getEnvironment with ThreadingOptions
Creates environment with custom global thread pool.ThreadingOptions
Configure global thread pool settings.Resource Management
close()
Closes the environment and releases resources.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
TheOrtEnvironment 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
- Create early: Initialize environment at application startup
- Single instance: Leverage singleton pattern, don’t try to recreate
- Configure once: Set logging and threading on first creation
- Reuse sessions: Create sessions once, use many times
- Proper cleanup: Close sessions before environment (or use try-with-resources)
- Thread configuration: Set global thread pool if needed