下面列出了javax.management.MBeanServerPermission#sun.management.ManagementFactoryHelper 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static String executeDcmd(String cmd, String ... args) {
DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
Object[] dcmdArgs = {args};
String[] signature = {String[].class.getName()};
String cmdString = cmd + " " +
Arrays.stream(args).collect(Collectors.joining(" "));
File f = new File("dcmdoutput-" + cmd + "-" + System.currentTimeMillis() + ".txt");
System.out.println("Output from Dcmd '" + cmdString + "' is being written to file " + f);
try (FileWriter fw = new FileWriter(f)) {
fw.write("> " + cmdString + ":");
String result = (String) dcmd.invoke(cmd, dcmdArgs, signature);
fw.write(result);
return result;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String executeDcmd(String cmd, String ... args) {
DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
Object[] dcmdArgs = {args};
String[] signature = {String[].class.getName()};
try {
System.out.print("> " + cmd + " ");
for (String s : args) {
System.out.print(s + " ");
}
System.out.println(":");
String result = (String) dcmd.invoke(transform(cmd), dcmdArgs, signature);
System.out.println(result);
return result;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
private static String executeDcmd(String cmd, String ... args) {
DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
Object[] dcmdArgs = {args};
String[] signature = {String[].class.getName()};
String cmdString = cmd + " " +
Arrays.stream(args).collect(Collectors.joining(" "));
File f = new File("dcmdoutput-" + cmd + "-" + System.currentTimeMillis() + ".txt");
System.out.println("Output from Dcmd '" + cmdString + "' is being written to file " + f);
try (FileWriter fw = new FileWriter(f)) {
fw.write("> " + cmdString + ":");
String result = (String) dcmd.invoke(cmd, dcmdArgs, signature);
fw.write(result);
return result;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String executeDcmd(String cmd, String ... args) {
DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
Object[] dcmdArgs = {args};
String[] signature = {String[].class.getName()};
try {
System.out.print("> " + cmd + " ");
for (String s : args) {
System.out.print(s + " ");
}
System.out.println(":");
String result = (String) dcmd.invoke(transform(cmd), dcmdArgs, signature);
System.out.println(result);
return result;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
private static String executeDcmd(String cmd, String ... args) {
DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
Object[] dcmdArgs = {args};
String[] signature = {String[].class.getName()};
String cmdString = cmd + " " +
Arrays.stream(args).collect(Collectors.joining(" "));
File f = new File("dcmdoutput-" + cmd + "-" + System.currentTimeMillis() + ".txt");
System.out.println("Output from Dcmd '" + cmdString + "' is being written to file " + f);
try (FileWriter fw = new FileWriter(f)) {
fw.write("> " + cmdString + ":");
String result = (String) dcmd.invoke(cmd, dcmdArgs, signature);
fw.write(result);
return result;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
private static String executeDcmd(String cmd, String ... args) {
DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
Object[] dcmdArgs = {args};
String[] signature = {String[].class.getName()};
String cmdString = cmd + " " +
Arrays.stream(args).collect(Collectors.joining(" "));
File f = new File("dcmdoutput-" + cmd + "-" + System.currentTimeMillis() + ".txt");
System.out.println("Output from Dcmd '" + cmdString + "' is being written to file " + f);
try (FileWriter fw = new FileWriter(f)) {
fw.write("> " + cmdString + ":");
String result = (String) dcmd.invoke(cmd, dcmdArgs, signature);
fw.write(result);
return result;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
private final void test() {
System.gc();
MemoryUsagePrinter.printMemoryUsage("init");
allocate();
MemoryUsagePrinter.printMemoryUsage("allocated");
MemoryUsage muFull = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
free();
MemoryUsagePrinter.printMemoryUsage("free");
MemoryUsage muFree = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
assertLessThan(muFree.getCommitted(), muFull.getCommitted(), String.format(
"committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
+ "%s = %s%n%s = %s",
MIN_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
MAX_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
));
}
private final void test() {
System.gc();
MemoryUsagePrinter.printMemoryUsage("init");
allocate();
MemoryUsagePrinter.printMemoryUsage("allocated");
MemoryUsage muFull = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
free();
MemoryUsagePrinter.printMemoryUsage("free");
MemoryUsage muFree = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
assertLessThan(muFree.getCommitted(), muFull.getCommitted(), String.format(
"committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
+ "%s = %s%n%s = %s",
MIN_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
MAX_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
));
}
/**
* Template method for testing. Prints tested method's info before
* {@linkplain #test()} and after {@linkplain #test()} or on thrown
* exception.
*
* @throws RuntimeException if method {@linkplain #test()} throws any
* exception
* @see #test()
*/
protected final void runTest() {
if (ManagementFactoryHelper.getCompilationMXBean() == null) {
System.err.println(
"Warning: test is not applicable in interpreted mode");
return;
}
System.out.println("at test's start:");
printInfo();
try {
test();
} catch (Exception e) {
System.out.printf("on exception '%s':", e.getMessage());
printInfo();
e.printStackTrace();
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
System.out.println("at test's end:");
printInfo();
}
private static String executeDcmd(String cmd, String ... args) {
DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
Object[] dcmdArgs = {args};
String[] signature = {String[].class.getName()};
String cmdString = cmd + " " +
Arrays.stream(args).collect(Collectors.joining(" "));
File f = new File("dcmdoutput-" + cmd + "-" + System.currentTimeMillis() + ".txt");
System.out.println("Output from Dcmd '" + cmdString + "' is being written to file " + f);
try (FileWriter fw = new FileWriter(f)) {
fw.write("> " + cmdString + ":");
String result = (String) dcmd.invoke(cmd, dcmdArgs, signature);
fw.write(result);
return result;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
private static String executeDcmd(String cmd, String ... args) {
DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
Object[] dcmdArgs = {args};
String[] signature = {String[].class.getName()};
String cmdString = cmd + " " +
Arrays.stream(args).collect(Collectors.joining(" "));
File f = new File("dcmdoutput-" + cmd + "-" + System.currentTimeMillis() + ".txt");
System.out.println("Output from Dcmd '" + cmdString + "' is being written to file " + f);
try (FileWriter fw = new FileWriter(f)) {
fw.write("> " + cmdString + ":");
String result = (String) dcmd.invoke(cmd, dcmdArgs, signature);
fw.write(result);
return result;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
private static String executeDcmd(String cmd, String ... args) {
DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
Object[] dcmdArgs = {args};
String[] signature = {String[].class.getName()};
try {
System.out.print("> " + cmd + " ");
for (String s : args) {
System.out.print(s + " ");
}
System.out.println(":");
String result = (String) dcmd.invoke(cmd, dcmdArgs, signature);
System.out.println(result);
return result;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Returns value of VM option.
*
* @param name option's name
* @return value of option or {@code null}, if option doesn't exist
* @throws NullPointerException if name is null
*/
public static String getVMOption(String name) {
String result;
HotSpotDiagnosticMXBean diagnostic
= ManagementFactoryHelper.getDiagnosticMXBean();
result = diagnostic.getVMOption(name).getValue();
return result;
}
/**
* Returns value of VM option.
*
* @param name option's name
* @return value of option or {@code null}, if option doesn't exist
* @throws NullPointerException if name is null
*/
protected static String getVMOption(String name) {
Objects.requireNonNull(name);
HotSpotDiagnosticMXBean diagnostic
= ManagementFactoryHelper.getDiagnosticMXBean();
VMOption tmp;
try {
tmp = diagnostic.getVMOption(name);
} catch (IllegalArgumentException e) {
tmp = null;
}
return (tmp == null ? null : tmp.getValue());
}
private String prepareMessageCommittedIsNotLess() {
return String.format(
"committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
+ "%s = %s%n%s = %s",
MIN_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
MAX_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
);
}
public static void main(String[] args) {
HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
VMOption option = diagnostic.getVMOption("UseG1GC");
if (option.getValue().equals("false")) {
System.out.println("Skipping this test. It is only a G1 test.");
return;
}
String expectedValue = getExpectedValue(args);
option = diagnostic.getVMOption("G1HeapRegionSize");
if (!expectedValue.equals(option.getValue())) {
throw new RuntimeException("Wrong value for G1HeapRegionSize. Expected " + expectedValue + " but got " + option.getValue());
}
}
static synchronized DiagnosticCommandMBean getDiagnosticCommandMBean() {
VMManagement jvm = ManagementFactoryHelper.getVMManagement();
// Remote Diagnostic Commands may not be supported
if (diagCommandMBean == null && jvm.isRemoteDiagnosticCommandsSupported()) {
diagCommandMBean = new DiagnosticCommandImpl(jvm);
}
return diagCommandMBean;
}
public static boolean testingG1GC() {
HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
VMOption option = diagnostic.getVMOption("UseG1GC");
if (option.getValue().equals("false")) {
System.out.println("Skipping this test. It is only a G1 test.");
return false;
}
return true;
}
private String prepareMessageCommittedIsNotLess() {
return String.format(
"committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
+ "%s = %s%n%s = %s",
MIN_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
MAX_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
);
}
public static boolean testingG1GC() {
HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
VMOption option = diagnostic.getVMOption("UseG1GC");
if (option.getValue().equals("false")) {
System.out.println("Skipping this test. It is only a G1 test.");
return false;
}
return true;
}
public static void main(String[] args) throws Exception {
HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
System.out.println("Max memory= " + MAX_MEMORY + " bytes");
int obj_size = 0;
long seconds_to_run = 0;
if (args.length != 2) {
throw new RuntimeException("Object size argument must be supplied");
} else {
obj_size = Integer.parseInt(args[0]);
seconds_to_run = Integer.parseInt(args[1]);
}
System.out.println("Objects size= " + obj_size + " bytes");
System.out.println("Seconds to run=" + seconds_to_run);
int region_size =
Integer.parseInt(diagnostic.getVMOption("G1HeapRegionSize").getValue());
if (obj_size < (region_size / 2)) {
throw new RuntimeException("Object size " + obj_size +
" is not humongous with region size " + region_size);
}
ExecutorService executor =
Executors.newFixedThreadPool(THREAD_COUNT, new NamedThreadFactory());
System.out.println("Starting " + THREAD_COUNT + " threads");
for (int i = 0; i < THREAD_COUNT; i++) {
executor.execute(new Runner(obj_size));
}
Thread.sleep(seconds_to_run * 1000);
executor.shutdownNow();
if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
System.err.println("Thread pool did not terminate after 10 seconds after shutdown");
}
}
private String prepareMessageCommittedIsNotLess() {
return String.format(
"committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
+ "%s = %s%n%s = %s",
MIN_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
MAX_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
);
}
public static boolean testingG1GC() {
HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
VMOption option = diagnostic.getVMOption("UseG1GC");
if (option.getValue().equals("false")) {
System.out.println("Skipping this test. It is only a G1 test.");
return false;
}
return true;
}
public static void main(String[] args) {
HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
String expectedValue = getExpectedValue(args);
VMOption option = diagnostic.getVMOption("G1HeapRegionSize");
if (!expectedValue.equals(option.getValue())) {
throw new RuntimeException("Wrong value for G1HeapRegionSize. Expected " + expectedValue + " but got " + option.getValue());
}
}
public static void main(String[] args) {
HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
String expectedValue = getExpectedValue(args);
VMOption option = diagnostic.getVMOption("UseG1GC");
if (option.getValue().equals("false")) {
System.out.println("Skipping this test. It is only a G1 test.");
return;
}
option = diagnostic.getVMOption("G1HeapRegionSize");
if (!expectedValue.equals(option.getValue())) {
throw new RuntimeException("Wrong value for G1HeapRegionSize. Expected " + expectedValue + " but got " + option.getValue());
}
}
private void doMethodInBacktraceTestB() throws Exception {
// Start a thread which blocks in method
Thread t = new Thread(RedefineMethodInBacktraceTargetB::methodToRedefine);
t.setDaemon(true);
t.start();
// Wait here until the new thread is in the method we want to redefine
called.await();
// Now redefine the class while the method is still on the stack of the new thread
doRedefine(RedefineMethodInBacktraceTargetB.class);
// Do thread dumps in two different ways (to exercise different code paths)
// while the old class is still on the stack
ThreadInfo[] tis = ManagementFactory.getThreadMXBean().dumpAllThreads(false, false);
for(ThreadInfo ti : tis) {
System.out.println(ti);
}
String[] threadPrintArgs = {};
Object[] dcmdArgs = {threadPrintArgs};
String[] signature = {String[].class.getName()};
DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
System.out.println(dcmd.invoke("threadPrint", dcmdArgs, signature));
// release the thread
stop.countDown();
}
private static long getCompressedClassSpaceSize() {
HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
VMOption option = diagnostic.getVMOption("CompressedClassSpaceSize");
return Long.parseLong(option.getValue());
}
/**
* Entry point. Compiles classes in {@code args}, or all classes in
* boot-classpath if args is empty
*
* @param args paths to jar/zip, dir contains classes, or to .lst file
* contains list of classes to compile
*/
public static void main(String[] args) {
String logfile = Utils.LOG_FILE;
PrintStream os = null;
if (logfile != null) {
try {
os = new PrintStream(Files.newOutputStream(Paths.get(logfile)));
} catch (IOException io) {
}
}
if (os != null) {
System.setOut(os);
}
try {
try {
if (ManagementFactoryHelper.getCompilationMXBean() == null) {
throw new RuntimeException(
"CTW can not work in interpreted mode");
}
} catch (java.lang.NoClassDefFoundError e) {
// compact1, compact2 support
}
String[] paths = args;
boolean skipRtJar = false;
if (args.length == 0) {
paths = getDefaultPaths();
skipRtJar = true;
}
ExecutorService executor = createExecutor();
long start = System.currentTimeMillis();
try {
String path;
for (int i = 0, n = paths.length; i < n
&& !PathHandler.isFinished(); ++i) {
path = paths[i];
if (skipRtJar && i > 0 && isRtJar(path)) {
// rt.jar is not first, so skip it
continue;
}
PathHandler.create(path, executor).process();
}
} finally {
await(executor);
}
System.out.printf("Done (%d classes, %d methods, %d ms)%n",
Compiler.getClassCount(),
Compiler.getMethodCount(),
System.currentTimeMillis() - start);
} finally {
if (os != null) {
os.close();
}
}
}
/**
* Initialize ThreadInfo object
*
* @param t Thread
* @param state Thread state
* @param lockObj Object on which the thread is blocked
* @param lockOwner the thread holding the lock
* @param blockedCount Number of times blocked to enter a lock
* @param blockedTime Approx time blocked to enter a lock
* @param waitedCount Number of times waited on a lock
* @param waitedTime Approx time waited on a lock
* @param stackTrace Thread stack trace
* @param lockedMonitors List of locked monitors
* @param lockedSynchronizers List of locked synchronizers
*/
private void initialize(Thread t, int state, Object lockObj, Thread lockOwner,
long blockedCount, long blockedTime,
long waitedCount, long waitedTime,
StackTraceElement[] stackTrace,
MonitorInfo[] lockedMonitors,
LockInfo[] lockedSynchronizers) {
this.threadId = t.getId();
this.threadName = t.getName();
this.threadState = ManagementFactoryHelper.toThreadState(state);
this.suspended = ManagementFactoryHelper.isThreadSuspended(state);
this.inNative = ManagementFactoryHelper.isThreadRunningNative(state);
this.blockedCount = blockedCount;
this.blockedTime = blockedTime;
this.waitedCount = waitedCount;
this.waitedTime = waitedTime;
if (lockObj == null) {
this.lock = null;
this.lockName = null;
} else {
this.lock = new LockInfo(lockObj);
this.lockName =
lock.getClassName() + '@' +
Integer.toHexString(lock.getIdentityHashCode());
}
if (lockOwner == null) {
this.lockOwnerId = -1;
this.lockOwnerName = null;
} else {
this.lockOwnerId = lockOwner.getId();
this.lockOwnerName = lockOwner.getName();
}
if (stackTrace == null) {
this.stackTrace = NO_STACK_TRACE;
} else {
this.stackTrace = stackTrace;
}
this.lockedMonitors = lockedMonitors;
this.lockedSynchronizers = lockedSynchronizers;
}
private static long getCompressedClassSpaceSize() {
HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
VMOption option = diagnostic.getVMOption("CompressedClassSpaceSize");
return Long.parseLong(option.getValue());
}