0
# JVM Lifecycle Management
1
2
Core functionality for starting, configuring, and managing the Java Virtual Machine from within Python applications. This module provides complete control over JVM lifecycle, configuration, and discovery.
3
4
## Capabilities
5
6
### JVM Startup and Shutdown
7
8
Start and stop the Java Virtual Machine with custom configuration options.
9
10
```python { .api }
11
def startJVM(*jvmargs: str, jvmpath=None, classpath=None, ignoreUnrecognized=False, convertStrings=False, interrupt=True):
12
"""Start the Java Virtual Machine.
13
14
Args:
15
*jvmargs: JVM arguments like "-Xmx1g", "-Djava.awt.headless=true"
16
jvmpath: Path to JVM library file (libjvm.so, jvm.dll, etc.)
17
classpath: String path or list of paths to set classpath
18
ignoreUnrecognized: Ignore invalid JVM arguments (default False)
19
convertStrings: Force Java strings to convert to Python str (default False)
20
interrupt: Enable interrupt handling (default True)
21
22
Raises:
23
OSError: If JVM cannot be started
24
RuntimeError: If JVM is already running
25
"""
26
27
def shutdownJVM():
28
"""Shutdown the running JVM.
29
30
Raises:
31
RuntimeError: If JVM is not running
32
"""
33
34
def isJVMStarted() -> bool:
35
"""Check if JVM is currently running.
36
37
Returns:
38
bool: True if JVM is started, False otherwise
39
"""
40
```
41
42
### JVM Configuration and Discovery
43
44
Discover and configure JVM installations and retrieve runtime information.
45
46
```python { .api }
47
def getDefaultJVMPath() -> str:
48
"""Find the default JVM library path on the system.
49
50
Returns:
51
str: Path to the default JVM library
52
53
Raises:
54
JVMNotFoundException: If no JVM is found
55
"""
56
57
def get_default_jvm_path() -> str:
58
"""Alternative name for getDefaultJVMPath().
59
60
Returns:
61
str: Path to the default JVM library
62
"""
63
64
def getJVMVersion() -> tuple:
65
"""Get the version of the running JVM.
66
67
Returns:
68
tuple: JVM version as (major, minor, patch)
69
70
Raises:
71
RuntimeError: If JVM is not running
72
"""
73
```
74
75
### Threading Support (Deprecated)
76
77
Legacy threading functions for manual thread management. Modern JPype automatically manages thread attachment.
78
79
```python { .api }
80
def isThreadAttachedToJVM() -> bool:
81
"""Check if current thread is attached to JVM.
82
83
Returns:
84
bool: True if thread is attached
85
86
Note:
87
Deprecated: JPype automatically manages thread attachment
88
"""
89
90
def attachThreadToJVM():
91
"""Manually attach current thread to JVM.
92
93
Note:
94
Deprecated: JPype automatically manages thread attachment
95
"""
96
97
def detachThreadFromJVM():
98
"""Detach current thread from JVM.
99
100
Note:
101
Deprecated: JPype automatically manages thread attachment
102
"""
103
```
104
105
### Initialization Control
106
107
Control JVM initialization timing and register startup callbacks.
108
109
```python { .api }
110
def onJVMStart(func):
111
"""Decorator to register function to be called after JVM starts.
112
113
Args:
114
func: Function to call when JVM starts
115
116
Returns:
117
func: The original function (for use as decorator)
118
119
Example:
120
@onJVMStart
121
def load_resources():
122
# Load Java classes or resources
123
pass
124
"""
125
```
126
127
### Exception Classes
128
129
Exceptions raised during JVM operations.
130
131
```python { .api }
132
class JVMNotFoundException(RuntimeError):
133
"""Raised when JVM installation cannot be found."""
134
135
class JVMNotSupportedException(RuntimeError):
136
"""Raised when JVM version is not supported."""
137
138
class JVMNotRunning(RuntimeError):
139
"""Raised when JVM operations attempted while not running."""
140
```
141
142
## Usage Examples
143
144
### Basic JVM Lifecycle
145
146
```python
147
import jpype
148
149
# Start JVM with default settings
150
jpype.startJVM()
151
152
# Check if running
153
if jpype.isJVMStarted():
154
print("JVM is running")
155
156
# Get JVM version
157
version = jpype.getJVMVersion()
158
print(f"JVM version: {version}")
159
160
# Shutdown when done
161
jpype.shutdownJVM()
162
```
163
164
### JVM with Custom Configuration
165
166
```python
167
import jpype
168
169
# Start with custom memory and system properties
170
jpype.startJVM(
171
jpype.getDefaultJVMPath(),
172
"-Xmx2g", # Set max heap to 2GB
173
"-Xms512m", # Set initial heap to 512MB
174
"-Djava.awt.headless=true", # Headless mode
175
classpath=["lib/mylib.jar", "classes/"],
176
convertStrings=False # Keep Java strings as JString objects
177
)
178
179
# Your Java integration code here
180
java = jpype.java
181
String = java.lang.String("Hello Java!")
182
183
jpype.shutdownJVM()
184
```
185
186
### Initialization Callbacks
187
188
```python
189
import jpype
190
191
@jpype.onJVMStart
192
def initialize_resources():
193
"""Load resources after JVM starts."""
194
# Load Java classes that depend on JVM
195
MyClass = jpype.JClass("com.example.MyClass")
196
MyClass.initializeStaticResources()
197
198
# Start JVM - callback will be executed automatically
199
jpype.startJVM()
200
jpype.shutdownJVM()
201
```
202
203
### JVM Discovery
204
205
```python
206
import jpype
207
208
try:
209
jvm_path = jpype.getDefaultJVMPath()
210
print(f"Found JVM at: {jvm_path}")
211
jpype.startJVM(jvm_path)
212
except jpype.JVMNotFoundException:
213
print("No JVM found on system")
214
except jpype.JVMNotSupportedException:
215
print("JVM version not supported")
216
```