|
40 | 40 | */
|
41 | 41 | package com.oracle.graal.python.util;
|
42 | 42 |
|
| 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 | + |
43 | 54 | import com.oracle.truffle.api.CompilerDirectives;
|
44 | 55 | import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
|
45 | 56 |
|
@@ -78,4 +89,42 @@ public static int multiplyExact(int x, int y) throws OverflowException {
|
78 | 89 | }
|
79 | 90 | return (int) r;
|
80 | 91 | }
|
| 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 | + } |
81 | 130 | }
|
0 commit comments