Package jep
Class MainInterpreter
java.lang.Object
jep.MainInterpreter
- All Implemented Interfaces:
AutoCloseable
The main Python interpreter that all sub-interpreters will be created from.
In a simpler embedded Python project, a single Python interpreter would be
used and all would be good. However, since Jep supports multithreading with
multiple sub-interpreters, we need the MainInterpreter to work around some
issues.
The MainInterpreter is used to avoid potential deadlocks. Python can deadlock
when trying to acquire the GIL through methods such as PyGILState_*.
While Jep does not use those methods, CPython extensions such as numpy do.
The deadlock can occur if there is more than one PyThreadState per thread. To
get around this, the MainInterpreter creates a unique thread that initializes
Python and keeps this thread around forever. This ensures that any new
sub-interpreters cannot be created on the same thread as the main Python
interpreter.
The MainInterpreter is also used to support shared modules. While each
sub-interpreter is fairly sandboxed, in practice this does not always work
well with CPython extensions. In particular, disposing of a sub-interpreter
that has imported a CPython extension may cause some of the CPython
extension's objects to be garbage collected. To get around this, shared
modules import on the main interpreter's thread so they can be shared amongst
sub-interpreters and will never be garbage collected.
For more information about why the MainInterpreter class exists, see Sub-interpreter
bugs and caveats.
- Since:
- 3.8
-
Method Summary
Modifier and TypeMethodDescriptionvoid
close()
Stop the interpreter thread.static void
setInitParams
(PyConfig config) Sets interpreter settings for the main Python interpreter.static void
setJepLibraryPath
(String path) Sets the path of the jep native library.static void
setSharedModulesArgv
(String... argv) Sets the sys.argv values on the main interpreter.void
sharedImport
(String module) Import a module into the main interpreter on the correct thread for that interpreter.
-
Method Details
-
close
public void close()Stop the interpreter thread.- Specified by:
close
in interfaceAutoCloseable
-
setInitParams
Sets interpreter settings for the main Python interpreter. This method must be called before the first Interpreter instance is created in the process.- Parameters:
config
- the python configuration to use.- Throws:
JepException
- if an error occurs- Since:
- 3.6
-
setJepLibraryPath
Sets the path of the jep native library. The location should be a path that can be passed toSystem.load(String)
. This method must be called before the first Interpreter instance is created in the process.- Parameters:
path
- the path of the jep native library, an absolute path leading to a file that is often named libjep.so or libjep.dll.- Throws:
JepException
- if an error occurs- Since:
- 3.9