Skip to content

Commit 9aa2a59

Browse files
committed
Add shortcuts for JVM config
Including: 1. heap allocation and limits 2. headless mode 3. interprocess debugging with JDWP
1 parent d1cb1d1 commit 9aa2a59

1 file changed

Lines changed: 69 additions & 0 deletions

File tree

src/scyjava/config.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,75 @@ def get_classpath():
166166
return jpype.getClassPath()
167167

168168

169+
def set_heap_min(mb: int = None, gb: int = None):
170+
"""
171+
Set the initial amount of memory to allocate to the Java heap.
172+
173+
Either mb or gb, but not both, must be given.
174+
175+
Shortcut for passing -Xms###m or -Xms###g to Java.
176+
177+
:param mb:
178+
The ### of megabytes of memory Java should start with.
179+
:param gb:
180+
The ### of gigabytes of memory Java should start with.
181+
:raise ValueError: If exactly one of mb or gb is not given.
182+
"""
183+
add_option(f"-Xms{_mem_value(mb, gb)}")
184+
185+
186+
def set_heap_max(mb: int = None, gb: int = None):
187+
"""
188+
Shortcut for passing -Xmx###m or -Xmx###g to Java.
189+
190+
Either mb or gb, but not both, must be given.
191+
192+
:param mb:
193+
The maximum ### of megabytes of memory Java is allowed to use.
194+
:param gb:
195+
The maximum ### of gigabytes of memory Java is allowed to use.
196+
:raise ValueError: If exactly one of mb or gb is not given.
197+
"""
198+
add_option(f"-Xmx{_mem_value(mb, gb)}")
199+
200+
201+
def _mem_value(mb: int = None, gb: int = None) -> str:
202+
# fmt: off
203+
if mb is not None and gb is None: return f"{mb}m" # noqa: E701
204+
if gb is not None and mb is None: return f"{gb}g" # noqa: E701
205+
# fmt: on
206+
raise ValueError("Exactly one of mb or gb must be given.")
207+
208+
209+
def enable_headless_mode():
210+
"""
211+
Enable headless mode, for running Java without a display.
212+
This mode prevents any graphical elements from popping up.
213+
Shortcut for passing -Djava.awt.headless=true to Java.
214+
"""
215+
add_option("-Djava.awt.headless=true")
216+
217+
218+
def enable_remote_debugging(port: int = 8000, suspend: bool = False):
219+
"""
220+
Enable the JDWP debugger, listening on the given port of localhost.
221+
Shortcut for -agentlib:jdwp=transport=dt_socket,address=localhost:<port>.
222+
223+
:param port:
224+
The port to listen on for client debuggers (e.g. IDEs).
225+
:param suspend:
226+
If True, pause when starting up the JVM until a client debugger connects.
227+
"""
228+
jdwp_args = {
229+
"transport": "dt_socket",
230+
"server": "y",
231+
"suspend": "y" if suspend else "n",
232+
"address": f"localhost:{port}",
233+
}
234+
arg_string = ",".join(f"{k}={v}" for k, v in jdwp_args.items())
235+
add_option(f"-agentlib:jdwp={arg_string}")
236+
237+
169238
def add_option(option):
170239
global _options
171240
_options.append(option)

0 commit comments

Comments
 (0)