🚀 JPyRust: Call CPython from Java, without a Python service
One 2.2 MB JAR. Python runs in worker processes the JVM manages, provisions itself on first run, and can crash without taking the JVM down.

💡 Introduction
JPyRust lets a Java application call its own Python functions — a scikit-learn model, a PyTorch pipeline, pandas code — as if they were local methods. There is no Python service to deploy: the library downloads a pinned CPython, builds a venv with your requirements.txt, and runs your @task functions in worker processes that the JVM starts, watches and restarts.
|
JPyRust |
In-process (Jep, Pemja, GraalPy) |
Python HTTP service |
| Deploy |
One JAR (2.2 MB) |
JAR + Python and native build per host (GraalPy: ~160 MB of JARs) |
A second service to run |
| Python crash or hang |
Worker restarted, JVM keeps running |
A native crash takes the JVM down; a hang blocks the caller |
Service restarts separately |
| CPU-bound Python on N cores |
workers(n) processes |
One GIL per JVM |
Several server processes |
| Call latency, 16 B round trip |
10.7 µs p50 |
2.2 µs p50 (Jep) |
65 µs p50 (HTTP), 82 µs (gRPC) |
| Full CPython ecosystem |
Yes |
Jep/Pemja yes, GraalPy partial |
Yes |
Latency from the JMH benchmarks on an Apple M5; in-process bridges were not measured.
🌟 Why JPyRust?
- 📦 One dependency, nothing to install: a checksum-verified CPython from python-build-standalone on every OS, 3.11 by default or 3.12–3.14 with
pythonVersion(...), cached in ~/.jpyrust/cache. Docker images based on glibc work as-is.
- 🛡️ Crash isolation: a segfault,
os._exit or a hung task raises WorkerCrashedException / WorkerTimeoutException and the worker is respawned; the JVM never goes down with it.
- 🚀 Shared-memory IPC: inputs and outputs travel through reusable shared-memory buffers, 5.6–12.3× faster than a loopback HTTP call at the payload sizes measured (16 B to 1 MB).
- 🔄 Multi-core Python:
workers(4) runs four Python processes behind one bridge — 3.0× the throughput of one worker on CPU-bound code, which a single-GIL design cannot do.
- 🌱 Spring Boot starter:
jpyrust.* properties, JPyRustTemplate, Micrometer timers and an Actuator health check.
🏗️ Architecture
Each JPyRustBridge owns one or more Python worker processes (workers(n)). Several bridges can run side by side with their own environments, for example one per model.
🧩 System Component Diagram
graph TD
subgraph JavaApp [☕ Java Application Layer]
style JavaApp fill:#f9f2f4,stroke:#333,stroke-width:2px
J1["Camera 1 Bridge<br>(Instance ID: cam1)"]
J2["Camera 2 Bridge<br>(Instance ID: cam2)"]
end
subgraph NativeLayer [🦀 Rust JNI Layer]
style NativeLayer fill:#e8f4f8,stroke:#333,stroke-width:2px
R1["BridgeState A<br>{Ptr: 0x7FA...}"]
R2["BridgeState B<br>{Ptr: 0x81B...}"]
end
subgraph PythonLayer [🐍 Embedded Python Layer]
style PythonLayer fill:#edfbec,stroke:#333,stroke-width:2px
P1["Python Worker A<br>(PID: 1001)"]
P2["Python Worker B<br>(PID: 1002)"]
end
J1 -- "JNI Call (nativePtr)" --> R1
J2 -- "JNI Call (nativePtr)" --> R2
R1 <== "⚡ SHMEM (Images)" ==> P1
R2 <== "⚡ SHMEM (Images)" ==> P2
P1 -- "JSON Result" --> R1
P2 -- "JSON Result" --> R2
⚡ Execution Sequence
sequenceDiagram
participant Java as ☕ Java (Spring)
participant Rust as 🦀 Rust (JNI)
participant Py as 🐍 Python (Worker)
Note over Java, Py: Initialization Phase
Java->>Rust: new JPyRustBridge("cam1").initialize()
Rust->>Rust: Allocate BridgeState (Heap)
Rust->>Py: Spawn Process (arg: --instance-id cam1)
Py->>Py: Setup ~/.jpyrust/cam1/
Py-->>Rust: Signal "READY"
Rust-->>Java: Return nativePtr (Handle)
Note over Java, Py: Inference Phase (Loop)
Java->>Rust: processImage(ptr, image_bytes)
Rust->>Rust: Write to Shared Memory
Rust->>Py: Send Signal (IPC)
Py->>Py: Read SHMEM -> YOLO Inference
Py-->>Rust: Return JSON Result
Rust-->>Java: Return Result String
Measured with JMH against a persistent Python HTTP server on the same machine (details and how to run):
| Payload |
JPyRust p50 |
Python HTTP server p50 |
| 16 B |
10.7 µs |
65.3 µs |
| 64 KB |
16.1 µs |
89.6 µs |
| 1 MB |
79.0 µs |
974.9 µs |
CPU-bound Python from four Java threads: 290 calls/s with one worker, 875 with workers(4), versus 287–288 for a threaded Python HTTP server.
A float32 array of 1,000,000 values, scaled in numpy and returned: 0.65 ms as NDArray, 152 ms as JSON over HTTP (234×).
Apple M5, OpenJDK 17, CPython 3.11.18, 2026-12-05. Run ./gradlew :benchmarks:jmh on your own hardware.
🚀 Quick Start
1. Installation (Gradle)
From 2.0.0 the library is published to Maven Central:
dependencies {
implementation("io.github.farmer0010:jpyrust:3.1.0")
// Spring Boot: implementation("io.github.farmer0010:jpyrust-spring-boot-starter:3.1.0")
}
JitPack keeps serving every tag (com.github.farmer0010.JPyRust:JPyRust:<tag>, or com.github.farmer0010.JPyRust:jpyrust-spring-boot-starter:<tag>, from https://jitpack.io); its JAR carries natives for Linux x86_64, macOS Apple Silicon and Windows x86_64 only.
2. Usage (Java) — Your Own Python Code
Register any Python function as a task and call it from Java. You choose the Python dependencies, and nothing beyond numpy is installed unless you ask for it.
# tasks/text_tasks.py
from jpyrust import task
@task("WORD_COUNT")
def word_count(data: bytes, args: str):
return {"words": len(data.decode("utf-8").split()), "args": args}
JPyRustBridge bridge = new JPyRustBridge("text")
.requirements(Path.of("python/requirements.txt"))
.moduleDir(Path.of("python/tasks"));
bridge.initialize();
String json = bridge.call("WORD_COUNT", "hello jpyrust"); // {"words": 2, "args": ""}
byte[] raw = bridge.call("WORD_COUNT", bytes, "any args here"); // raw bytes in, raw bytes out
- A task receives the input bytes and the
args string. Returning bytes sends them as-is, str is UTF-8 encoded, anything else is sent as JSON. An exception becomes a TaskFailedException in Java.
- Every
.py file in each moduleDir is imported at daemon start. Task names are case-insensitive, and a registered task replaces a built-in one with the same name. A module that fails to import is reported on stderr and skipped.
requirements(...) replaces the bundled core requirements.txt; requirements of enabled extras are appended to it. The install is keyed by the file’s SHA-256, so changing it re-runs pip install on the next initialize().
- Calls from several threads run in parallel with
workers(n); callAsync(...) returns a CompletableFuture. See the API reference for every option.
bridge.proxy(MyTasks.class) implements a Java interface with tasks: each method calls the task named after it (or @Task("NAME")) and converts the result, so double score(String text) returns a double. See Typed calls.
- With OpenTelemetry on the classpath, each call is a client span and its trace continues in Python: a task runs in a server span under it, so spans the task creates land in the same trace. See Tracing.
3. Arrays (NumPy)
NDArray sends typed, shaped arrays both ways with no JSON in between. The task receives a numpy.ndarray, and an array it returns comes back typed.
NDArray image = NDArray.ofUInt8(pixels, 480, 640, 3);
NDArray gray = bridge.call("GRAYSCALE", image, ""); // float32, shape (480, 640)
float[] values = gray.toFloatArray();
@task("GRAYSCALE")
def grayscale(image, args):
return image.astype("float32").mean(axis=2) / 255
The wire format is NumPy’s own .npy, so nothing is encoded element by element. See Arrays in the API reference for every dtype.
4. Streaming
A Python generator becomes a Java Stream. Values arrive as they are produced, the worker waits for Java before producing the next one, and closing the stream stops the generator.
@task("TOKENS")
def tokens(prompt, args):
for token in model.generate(prompt.decode()):
yield token
try (Stream<String> tokens = bridge.callStream("TOKENS", "Once upon a time")) {
tokens.forEach(System.out::print);
}
examples/spring-boot streams a generator to the browser as Server-Sent Events. See Streaming in the API reference.
5. Usage (Java) — Built-in Vision
Important: As of v1.3.0, static methods are removed. You must instantiate JPyRustBridge.
The built-in AI tasks are opt-in extras. The default install is only numpy; enable an extra with extras(...) before initialize() and its Python dependencies are installed with it.
| Extra |
Tasks / Java methods |
Installs |
License note |
vision |
YOLO (processImage), EDGE_DETECT (processEdgeDetection) |
ultralytics, torch, torchvision, opencv-python-headless |
ultralytics is AGPL-3.0 |
audio |
WHISPER (processAudio) |
openai-whisper, torch |
|
ml |
NLP_TEXTBLOB (processNlp), REGRESSION (processRegression) |
pandas, scikit-learn, textblob |
|
llm |
LLM (callStream), a Hugging Face chat model set with llmModel(...) |
transformers, torch |
the model’s own license |
Calling a task without its extra fails with Task YOLO requires extras("vision").
The llm extra serves a Hugging Face chat model from the worker, on CUDA, Apple Silicon (MPS) or CPU, and streams the answer piece by piece. Closing the stream stops generation. examples/llm-chat relays it as Server-Sent Events from Spring Boot.
try (JPyRustBridge llm = new JPyRustBridge("chat").extras("llm").llmModel("HuggingFaceTB/SmolLM2-360M-Instruct")) {
llm.initialize(); // downloads the model into the Hugging Face cache on first use
try (Stream<String> answer = llm.callStream("LLM", "{\"messages\": [{\"role\": \"user\", \"content\": \"Hi!\"}]}")) {
answer.forEach(System.out::print);
}
}
import com.jpyrust.JPyRustBridge;
public class VisionService {
public void startDetection() {
// 1. Create independent instances for each camera
JPyRustBridge cam1 = new JPyRustBridge("cam1").extras("vision");
JPyRustBridge cam2 = new JPyRustBridge("cam2").extras("vision");
// 2. Initialize with defaults (Spawns workers in ~/.jpyrust/camX)
cam1.initialize();
// 2-1. (v1.3.1+) Initialize with a custom model & confidence threshold
cam2.initialize("/path/to/workdir", "custom_model.pt", 0.25f);
// 3. Process Images (Thread-Safe)
// arg: (imageData, length, width, height, channels)
byte[] result1 = cam1.processImage(imgData1, len1, 640, 480, 3);
byte[] result2 = cam2.processImage(imgData2, len2, 640, 480, 3);
System.out.println("Cam1 Result: " + new String(result1));
}
}
6. Usage (Java) — Built-in Audio / Whisper
New: JPyRust can also transcribe audio via OpenAI Whisper, reusing the same persistent-daemon architecture as YOLO.
import com.jpyrust.JPyRustBridge;
public class SpeechService {
public void startTranscription() {
JPyRustBridge stt = new JPyRustBridge("stt").extras("audio");
// Initialize with a Whisper model name (e.g. "tiny", "base", "small") or a local .pt checkpoint path.
// The trailing whisperModelPath argument is the only difference from the image-only overload.
stt.initialize("/path/to/workdir", "yolov8n.pt", 0.5f, "session-key", "tiny");
// arg: (audioData WAV bytes, length, sampleRate)
byte[] result = stt.processAudio(audioBuffer, audioLength, 16000);
// {"recognized_text": "...", "confidence": 0.87}
System.out.println("Transcription: " + new String(result));
}
}
Audio input is expected as a WAV container (16kHz, mono, 16-bit PCM). confidence is an approximation derived from Whisper’s per-segment avg_logprob, not a calibrated probability.
7. GPUs and per-environment versions
Tasks use the GPU through their own libraries; jpyrust.config["device"] is cuda, mps or cpu. Three settings make the same code fit each machine:
new JPyRustBridge("detector")
.devices("cuda:0", "cuda:1") // one worker per GPU; each task sees its GPU as cuda:0
.torch("auto") // torch build matching the NVIDIA driver, cpu without a GPU
.extras("vision");
java -jar jpyrust-3.1.0.jar doctor # what this machine has and what to use
java -Djpyrust.torch=cpu -jar app.jar # override at start, no code change
Many small requests use a GPU better when they are sent together. bridge.batcher("SCORE").maxBatch(32).build() collects submit(NDArray) calls into one array along a new first axis and splits the result back to each caller; see Batching.
On Apple Silicon, devices("mps") (or the default device detection) runs tasks on the built-in GPU; macOS torch wheels already include MPS, so torch(...) stays default.
A CUDA or MPS out-of-memory error throws GpuOutOfMemoryException and restarts that worker so the memory is released. STATUS and the Actuator health check report the GPU name and memory. See Choosing versions per environment and Command line. GPU code paths are not covered by CI, which has no GPU runners.
🛠️ Configuration & Troubleshooting
🔧 1. UnsatisfiedLinkError / DLL Not Found
- Cause: Java cannot find the native library.
- Fix: The library is bundled in the JAR and extracted to a temp file automatically —
jpyrust.dll (Windows), jpyrust.dylib (macOS), or jpyrust.so (Linux). Natives live under natives/<os>-<arch>/ in the JAR (windows-x86_64, linux-x86_64, linux-aarch64, linux-x86_64-musl, linux-aarch64-musl, darwin-aarch64, darwin-x86_64); musl-based Linux such as Alpine is detected and gets the -musl build. The JitPack build only contains the three committed to the repo (windows-x86_64, linux-x86_64, darwin-aarch64); the JAR attached to each GitHub Release and the Maven Central artifact contain all seven. If loading fails, the error lists the exact path that was looked up.
🛡️ 2. WinError 5 (Access Denied)
- Cause: Windows Security permissions on Shared Memory.
- Fix: JPyRust v1.2+ uses explicit
SECURITY_ATTRIBUTES with SDDL D:P(A;;GA;;;OW)(A;;GA;;;SY), granting access only to the owning user and SYSTEM so the Python child process (same user) can open the mapping. No manual action required.
🐍 3. Python Dependency Issues
- Every OS: on the first
initialize(), JPyRust downloads a portable CPython build from python-build-standalone for your OS and architecture (Windows x86_64, macOS and Linux on x86_64/aarch64, glibc or musl), verifies it against a SHA-256 hash built into the library, unpacks it into ~/.jpyrust/cache, creates a private venv at ~/.jpyrust/<instanceId>/venv and installs requirements.txt plus the enabled extras into it. Nothing needs to be installed beforehand (tar must be on PATH, as it is on Windows 10+, macOS and mainstream Linux), but the first run needs network access to GitHub and PyPI (honoring https.proxyHost for the download and HTTPS_PROXY for pip). The venv is built once per instance directory (tracked by a .installed marker); delete that directory to force a clean reinstall. A failed download, checksum mismatch or pip error makes initialize() throw. On Alpine (musl) it downloads the musl build, and pip installs musllinux wheels.
- Python version:
pythonVersion("3.13") picks CPython 3.11 (default), 3.12, 3.13 or 3.14. Changing it rebuilds the instance’s venv on the next initialize(). The bundled core requirements pin numpy 2.3.5, and the built-in extras pin torch 2.14 with current releases (ultralytics 8.4, openai-whisper 20250625, pandas 3), the same on every version. 2.x used numpy 1.26 and torch 2.2 on 3.11–3.12, see Migrating to 3.0.0.
- If a built-in task reports
requires extras(...), add that extra with extras(...).
- Offline / intranet:
python(Path.of("/usr/bin/python3.11")) builds the venv from an interpreter you already have (python -m venv --system-site-packages) instead of downloading one, on every OS. Packages already installed for that interpreter are reused, so pip only fetches what is missing. Point pip at an internal index with the standard PIP_INDEX_URL / PIP_TRUSTED_HOST environment variables or a pip.conf; the pip child process inherits them. The interpreter is chosen when the instance directory is first set up, so use a fresh directory to switch.
- Docker: glibc-based images (e.g.
eclipse-temurin) work as-is: the first initialize() downloads Python into the container. Bake it in at build time by running your app’s initialization once in a RUN step, or install Python in the image and pass it with python(...). Docker’s default 64 MB /dev/shm caps the shared-memory buffers; larger payloads go through files automatically, or raise the limit with --shm-size.
- Logging: JPyRust logs through
System.Logger (logger name com.jpyrust), which goes to java.util.logging by default or to SLF4J/Log4j when their System.Logger bridge is on the classpath. pip output is logged at DEBUG.
⏱️ 4. Errors & Timeouts
Every failure is a JPyRustException (a RuntimeException), so the JVM never crashes and nothing returns null.
| Situation |
What you get |
Any call before initialize() or after close() |
IllegalStateException |
| The Python task raises (bad input, unknown task, missing extra, …) |
TaskFailedException with the worker’s ERROR ... message; the worker keeps running |
| The task runs longer than the task timeout |
WorkerTimeoutException; the worker process is killed and respawned on the next call |
The worker process dies (segfault, os._exit, OOM kill) |
WorkerCrashedException; respawned on the next call |
Heap ByteBuffer passed, or length larger than the buffer |
JPyRustException (Input must be a direct ByteBuffer / Invalid input length ...) |
The Python daemon does not start during initialize() |
JPyRustException (Failed to initialize JPyRustBridge, cause Daemon start failed: ...) |
JPyRustBridge bridge = new JPyRustBridge("svc")
.timeouts(Duration.ofSeconds(120), Duration.ofSeconds(10)) // startup (incl. model load), per task
.workers(4); // 4 Python processes, calls run in parallel
- Defaults are 600 s for startup and 300 s per task.
workers(n) starts n Python processes sharing one environment. Calls from different threads run in parallel on separate processes, so CPU-bound Python code uses n cores instead of being serialized by one GIL. callAsync(task, bytes, args) returns a CompletableFuture backed by a pool of the same size.
- Data goes through reusable shared-memory buffers that grow as needed (up to 256 MB); larger payloads, or platforms where shared memory is unavailable, fall back to files automatically. There is no fixed output size limit.
- A respawned worker pays the startup cost again (model reload).
📜 Version History
See CHANGELOG.md.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
Built with 🦀 Rust & ☕ Java by Farmer0010 (JPyRust Team).
评论