Machine Learning in Java: Deep Java Library and ONNX Runtime

When it makes sense to run models inside the JVM, how to export them to ONNX, how to call ONNX Runtime from Java, and where Deep Java Library fits.

Data scientists usually train models in Python. Many production systems in Indian enterprises, however, run on Java: payment platforms, lending systems, logistics back ends and large Spring Boot applications. The usual bridge is a separate Python service called over HTTP. That works, but it adds a network hop, another runtime to maintain and another point of failure.

For many models there is a simpler option: run inference directly inside the JVM. Two well-established tools make this practical, ONNX Runtime with its Java API and Deep Java Library (DJL). This article explains when in-JVM inference is the right choice and how to get started.

When to run models inside the JVM

In-JVM inference is a good fit when:

  • Latency matters: scoring each transaction, search query or event as part of a request, where an extra network call is noticeable.
  • Volume is high: millions of small predictions a day, where serialisation and HTTP overhead add up.
  • The model is modest in size: gradient-boosted trees, logistic regression, small neural networks, text classifiers or embedding models.
  • Operations prefer one runtime: a team that already deploys, monitors and secures Java services can reuse all of that.

It is a weaker fit for very large language models that need dedicated GPUs, for models that change several times a day, or where the data science team needs to iterate independently of Java release cycles. In those cases a separate model service remains the better design.

Exporting models to ONNX

ONNX (Open Neural Network Exchange) is an open format for representing machine learning models as a computation graph. Training happens in your usual framework; the trained model is exported to a .onnx file that any ONNX-compatible runtime can execute.

  • PyTorch: use torch.onnx.export with a sample input to trace the model.
  • scikit-learn: use the skl2onnx package, which converts many estimators and pipelines.
  • TensorFlow/Keras: use the tf2onnx converter.
  • XGBoost and LightGBM: supported through onnxmltools.

After export, always verify: run the same test inputs through the original model in Python and through the ONNX model, and compare outputs within a small tolerance. Note the input names, shapes and data types; you will need them in Java. Tools such as Netron let you inspect the graph visually.

ONNX Runtime in Java

ONNX Runtime is Microsoft's open-source inference engine for ONNX models. Its Java API is published on Maven Central as com.microsoft.onnxruntime:onnxruntime (CPU) and onnxruntime_gpu (CUDA). The core classes are OrtEnvironment, OrtSession and OnnxTensor.

import ai.onnxruntime.*;
import java.util.Map;

public class RiskScorer implements AutoCloseable {
    private final OrtEnvironment env = OrtEnvironment.getEnvironment();
    private final OrtSession session;

    public RiskScorer(String modelPath) throws OrtException {
        session = env.createSession(modelPath, new OrtSession.SessionOptions());
    }

    public float score(float[] features) throws OrtException {
        String inputName = session.getInputNames().iterator().next();
        try (OnnxTensor input = OnnxTensor.createTensor(env, new float[][] { features });
             OrtSession.Result result = session.run(Map.of(inputName, input))) {
            float[][] output = (float[][]) result.get(0).getValue();
            return output[0][0];
        }
    }

    @Override
    public void close() throws OrtException {
        session.close();
    }
}

A few points about this example. The session is created once and reused: creating it loads and optimises the graph, which is expensive. OrtSession supports concurrent run calls, so one instance can serve many request threads; in Spring, expose it as a singleton bean. Both the input tensor and the result hold native memory and are closed with try-with-resources. The output cast assumes the model returns a single float matrix of shape [1, 1]; models converted from scikit-learn classifiers often return a label tensor and a probability output instead, so check your model's outputs before casting.

Deep Java Library (DJL)

DJL is an open-source, engine-agnostic deep learning library for Java, started by Amazon. Instead of binding you to one runtime, it provides a common API on top of several engines, including PyTorch, TensorFlow and ONNX Runtime. Its main building blocks are:

  • Criteria and ZooModel: describe what you want to load (engine, model location, input and output types) and DJL loads it.
  • Translator: converts your Java objects (a String, an image, a domain object) into tensors and back. This is where preprocessing and post-processing live.
  • Predictor: the object you call to run inference.
  • Model zoo: pre-trained models for common tasks such as image classification, object detection and text embeddings.

Choose raw ONNX Runtime when you have one ONNX model and want the thinnest possible layer. Choose DJL when you need image or text preprocessing helpers, want to load PyTorch models directly, or expect to switch engines. Note that a DJL Predictor is not designed to be shared across threads; create one per thread or use a pool, while the underlying model can be shared.

Performance and memory notes

  • Off-heap memory: native engines allocate memory outside the Java heap. A container with a 2 GB limit and -Xmx2g will be killed. Leave headroom for the model, native buffers and thread stacks.
  • Warm-up: the first few inferences are often slower. Run a few dummy predictions at startup before marking the service healthy.
  • Threads: ONNX Runtime has its own intra-op thread pool. With many concurrent request threads, limit it through SessionOptions.setIntraOpNumThreads to avoid oversubscribing CPU cores.
  • Batching: processing several inputs in one call is usually more efficient than many single calls, if your latency budget allows it.
  • Graph optimisation and quantisation: ONNX Runtime applies graph optimisations by default; quantising a model to 8-bit integers can reduce size and speed up CPU inference, but always re-check accuracy.
  • Native libraries: the Maven artefacts bundle native binaries for common platforms. Check that your target OS and CPU architecture (for example ARM servers) are supported before committing.

Measure with realistic inputs, using JMH or load tests, rather than assuming.

How NextWebGen can help

NextWebGen develops and maintains Java and Spring applications, and we can help you decide whether a model belongs inside your JVM or in a separate service, then build the integration, tests and monitoring around it. To discuss your system, request a free quote.