Java Code Examples for java.lang.management.ManagementFactory.getPlatformMXBean()

The following are Jave code examples for showing how to use getPlatformMXBean() of the java.lang.management.ManagementFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: redpipe   File: MetricsVerticle.java   View Source Code Vote up 6 votes
@Override
public void start() throws Exception {
  systemMBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);

  // A random identifier
  String pid = UUID.randomUUID().toString();

  // Get the kafka producer config
  JsonObject config = config();

  // Create the producer
  producer = KafkaWriteStream.create(vertx.getDelegate(), config.getMap(), String.class, JsonObject.class);

  // Publish the metircs in Kafka
  vertx.setPeriodic(1000, id -> {
    JsonObject metrics = new JsonObject();
    metrics.put("CPU", systemMBean.getProcessCpuLoad());
    metrics.put("Mem", systemMBean.getTotalPhysicalMemorySize() - systemMBean.getFreePhysicalMemorySize());
    producer.write(new ProducerRecord<>("the_topic", new JsonObject().put(pid, metrics)));
  });
}
 
Example 2
Project: MinecraftMarket-Plugin   File: MCMarketStats.java   View Source Code Vote up 6 votes
Map<String, Object> getSystemStats() {
    Map<String, Object> stats = new HashMap<>();
    OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
    double cpuUsage = osBean.getProcessCpuLoad() < 0 ? 0 : osBean.getProcessCpuLoad() * 100.0;

    stats.put("javaVersion", System.getProperty("java.version"));
    stats.put("osName", System.getProperty("os.name"));
    stats.put("osArch", System.getProperty("os.arch"));
    stats.put("osVersion", System.getProperty("os.version"));
    stats.put("maxMemory", Runtime.getRuntime().maxMemory());
    stats.put("totalMemory", Runtime.getRuntime().totalMemory());
    stats.put("freeMemory", Runtime.getRuntime().freeMemory());
    stats.put("cores", Long.parseLong(String.valueOf(Runtime.getRuntime().availableProcessors()))); // Is this really necessary?
    stats.put("cpuUsage", Math.min(round(cpuUsage), 100.0));

    return stats;
}
 
Example 3
Project: jdk8u-jdk   File: PlatformLoggingMXBeanTest.java   View Source Code Vote up 6 votes
public static void main(String[] argv) throws Exception {
    PlatformLoggingMXBean mbean =
        ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class);
    ObjectName objname = mbean.getObjectName();
    if (!objname.equals(new ObjectName(LogManager.LOGGING_MXBEAN_NAME))) {
        throw new RuntimeException("Invalid ObjectName " + objname);
    }

    // check if the PlatformLoggingMXBean is registered in the platform MBeanServer
    MBeanServer platformMBS = ManagementFactory.getPlatformMBeanServer();
    ObjectName objName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME);

    // We could call mbs.isRegistered(objName) here.
    // Calling getMBeanInfo will throw exception if not found.
    platformMBS.getMBeanInfo(objName);

    if (!platformMBS.isInstanceOf(objName, "java.lang.management.PlatformLoggingMXBean") ||
        !platformMBS.isInstanceOf(objName, "java.util.logging.LoggingMXBean")) {
        throw new RuntimeException(objName + " is of unexpected type");
    }

    // test if PlatformLoggingMXBean works properly in a MBeanServer
    PlatformLoggingMXBeanTest test = new PlatformLoggingMXBeanTest();
    test.runTest(mbean);
}
 
Example 4
Project: openjdk-jdk10   File: VmFlagTest.java   View Source Code Vote up 6 votes
protected String getVMOptionAsString() {
    if (WHITE_BOX.isConstantVMFlag(flagName) || WHITE_BOX.isLockedVMFlag(flagName)) {
      // JMM cannot access debug flags in product builds or locked flags,
      // use whitebox methods to get such flags value.
      return asString(getValue());
    }
    HotSpotDiagnosticMXBean diagnostic
            = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
    VMOption tmp;
    try {
        tmp = diagnostic.getVMOption(flagName);
    } catch (IllegalArgumentException e) {
        tmp = null;
    }
    return tmp == null ? null : tmp.getValue();
}
 
Example 5
Project: openjdk-jdk10   File: PlatformLoggingMXBeanTest.java   View Source Code Vote up 6 votes
public static void main(String[] argv) throws Exception {
    PlatformLoggingMXBean mbean =
        ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class);
    ObjectName objname = mbean.getObjectName();
    if (!objname.equals(new ObjectName(LogManager.LOGGING_MXBEAN_NAME))) {
        throw new RuntimeException("Invalid ObjectName " + objname);
    }

    // check if the PlatformLoggingMXBean is registered in the platform MBeanServer
    MBeanServer platformMBS = ManagementFactory.getPlatformMBeanServer();
    ObjectName objName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME);

    // We could call mbs.isRegistered(objName) here.
    // Calling getMBeanInfo will throw exception if not found.
    platformMBS.getMBeanInfo(objName);

    if (!platformMBS.isInstanceOf(objName, "java.lang.management.PlatformLoggingMXBean")) {
        throw new RuntimeException(objName + " is of unexpected type");
    }

    // test if PlatformLoggingMXBean works properly in a MBeanServer
    PlatformLoggingMXBeanTest test = new PlatformLoggingMXBeanTest();
    test.runTest(mbean);
}
 
Example 6
Project: openjdk-jdk10   File: VMOptionOpenDataTest.java   View Source Code Vote up 6 votes
public static void main(String... args) throws Exception {
    MBeanServerConnection msc = ManagementFactory.getPlatformMBeanServer();
    HotSpotDiagnosticMXBean mxbean =
        ManagementFactory.getPlatformMXBean(msc, HotSpotDiagnosticMXBean.class);


    String[] signatures = new String[] {
        String.class.getName()
    };
    Object obj = msc.invoke(mxbean.getObjectName(), "getVMOption",
        new String[] { "PrintVMOptions"}, signatures);

    CompositeData data = (CompositeData)obj;
    validateType(data);

    VMOption option = mxbean.getVMOption("PrintVMOptions");
    VMOption o = VMOption.from(data);
    assertEquals(option, o);
}
 
Example 7
Project: openjdk-jdk10   File: TestGreyReclaimedHumongousObjects.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    HotSpotDiagnosticMXBean diagnostic =
            ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);

    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");
    }
}
 
Example 8
Project: openjdk-jdk10   File: TestUseCompressedOopsErgoTools.java   View Source Code Vote up 5 votes
private static long getCompressedClassSpaceSize() {
  HotSpotDiagnosticMXBean diagnostic =
      ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);

  VMOption option = diagnostic.getVMOption("CompressedClassSpaceSize");
  return Long.parseLong(option.getValue());
}
 
Example 9
Project: openjdk-jdk10   File: Utils.java   View Source Code Vote up 5 votes
/**
 * 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
            = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
    result = diagnostic.getVMOption(name).getValue();
    return result;
}
 
Example 10
Project: jdk8u-jdk   File: SetVMOption.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
    mbean =
        ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);

    VMOption option = findPrintGCDetailsOption();
    if (!option.getValue().equalsIgnoreCase(EXPECTED_VALUE)) {
        throw new RuntimeException("Unexpected value: " +
            option.getValue() + " expected: " + EXPECTED_VALUE);
    }
    if (option.getOrigin() != Origin.VM_CREATION) {
        throw new RuntimeException("Unexpected origin: " +
            option.getOrigin() + " expected: VM_CREATION");
    }
    if (!option.isWriteable()) {
        throw new RuntimeException("Expected " + PRINT_GC_DETAILS +
            " to be writeable");
    }

    // set VM option to a new value
    mbean.setVMOption(PRINT_GC_DETAILS, NEW_VALUE);

    option = findPrintGCDetailsOption();
    if (!option.getValue().equalsIgnoreCase(NEW_VALUE)) {
        throw new RuntimeException("Unexpected value: " +
            option.getValue() + " expected: " + NEW_VALUE);
    }
    if (option.getOrigin() != Origin.MANAGEMENT) {
        throw new RuntimeException("Unexpected origin: " +
            option.getOrigin() + " expected: MANAGEMENT");
    }
    VMOption o = mbean.getVMOption(PRINT_GC_DETAILS);
    if (!option.getValue().equals(o.getValue())) {
        throw new RuntimeException("Unmatched value: " +
            option.getValue() + " expected: " + o.getValue());
    }
    if (!option.getValue().equals(o.getValue())) {
        throw new RuntimeException("Unmatched value: " +
            option.getValue() + " expected: " + o.getValue());
    }
    if (option.getOrigin() != o.getOrigin()) {
        throw new RuntimeException("Unmatched origin: " +
            option.getOrigin() + " expected: " + o.getOrigin());
    }
    if (option.isWriteable() != o.isWriteable()) {
        throw new RuntimeException("Unmatched writeable: " +
            option.isWriteable() + " expected: " + o.isWriteable());
    }

    // check if ManagementServer is not writeable
    List<VMOption> options = mbean.getDiagnosticOptions();
    VMOption mgmtServerOption = null;
    for (VMOption o1 : options) {
        if (o1.getName().equals(MANAGEMENT_SERVER)) {
             mgmtServerOption = o1;
             break;
        }
    }
    if (mgmtServerOption != null) {
        throw new RuntimeException(MANAGEMENT_SERVER +
            " is not expected to be writeable");
    }
    mgmtServerOption = mbean.getVMOption(MANAGEMENT_SERVER);
    if (mgmtServerOption == null) {
        throw new RuntimeException(MANAGEMENT_SERVER +
            " should exist.");
    }
    if (mgmtServerOption.getOrigin() != Origin.DEFAULT) {
        throw new RuntimeException(MANAGEMENT_SERVER +
            " should have the default value.");
    }
    if (mgmtServerOption.isWriteable()) {
        throw new RuntimeException(MANAGEMENT_SERVER +
            " is not expected to be writeable");
    }
}
 
Example 11
Project: openjdk-jdk10   File: CheckOrigin.java   View Source Code Vote up 4 votes
public static void main(String... args) throws Exception {
    if (args.length == 0) {
        // start a process that has options set in a number of different ways

        File flagsFile = File.createTempFile("CheckOriginFlags", null);
        try (PrintWriter pw =
               new PrintWriter(new FileWriter(flagsFile))) {
            pw.println("+PrintSafepointStatistics");
        }

        ProcessBuilder pb = ProcessTools.
            createJavaProcessBuilder(
                "--add-exports", "jdk.attach/sun.tools.attach=ALL-UNNAMED",
                "-XX:+UseConcMarkSweepGC",  // this will cause MaxNewSize to be FLAG_SET_ERGO
                "-XX:+UseCodeAging",
                "-XX:+UseCerealGC",         // Should be ignored.
                "-XX:Flags=" + flagsFile.getAbsolutePath(),
                "-Djdk.attach.allowAttachSelf",
                "-cp", System.getProperty("test.class.path"),
                "CheckOrigin",
                "-runtests");

        Map<String, String> env = pb.environment();
        // "UseCMSGC" should be ignored.
        env.put("_JAVA_OPTIONS", "-XX:+CheckJNICalls -XX:+UseCMSGC");
        // "UseGOneGC" should be ignored.
        env.put("JAVA_TOOL_OPTIONS", "-XX:+IgnoreUnrecognizedVMOptions "
            + "-XX:+PrintVMOptions -XX:+UseGOneGC");

        pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        pb.redirectError(ProcessBuilder.Redirect.INHERIT);
        Process p = pb.start();
        int exit = p.waitFor();
        System.out.println("sub process exit == " + exit);
        if (exit != 0) {
            throw new Exception("Unexpected exit code from subprocess == " + exit);
        }
    } else {
        mbean =
            ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);

        // set a few more options
        mbean.setVMOption("HeapDumpOnOutOfMemoryError", "true");
        setOptionUsingAttach("HeapDumpPath", "/a/sample/path");

        // check the origin field for all the options we set

        // Not set, so should be default
        checkOrigin("ManagementServer", Origin.DEFAULT);
        // Set on the command line
        checkOrigin("UseCodeAging", Origin.VM_CREATION);
        // Set in _JAVA_OPTIONS
        checkOrigin("CheckJNICalls", Origin.ENVIRON_VAR);
        // Set in JAVA_TOOL_OPTIONS
        checkOrigin("IgnoreUnrecognizedVMOptions", Origin.ENVIRON_VAR);
        checkOrigin("PrintVMOptions", Origin.ENVIRON_VAR);
        // Set in -XX:Flags file
        checkOrigin("PrintSafepointStatistics", Origin.CONFIG_FILE);
        // Set through j.l.m
        checkOrigin("HeapDumpOnOutOfMemoryError", Origin.MANAGEMENT);
        // Should be set by the VM, when we set UseConcMarkSweepGC
        checkOrigin("MaxNewSize", Origin.ERGONOMIC);
        // Set using attach
        checkOrigin("HeapDumpPath", Origin.ATTACH_ON_DEMAND);
    }
}
 
Example 12
Project: openjdk-jdk10   File: SetVMOption.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
    mbean =
        ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);

    VMOption option = findHeapDumpOnOomOption();
    if (!option.getValue().equalsIgnoreCase(EXPECTED_VALUE)) {
        throw new RuntimeException("Unexpected value: " +
            option.getValue() + " expected: " + EXPECTED_VALUE);
    }
    if (option.getOrigin() != Origin.VM_CREATION) {
        throw new RuntimeException("Unexpected origin: " +
            option.getOrigin() + " expected: VM_CREATION");
    }
    if (!option.isWriteable()) {
        throw new RuntimeException("Expected " + HEAP_DUMP_ON_OOM +
            " to be writeable");
    }

    // set VM option to a new value
    mbean.setVMOption(HEAP_DUMP_ON_OOM, NEW_VALUE);

    option = findHeapDumpOnOomOption();
    if (!option.getValue().equalsIgnoreCase(NEW_VALUE)) {
        throw new RuntimeException("Unexpected value: " +
            option.getValue() + " expected: " + NEW_VALUE);
    }
    if (option.getOrigin() != Origin.MANAGEMENT) {
        throw new RuntimeException("Unexpected origin: " +
            option.getOrigin() + " expected: MANAGEMENT");
    }
    VMOption o = mbean.getVMOption(HEAP_DUMP_ON_OOM);
    if (!option.getValue().equals(o.getValue())) {
        throw new RuntimeException("Unmatched value: " +
            option.getValue() + " expected: " + o.getValue());
    }
    if (!option.getValue().equals(o.getValue())) {
        throw new RuntimeException("Unmatched value: " +
            option.getValue() + " expected: " + o.getValue());
    }
    if (option.getOrigin() != o.getOrigin()) {
        throw new RuntimeException("Unmatched origin: " +
            option.getOrigin() + " expected: " + o.getOrigin());
    }
    if (option.isWriteable() != o.isWriteable()) {
        throw new RuntimeException("Unmatched writeable: " +
            option.isWriteable() + " expected: " + o.isWriteable());
    }

    // check if ManagementServer is not writeable
    List<VMOption> options = mbean.getDiagnosticOptions();
    VMOption mgmtServerOption = null;
    for (VMOption o1 : options) {
        if (o1.getName().equals(MANAGEMENT_SERVER)) {
             mgmtServerOption = o1;
             break;
        }
    }
    if (mgmtServerOption != null) {
        throw new RuntimeException(MANAGEMENT_SERVER +
            " is not expected to be writeable");
    }
    mgmtServerOption = mbean.getVMOption(MANAGEMENT_SERVER);
    if (mgmtServerOption == null) {
        throw new RuntimeException(MANAGEMENT_SERVER +
            " should exist.");
    }
    if (mgmtServerOption.getOrigin() != Origin.DEFAULT) {
        throw new RuntimeException(MANAGEMENT_SERVER +
            " should have the default value.");
    }
    if (mgmtServerOption.isWriteable()) {
        throw new RuntimeException(MANAGEMENT_SERVER +
            " is not expected to be writeable");
    }
}
 
Example 13
Project: java-memory-assistant   File: HeapDumpCreator.java   View Source Code Vote up 4 votes
HeapDumpCreator(final Configuration configuration, final CommandExecutor commandExecutor)
    throws Exception {
  this(configuration, initHostName(), ManagementFactory
      .getPlatformMXBean(com.sun.management.HotSpotDiagnosticMXBean.class),
      commandExecutor, Logger.Factory.get(HeapDumpCreator.class));
}
 
Example 14
Project: openjdk-jdk10   File: DynamicVMOption.java   View Source Code Vote up 2 votes
/**
 * Creates an instance of DynamicVMOption.
 *
 * @param name the VM option name
 */
public DynamicVMOption(String name) {
    this.name = name;
    mxBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
}