Skip to content

Instantly share code, notes, and snippets.

@rednaxelafx
Created November 21, 2011 07:45
Show Gist options
  • Save rednaxelafx/1381950 to your computer and use it in GitHub Desktop.
Save rednaxelafx/1381950 to your computer and use it in GitHub Desktop.
HotSpot VM utils
public class GCUtils {
private static final String DISABLE_EXPLICIT_GC = "DisableExplicitGC"; // need to be "manageable" in VM
public static void forceGC() {
String oldValue = HotSpotUtils.getVMOption(DISABLE_EXPLICIT_GC);
if ("true".equals(oldValue)) {
HotSpotUtils.setVMOption(DISABLE_EXPLICIT_GC, "false");
System.gc();
HotSpotUtils.setVMOption(DISABLE_EXPLICIT_GC, oldValue);
} else {
System.gc();
}
}
}
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import com.sun.management.HotSpotDiagnosticMXBean;
// import com.sun.management.VMOption;
public class HotSpotUtils {
public static String getVMOption(String name) {
return SingletonHolder.HOTSPOT_BEAN.getVMOption(name).getValue(); // could throw exception
}
public static void setVMOption(String name, String value) {
SingletonHolder.HOTSPOT_BEAN.setVMOption(name, value);
}
private static class SingletonHolder {
static final HotSpotDiagnosticMXBean HOTSPOT_BEAN = populateHotSpotBean();
private static final String HOTSPOT_BEAN_NAME = "com.sun.management:type=HotSpotDiagnostic";
private static final HotSpotDiagnosticMXBean populateHotSpotBean() {
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean bean = ManagementFactory.newPlatformMXBeanProxy(
server, HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class);
return bean;
} catch (java.io.IOException e) {
throw new InternalError("should run on a HotSpot VM");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment