iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Using Python libraries in Java is possible, but the right method depends on which runtime hosts the application and whether the Python package needs CPython or native extensions. For a Java-hosted Python 3 workload, GraalPy embedded through the GraalVM Polyglot API is the strongest current starting point; a separate Python process is often safer for CPython-heavy packages.
Java cannot import a Python package in the same way that it imports a Java class. A Java application must either embed a Python runtime, communicate with a Python interpreter through a bridge or process boundary, or replace the Python dependency with a Java implementation.
Key takeaways
- GraalPy 25.x, with documentation examples using version 25.0.3 and Python 3.12.8 compatibility, is the most direct current option for embedding Python 3 in a Java application.
- Pure-Python packages are generally easier to embed than packages that depend on CPython internals, native shared libraries, binary wheels, or operating-system-specific behavior.
- Py4J normally connects separate Python and Java runtimes, while JPype is primarily designed for Python applications that need Java libraries.
- A separate Python service or process provides the broadest CPython compatibility and stronger operational isolation, at the cost of IPC, serialization, deployment, and monitoring overhead.
- GraalPy’s
allowAllAccess(true)setting is suitable only for controlled development because unrestricted host, file, thread, and native access can expose the Java application and operating system.
What does using Python libraries in Java actually mean?
Using Python libraries in Java can mean three different integration goals:
- Executing Python code from Java. Java evaluates a Python expression or script inside an embedded runtime.
- Importing and calling a Python package. Java starts Python code that imports a package such as
requestsornumpy, then receives the result. - Calling Java libraries from Python. Python accesses Java classes on the classpath. This is the reverse direction and should not be confused with Java importing an arbitrary CPython module as a Java class.
GraalPy supports both embedded Python execution and Java interoperability. For example, embedded Python can access Java classes with java.type(), while Java can retrieve a Python function through polyglot bindings. See the GraalPy Python and Java interoperability documentation for the supported model and security implications.
Popular on Amazon
Which method should you choose?
Choose the integration method according to the host language, package compatibility, isolation requirements, and deployment model. The following table separates tools that are often incorrectly treated as interchangeable.
| Approach | Runtime architecture | Best fit | Important limitation |
|---|---|---|---|
| GraalPy embedding | Python runs inside the Java process through the Polyglot API. | New Java applications needing in-process Python 3 calls. | Not every CPython package or native extension works unchanged. |
| Py4J | Python and Java normally run as separate interpreters connected by a gateway. | Existing Python-led systems, process isolation, and standard CPython environments. | Gateway calls cross a process boundary and use proxies or transferred values. |
| JPype | A Python module starts or embeds a JVM and exposes Java to Python. | Python applications that need Java libraries. | It is usually the wrong direction for a Java application that needs to host Python. |
| Jython | Python runs on the JVM. | Maintaining legacy Jython applications and Jython-specific code. | Jython is primarily associated with Python 2.x-era compatibility and does not automatically support CPython native packages. |
| Separate Python service or process | Java communicates with standard CPython through HTTP, gRPC, messaging, pipes, or sockets. | Native-heavy packages, independent scaling, and failure isolation. | Requires an API, serialization, lifecycle management, health checks, and observability. |
| Java rewrite or replacement | The required behavior is reimplemented or provided by a Java-native library. | Strict latency, throughput, deployment, or JVM-only requirements. | Development and behavioral-equivalence costs can be substantial. |
For a Java-led application, start with a GraalPy proof of concept when the required package is compatible. Use a separate CPython process or service when package compatibility and isolation matter more than in-process calls.
Why is GraalPy the leading Java-hosted option?
GraalPy is designed to embed Python 3 in Java through the GraalVM Polyglot API. The current GraalPy JVM documentation uses the 25.x line, provides examples with version 25.0.3, and identifies compatibility with Python 3.12.8 in that documentation snapshot. Check the release documentation immediately before publication or implementation because GraalPy artifact versions change.
GraalPy is available through Maven Central and provides Maven and Gradle tooling for Python resources and package management. A Java application can keep Python code and dependencies within a Java-oriented build rather than assuming that a developer’s system CPython installation will be present in production. The GraalPy JVM developer documentation covers embedding, package installation, security, and deployment.
GraalPy’s main advantages are in-process calls, Java/Python object interoperability, configurable host permissions, and support for packaging Python resources with the application. The main trade-off is compatibility: GraalPy is not identical to CPython, and native extensions, binary wheels, multiprocessing, system libraries, and CPython-specific behavior require direct testing.
Linux is the best-supported starting environment according to the GraalPy documentation, while support for some GraalPy features is more limited on Windows and macOS. Treat the operating system and CPU architecture as part of the compatibility test, not as an afterthought.
How do you run Python from Java with Gradle?
A minimal Gradle project applies the GraalPy plugin, adds the Polyglot and Python embedding artifacts, declares the Python package, and creates a GraalPy context. The following Kotlin DSL follows the current documentation’s 25.0.3 example:
Recommended Free Tools
plugins {
id("java")
id("application")
id("org.graalvm.python") version "25.0.3"
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.graalvm.polyglot:polyglot:25.0.3")
implementation("org.graalvm.python:python-embedding:25.0.3")
}
graalPy {
packages = listOf("termcolor==2.2")
}
application {
mainClass.set("interop.App")
}
All GraalPy-related versions should remain aligned. The example pins termcolor==2.2 so that the build declares a reproducible Python dependency; replace that package with a version that your compatibility tests support.
Installations performed into the developer’s ordinary CPython environment are not automatically visible to the embedded GraalPy runtime. Declare Python dependencies through the GraalPy build configuration and rebuild the application.
Use the following Java class to execute Python:
package interop;
import org.graalvm.python.embedding.GraalPyResources;
public class App {
public static void main(String[] args) {
try (var context = GraalPyResources.createContext()) {
System.out.println(
context.eval("python", "'Hello from Python'").asString()
);
}
}
}
The expected output is:
Hello from Python
GraalPyResources.createContext() creates the configured embedding context, and context.eval("python", source) evaluates Python source. The official embedding examples should be treated as the authority for changes to the API or plugin.
How do you configure GraalPy with Maven?
An existing Maven application can add the Polyglot and Python embedding dependencies with one shared GraalPy version property. The dossier’s current documentation snapshot uses 25.0.3:
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchAlso popular on Amazon
<properties>
<graalpy.version>25.0.3</graalpy.version>
</properties>
<dependencies>
<dependency>
<groupId>org.graalvm.polyglot</groupId>
<artifactId>polyglot</artifactId>
<version>${graalpy.version}</version>
</dependency>
<dependency>
<groupId>org.graalvm.python</groupId>
<artifactId>python-embedding</artifactId>
<version>${graalpy.version}</version>
</dependency>
</dependencies>
The Maven dependency pattern is useful for an existing application, but Python package resources still need to be managed through the GraalPy Maven tooling or the supported project configuration. Do not assume that adding Java dependencies alone installs arbitrary Python packages.
GraalPy also provides a Maven archetype. The Oracle reference documentation shows an archetype command using version 24.0.0, which is historical relative to the current 25.x documentation. Do not copy that version without checking the current GraalPy Maven guidance.
How do you import and call a Python package?
Declare the package in the GraalPy build and import it from Python source evaluated by the Java context. This example uses the configured termcolor dependency:
package interop;
import org.graalvm.polyglot.Context;
import org.graalvm.python.embedding.GraalPyResources;
public class App {
public static void main(String[] args) {
try (Context context = GraalPyResources.contextBuilder().build()) {
String source = """
from termcolor import colored
colored("hello Java", "red")
""";
var result = context.eval("python", source);
System.out.println(result.asString());
}
}
}
The package must be available to the GraalPy context created by the build configuration. A successful import proves only that import resolution works; it does not prove that the package’s important operations, optional dependencies, native libraries, subprocesses, or filesystem behavior work in production.
Free tools Windows power users keep installed
One-click scans. No signup required.
How do you call a Python function from Java?
Define a Python function once, evaluate the definition, retrieve the function from Python bindings, and invoke the function with Java arguments. This approach is clearer and generally more reusable than constructing a new large source string for every call.
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.python.embedding.GraalPyResources;
public class Main {
public static void main(String[] args) throws Exception {
try (Context context = GraalPyResources.createContext()) {
var source = Source.newBuilder(
"python",
"def calculate_mean(values):n" +
" return sum(values) / len(values)n",
"statistics.py"
).build();
context.eval(source);
var function = context
.getBindings("python")
.getMember("calculate_mean");
var result = function.execute(new int[] { 10, 20, 30 });
System.out.println(result.asDouble());
}
}
}
The function returns 20.0 for the supplied values. GraalPy’s polyglot binding examples demonstrate the same general pattern: evaluate Python code, retrieve an exported function, execute it, and convert the returned polyglot value.
Java-to-Python conversion is not automatically lossless for every type. Test the boundary explicitly for int, long, double, BigInteger, arrays, lists, maps, dictionaries, byte arrays, mutable objects, large numerical arrays, Java null, and Python None. Also test how Python exceptions appear to Java and how Java exceptions appear inside Python callbacks.
How can embedded Python call Java?
Embedded Python can access Java classes on the classpath through GraalPy’s Java interoperability features. For example:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
import java
BigInteger = java.type("java.math.BigInteger")
value = BigInteger.valueOf(42)
result = value.shiftLeft(128)
Python can also import Java collection classes:
from java.util import ArrayList
items = ArrayList()
items.add("Java")
items.add("Python")
Java interoperability is useful when Python code needs an existing Java service, model, collection, or utility. Broad host access also expands the security boundary: untrusted Python should not automatically receive unrestricted access to Java classes, application objects, files, threads, or other resources.
How should you secure an embedded Python context?
Configure only the host, I/O, thread, and native permissions that the Python code actually needs. A permissive development context can be created as follows:
try (var context = Context.newBuilder("python")
.allowAllAccess(true)
.build()) {
// Development-only use
}
allowAllAccess(true) disables most security protections and should not be a production shortcut. A more restrictive configuration can look like this:
Also popular on Amazon
var context = Context.newBuilder("python")
.allowHostAccess(HostAccess.EXPLICIT)
.allowIO(IOAccess.newBuilder()
.fileSystem(FileSystem.newDefaultFileSystem(
Path.of("/safe/directory")))
.build())
.allowCreateThread(false)
.allowNativeAccess(false)
.build();
The example requires the corresponding Polyglot imports and should be adapted to the exact GraalVM API version. allowHostAccess controls Java host objects, allowIO controls file and related I/O, allowCreateThread controls thread creation, and allowNativeAccess is especially important for packages that load native extensions. The GraalPy security documentation explains the available restrictions and their limitations.
Native Python extensions can execute native binaries and may bypass protections that apply to interpreted Python code. If the Python code is untrusted, native-extension access is a particularly serious risk; process-level isolation may be more appropriate than relying solely on Polyglot permissions.
How do you package Python code with a Java application?
GraalPy supports both virtual-filesystem resources and an external resource directory, and the choice affects portability and runtime behavior.
| Deployment model | Advantages | Risks and trade-offs |
|---|---|---|
| Virtual filesystem | Python code and packages can be embedded as Java resources inside a JAR or native executable, enabling a single deployable artifact. | Native libraries may still need platform-specific handling, and packages that require ordinary filesystem paths or dynamic files may need adaptation. |
| External directory | Resources are inspectable and replaceable, and packages expecting conventional files may behave more naturally. | Deployment includes more files, runtime paths and permissions must be correct, and resources can drift from the Java application version. |
Neither packaging model magically removes native-library requirements. Test the final artifact on the same operating system and architecture used in production. The GraalPy deployment documentation describes the virtual-filesystem and external-directory approaches.
Which Python packages work best in GraalPy?
Pure-Python packages are usually the simplest candidates, while packages with substantial native code need a package-specific proof of concept.
| Compatibility category | Examples or characteristics | Testing expectation |
|---|---|---|
| Lower risk | Pure-Python utilities, text-processing libraries, and serialization or validation packages with few CPython assumptions. | Verify the actual functions used, dependency resolution, exceptions, and packaging. |
| Higher risk | NumPy, SciPy, pandas, PyTorch, TensorFlow, OpenCV, and other packages with substantial native code. | Test the exact GraalPy release, operating system, architecture, native libraries, and production operation. |
| Special-case risk | Packages using os.fork, fork-based multiprocessing, system shared libraries, signals, sys.executable, hard-coded filesystem layouts, or native thread-local state. |
Test startup, concurrency, subprocess behavior, resource paths, and failure recovery; consider a separate CPython process. |
Do not promise that every package on PyPI will work. GraalPy documents native-package and platform-specific limitations involving native access, native library loading, garbage collection, os.fork, and Java virtual threads. The package compatibility guidance should be checked for the selected release.
A practical proof of concept installs and tests the package under the exact GraalPy version and target operating system used for deployment. Testing only import package is insufficient; execute the real production path with representative inputs.
Can GraalPy native extensions run on Java virtual threads?
Native Python extensions should not be assumed to work safely on Java virtual threads. GraalPy documentation explains that native extensions commonly rely on native thread-local state that cannot safely track virtual-thread scheduling. If embedded code may call native extensions, dispatch those calls to platform threads instead of Java virtual threads.
ExecutorService platformExecutor =
Executors.newFixedThreadPool(4);
platformExecutor.submit(() -> {
// Call GraalPy code that may use native Python extensions here.
});
This is not a universal requirement for every GraalPy workload. It is a specific design concern for code that loads or calls native extensions, and the package’s actual behavior still needs testing.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →How should you manage context lifetime and concurrency?
A GraalPy Context owns Python execution state, so context lifetime is an architectural decision rather than a trivial implementation detail.
- Reusing a context can preserve imports, globals, caches, and loaded modules.
- Creating a context for every request can increase startup and memory costs.
- A long-lived context can retain Python and Java objects when references remain reachable.
- Sharing a context across threads requires compliance with the runtime’s concurrency rules and testing of application state.
- Python callbacks into Java can introduce reentrancy, lock-ordering, and deadlock risks.
There is no universal rule that one context must be shared or that every request must receive a new context. Choose based on isolation, initialization cost, statefulness, concurrency, and failure behavior. GraalPy specifically warns that interactions between the Python GIL and Java interoperability can deadlock when one side waits while another thread attempts a callback; the GraalPy concurrency guidance should inform the design.
Also popular on Amazon
When is Py4J a better choice?
Py4J is a gateway bridge, not an in-process CPython embedding solution. A typical Py4J arrangement has a Python process connect to a Java gateway, access exposed Java objects through proxy objects, and optionally use callbacks from Java into Python.
from py4j.java_gateway import JavaGateway
gateway = JavaGateway()
random = gateway.jvm.java.util.Random()
number = random.nextInt(10)
Py4J’s current installation documentation supports Python 3.9 through 3.13 and requires Java 7 or newer in the documentation snapshot. Verify those requirements against the version selected for your project. The Py4J installation documentation and Py4J client/server documentation describe the gateway model.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Choose Py4J when standard CPython compatibility, an existing Python-led application, or process separation matters more than in-process latency. Do not choose Py4J expecting Java to import a Python module without a separate interpreter, or expecting Python objects to behave exactly like ordinary Java objects. Gateway calls introduce proxy, transfer, and process-management overhead.
When is JPype a better choice?
JPype is primarily for Python applications that need access to Java libraries, not for Java applications that need to host Python packages. JPype exposes a JVM to Python at the native level rather than using Py4J’s remote gateway architecture. The JPype documentation describes its Python-to-Java direction and integration model.
Choose JPype when Python is the main application, the Java component is a library or service, and tighter Python/JVM integration is useful. Current JPype documentation requires the Java module API introduced in Java 9, making Java 11 the earliest supported Java version in that documentation; Java 8 users must use JPype 1.5.2 or earlier. See the JPype user guide’s Java-version guidance.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Is Jython still suitable for using Python libraries in Java?
Jython is mainly a legacy option for applications already tied to Jython behavior, rather than the modern default for Python 3 package integration. Jython historically provided close Java integration, but Python packages written for CPython—especially packages with native extensions—are not automatically compatible with Jython.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsUse Jython when maintaining an existing Jython application, the codebase depends on Jython-specific behavior, the supported Python version is acceptable, and the dependency set is already proven compatible. For a new Java application requiring Python 3 packages, evaluate GraalPy or a standard CPython service instead. GraalPy’s JVM developer documentation presents GraalPy as a Python 3 path for projects migrating from Jython-oriented JVM Python.
When should Java call a separate Python service or process?
A separate Python service or process is often the most reliable choice when a package depends heavily on standard CPython, native wheels, large model runtimes, or operating-system behavior. Java can communicate through HTTP, REST, gRPC, a message queue, local sockets, Unix pipes, standard input/output, or a batch/job interface.
This architecture is especially useful when Python and Java need independent scaling, when a model has a large startup footprint, when failures must not corrupt the Java process, or when the organization already operates Python services. The process boundary can also provide stronger isolation than in-process permissions.
The costs are explicit API design, serialization, network or IPC latency, separate health checks, lifecycle management, deployment, logging, tracing, and versioning. For coarse-grained operations such as document analysis or model inference, those costs may be acceptable. For thousands of tiny calls, an in-process approach may be simpler—but only after compatibility and security are proven.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallWhat are the most common failure modes?
“I installed the package with pip, but Java cannot import it”
The package may have been installed into system CPython rather than the GraalPy environment, omitted from the GraalPy build configuration, placed outside the runtime resource path, or made unavailable by a missing native wheel.
Also popular on Amazon
- Confirm the exact GraalPy runtime and version.
- Declare the package through the GraalPy Maven or Gradle configuration.
- Clean and rebuild the Java project.
- Test on the same operating system and CPU architecture as production.
- Inspect native-library and wheel compatibility if import resolution still fails.
“The package imports, but the real operation fails”
An import test may not load optional dependencies, execute native code, access files, start subprocesses, or trigger unsupported Python behavior. Run the actual production operation with representative inputs and capture the complete exception chain.
“The Python code cannot read a file”
The context may have restricted I/O, or the application may be using virtual-filesystem packaging while the package expects an ordinary filesystem path. Grant narrowly scoped I/O, provide application-managed streams or buffers where possible, confirm the resource path, and avoid using allowAllAccess(true) as a production fix.
“The application crashes or uses too much memory”
Native extensions can allocate memory outside ordinary JVM garbage collection, while cross-boundary references and process-wide native state can retain resources. Profile JVM and native memory, bound context lifetime where appropriate, avoid repeatedly loading incompatible native libraries into one process, and consider a separate Python process for unstable native dependencies.
“The application deadlocks”
Python-to-Java callbacks, incorrect context sharing, lock-ordering errors, and GIL/interoperability interactions can cause deadlocks. Minimize callback depth, define lock ownership, use timeouts, test concurrency independently from functional correctness, and dispatch native-extension calls away from virtual threads.
“Java 8 no longer works”
Current JPype documentation requires Java 11 or newer, while JPype 1.5.2 or earlier is identified for Java 8 users. That limitation applies to current JPype documentation and does not automatically describe every GraalPy release; check the selected GraalPy artifact’s requirements separately.
What should a production proof of concept test?
A useful proof of concept tests the complete deployed behavior rather than proving only that a Python statement evaluates. Use this checklist before selecting an integration strategy:
- Run the exact package version under the exact GraalPy version and target operating system.
- Exercise the production function, not only
import package. - Test Java-to-Python values including numbers, collections, maps, binary data, null values, and large arrays.
- Verify Python and Java exception propagation and error messages.
- Measure startup, warm-up, steady-state execution, and boundary overhead using the real call granularity.
- Test repeated calls, context reuse, concurrent calls, callbacks, cancellation, and timeouts.
- Check filesystem, network, thread, subprocess, and native permissions explicitly.
- Build and run the final JAR, container, or native artifact rather than testing only an IDE configuration.
- Profile both JVM heap and native memory.
- Define whether a failed Python operation should fail the Java process, restart a worker, or move to a separate service.
Does using Python in Java require a paid product?
No mandatory paid bridge is required for the basic integration methods described here. GraalPy is documented as available under the GraalVM Free Terms and Conditions for commercial and production use, and its Java artifacts are available through Maven Central. Py4J and JPype are open-source projects with no paid plan required for the bridge itself. See the GraalPy licensing documentation, the GraalPy Maven artifact page, and the Py4J project documentation.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesThe commercial choices are usually adjacent infrastructure rather than a required integration license: managed containers, Kubernetes, cloud compute, observability, or enterprise support for a separately deployed Python service. Those services become relevant only if the selected architecture needs them; they are not prerequisites for embedding a compatible Python package in Java.
Frequently Asked Questions
Can Java directly import a Python package?
Java cannot import an arbitrary Python package as if it were a Java class. Java must embed a Python runtime such as GraalPy, connect to Python through a bridge such as Py4J, call a separate Python process or service, or replace the package with a Java implementation.
Is GraalPy compatible with every pip package?
No. Pure-Python packages are generally easier to use, but packages that rely on CPython internals, native extensions, binary wheels, system libraries, multiprocessing, or specific filesystem behavior may require changes or may not work. Test the exact package operation under the target GraalPy release and operating system.
Should a Java application use Py4J or GraalPy?
Use GraalPy when Java should host Python 3 in the same process and the required packages are compatible. Use Py4J when a standard CPython environment, an existing Python-led application, or process separation is more important than in-process execution.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Can GraalPy Python code call Java classes?
Yes. GraalPy supports Java interoperability, including access patterns such as java.type("java.math.BigInteger") and imports from Java namespaces. Host access should be restricted when Python code is not fully trusted.
The Bottom Line
Bottom line: For a new Java-hosted integration, test GraalPy first with the exact Python package and deployment platform. Choose a separate CPython service or process when native-package compatibility, independent scaling, or failure isolation is more important than in-process calls; reserve Py4J, JPype, and Jython for the directions and legacy situations they are designed to serve.

