Skip to content

Commit 65b7cd2

Browse files
committed
Introduce PythonUtils.forceFullGC (written by tfel).
1 parent 7e0c7c4 commit 65b7cd2

File tree

1 file changed

+49
-0
lines changed
  • graalpython/com.oracle.graal.python/src/com/oracle/graal/python/util

1 file changed

+49
-0
lines changed

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/util/PythonUtils.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,17 @@
4040
*/
4141
package com.oracle.graal.python.util;
4242

43+
import java.lang.management.ManagementFactory;
44+
45+
import javax.management.InstanceNotFoundException;
46+
import javax.management.MBeanException;
47+
import javax.management.MBeanServer;
48+
import javax.management.MalformedObjectNameException;
49+
import javax.management.ObjectName;
50+
import javax.management.ReflectionException;
51+
52+
import org.graalvm.nativeimage.ImageInfo;
53+
4354
import com.oracle.truffle.api.CompilerDirectives;
4455
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
4556

@@ -78,4 +89,42 @@ public static int multiplyExact(int x, int y) throws OverflowException {
7889
}
7990
return (int) r;
8091
}
92+
93+
private static final MBeanServer SERVER;
94+
private static final String OPERATION_NAME = "gcRun";
95+
private static final Object[] PARAMS = new Object[]{null};
96+
private static final String[] SIGNATURE = new String[]{String[].class.getName()};
97+
private static final ObjectName OBJECT_NAME;
98+
99+
static {
100+
if (ImageInfo.inImageCode()) {
101+
OBJECT_NAME = null;
102+
SERVER = null;
103+
} else {
104+
SERVER = ManagementFactory.getPlatformMBeanServer();
105+
ObjectName n;
106+
try {
107+
n = new ObjectName("com.sun.management:type=DiagnosticCommand");
108+
} catch (final MalformedObjectNameException e) {
109+
n = null;
110+
}
111+
OBJECT_NAME = n;
112+
}
113+
}
114+
115+
/**
116+
* {@link System#gc()} does not force a GC, but the DiagnosticCommand "gcRun" does.
117+
*/
118+
@TruffleBoundary
119+
public static void forceFullGC() {
120+
if (OBJECT_NAME != null && SERVER != null) {
121+
try {
122+
SERVER.invoke(OBJECT_NAME, OPERATION_NAME, PARAMS, SIGNATURE);
123+
} catch (InstanceNotFoundException | ReflectionException | MBeanException e) {
124+
// use fallback
125+
}
126+
}
127+
System.gc();
128+
Runtime.getRuntime().freeMemory();
129+
}
81130
}

0 commit comments

Comments
 (0)