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

The following are Jave code examples for showing how to use getRuntimeMXBean() 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: cdep   File: CDep.java   View Source Code Vote up 7 votes
private boolean handleStartupInfo(@NotNull List<String> args) {
  if (args.size() > 0 && "startup-info".equals(args.get(0))) {
    String jvmLocation = API.getJvmLocation();
    infoln("%s", jvmLocation);
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
    List<String> jvmArgs = bean.getInputArguments();

    for (String jvmArg : jvmArgs) {
      infoln(jvmArg);
    }
    infoln("-classpath " + System.getProperty("java.class.path"));
    // print the non-JVM command line arguments
    // print name of the main class with its arguments, like org.ClassName param1 param2
    infoln(System.getProperty("sun.java.command"));
    return true;
  }
  return false;
}
 
Example 2
Project: uavstack   File: JVMToolHelper.java   View Source Code Vote up 6 votes
/**
 * obtain current process cpu utilization if jdk version is 1.6 by-hongqiangwei
 */
@SuppressWarnings("restriction")
public static double getProcessCpuUtilization() {

    com.sun.management.OperatingSystemMXBean osMBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    long processCpuTime1 = osMBean.getProcessCpuTime();
    long runtime1 = runtimeMXBean.getUptime();

    ThreadHelper.suspend(50);

    long processCpuTime2 = osMBean.getProcessCpuTime();
    long runtime2 = runtimeMXBean.getUptime();

    long deltaProcessTime = processCpuTime2 - processCpuTime1;
    long deltaRunTime = (runtime2 - runtime1) * 1000000L;
    int cpuNumber = Runtime.getRuntime().availableProcessors();
    double cpuUtilization = (double) deltaProcessTime / (deltaRunTime * cpuNumber);

    return cpuUtilization;
}
 
Example 3
Project: BaseClient   File: PlayerUsageSnooper.java   View Source Code Vote up 6 votes
private void addJvmArgsToSnooper()
{
    RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean();
    List<String> list = runtimemxbean.getInputArguments();
    int i = 0;

    for (String s : list)
    {
        if (s.startsWith("-X"))
        {
            this.addClientStat("jvm_arg[" + i++ + "]", s);
        }
    }

    this.addClientStat("jvm_args", Integer.valueOf(i));
}
 
Example 4
Project: OpenJSharp   File: JdpController.java   View Source Code Vote up 6 votes
private static Integer getProcessId() {
    try {
        // Get the current process id using a reflection hack
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        Field jvm = runtime.getClass().getDeclaredField("jvm");
        jvm.setAccessible(true);

        VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
        Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
        pid_method.setAccessible(true);
        Integer pid = (Integer) pid_method.invoke(mgmt);
        return pid;
    } catch(Exception ex) {
        return null;
    }
}
 
Example 5
Project: BaseClient   File: PlayerUsageSnooper.java   View Source Code Vote up 6 votes
private void addJvmArgsToSnooper()
{
    RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean();
    List<String> list = runtimemxbean.getInputArguments();
    int i = 0;

    for (String s : list)
    {
        if (s.startsWith("-X"))
        {
            this.addClientStat("jvm_arg[" + i++ + "]", s);
        }
    }

    this.addClientStat("jvm_args", Integer.valueOf(i));
}
 
Example 6
Project: incubator-netbeans   File: Installer.java   View Source Code Vote up 5 votes
static File getHeapDump() {
    String heapDumpPath = null;
    RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
    List<String> lst = RuntimemxBean.getInputArguments();
    for (String arg : lst) {
        if (arg.contains("XX:HeapDumpPath")){
            int index = arg.indexOf('=');
            heapDumpPath = arg.substring(index+1);
        }
    }

    if (heapDumpPath == null){
        LOG.info("XX:HeapDumpPath parametter not specified");
        return null;
    }
    File heapDumpFile = new File(heapDumpPath);
    if (heapDumpFile.exists() && heapDumpFile.canRead() && heapDumpFile.length() > 0) {
        return heapDumpFile;
    }
    LOG.log(Level.INFO, "heap dump was not created at {0}", heapDumpPath);
    LOG.log(Level.INFO, "heapdump file: exists():{0}, canRead():{1}, length:{2}",new Object[] 
            {heapDumpFile.exists(), heapDumpFile.canRead(), heapDumpFile.length()});
    // no heap dump file found - this can happen in case of OOME: unable to create new native thread
    // try to create heap dump 
    dumpHeap(heapDumpFile.getAbsolutePath());
    if (heapDumpFile.exists() && heapDumpFile.canRead() && heapDumpFile.length() > 0) {
        return heapDumpFile;
    }        
    LOG.log(Level.INFO, "heap dump failed for {0}", heapDumpPath);
    return null;
}
 
Example 7
Project: dremio-oss   File: SabotConfig.java   View Source Code Vote up 5 votes
@VisibleForTesting
public SabotConfig(Config config, boolean enableServerConfigs) {
  super(config);
  logger.debug("Setting up SabotConfig object.");
  logger.trace("Given Config object is:\n{}",
               config.root().render(ConfigRenderOptions.defaults()));
  RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
  this.startupArguments = ImmutableList.copyOf(bean.getInputArguments());
  logger.debug("SabotConfig object initialized.");
}
 
Example 8
Project: jsf-sdk   File: JVMStatusTelnetHandler.java   View Source Code Vote up 5 votes
@Override
   public String telnet(Channel channel, String message) {
	StringBuilder sb = new StringBuilder();
	//内存使用情况
       MemoryMXBean mmxb = ManagementFactory.getMemoryMXBean();
       long max = mmxb.getHeapMemoryUsage().getMax();
       long used = mmxb.getHeapMemoryUsage().getUsed();
       long init = mmxb.getHeapMemoryUsage().getInit();
       long commit = mmxb.getHeapMemoryUsage().getCommitted();
       sb.append("********Memory status******************").append(line);
       sb.append("Max JVM Heap Memory:").append(max / 1024 / 1024).append("M").append(line)
               .append("Used Heap Memory:").append(used / 1024 / 1024).append("M").append(line)
               .append("Init Heap Memory:").append(init / 1024 / 1024).append("M").append(line)
               .append("Commited Heap Memory:").append(commit/1024/1024).append("M").append(line);
       
       sb.append("********Thread status********************").append(line);
       //线程数
       ThreadMXBean txmb = ManagementFactory.getThreadMXBean();
       sb.append("Peak thread count:").append(txmb.getPeakThreadCount()).append("").append(line)
               .append("Thread count:").append(txmb.getThreadCount()).append("").append(line);

       sb.append("********Runtime status******************").append(line);
       //启动入口参数
       RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
       sb.append("InputArguments:[");
       for(String ia : rmxb.getInputArguments()){
       	sb.append(ia).append(",");
       }
       sb.deleteCharAt(sb.length()-1).append("]").append(line);
       sb.append("JVM start time:").append(DateUtils.dateToStr(new Date(rmxb.getStartTime()))).append(line);
       
       return sb.toString();
}
 
Example 9
Project: EatDubbo   File: ConfigUtils.java   View Source Code Vote up 5 votes
public static int getPid() {
    if (PID < 0) {
        try {
            RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();  
            String name = runtime.getName(); // format: "[email protected]"  
            PID = Integer.parseInt(name.substring(0, name.indexOf('@')));
        } catch (Throwable e) {
            PID = 0;
        }
    }
    return PID;  
}
 
Example 10
Project: reading-and-annotate-rocketmq-3.4.6   File: UtilAll.java   View Source Code Vote up 5 votes
public static int getPid() {
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    String name = runtime.getName(); // format: "[email protected]"
    try {
        return Integer.parseInt(name.substring(0, name.indexOf('@')));
    }
    catch (Exception e) {
        return -1;
    }
}
 
Example 11
Project: iTAP-controller   File: Controller.java   View Source Code Vote up 4 votes
@Override
public long getSystemStartTime() {
    RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
    return rb.getStartTime();
}
 
Example 12
Project: OpenJSharp   File: JvmRuntimeImpl.java   View Source Code Vote up 4 votes
static RuntimeMXBean getRuntimeMXBean() {
    return ManagementFactory.getRuntimeMXBean();
}
 
Example 13
Project: athena   File: Controller.java   View Source Code Vote up 4 votes
public Long getUptime() {
    RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
    return rb.getUptime();
}
 
Example 14
Project: pcs-storage-adapter-java   File: Uptime.java   View Source Code Vote up 4 votes
/**
 * @return How long the service has been running.
 */
public static Duration getDuration() {
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    return Duration.millis(runtimeMXBean.getUptime());
}
 
Example 15
Project: device-telemetry-java   File: Uptime.java   View Source Code Vote up 4 votes
/**
 * @return When the service started.
 */
public static DateTime getStart() {
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    return new DateTime(runtimeMXBean.getStartTime()).toDateTime(DateTimeZone.UTC);
}
 
Example 16
Project: jdk8u-jdk   File: GetSystemProperties.java   View Source Code Vote up 4 votes
private static void runTest() throws Exception {
    RuntimeMXBean mbean = ManagementFactory.getRuntimeMXBean();

    // Print all system properties
    Map<String,String> props = mbean.getSystemProperties();
    printProperties(props);

    // Add new system properties
    System.setProperty(KEY1, VALUE1);
    System.setProperty(KEY2, VALUE2);

    Map<String,String> props1 = mbean.getSystemProperties();
    String value1 = props1.get(KEY1);
    if (value1 == null || !value1.equals(VALUE1)) {
        throw new RuntimeException(KEY1 + " property found" +
             " with value = " + value1 +
             " but expected to be " + VALUE1);
    }

    String value2 = props1.get(KEY2);
    if (value2 == null || !value2.equals(VALUE2)) {
        throw new RuntimeException(KEY2 + " property found" +
             " with value = " + value2 +
             " but expected to be " + VALUE2);
    }

    String value3 = props1.get(KEY3);
    if (value3 != null) {
        throw new RuntimeException(KEY3 + " property found" +
             " but should not exist" );
    }

    // Add new system properties but are not Strings
    Properties sp = System.getProperties();
    sp.put(KEY3, VALUE3);
    sp.put(KEY4, VALUE4);

    Map<String,String> props2 = mbean.getSystemProperties();
    // expect the system properties returned should be
    // same as the one before adding KEY3 and KEY4
    if (!props1.equals(props2)) {
        throw new RuntimeException("Two copies of system properties " +
            "are expected to be equal");
    }

    System.out.println("Test passed.");
}
 
Example 17
Project: appinventor-extensions   File: BuildServer.java   View Source Code Vote up 4 votes
@GET
@Path("vars")
@Produces(MediaType.TEXT_HTML)
public Response var() throws IOException {
  Map<String, String> variables = new LinkedHashMap<String, String>();

  // Runtime
  RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
  DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL);
  variables.put("state", getShutdownState() + "");
  if (shuttingTime != 0) {
    variables.put("shutdown-time", dateTimeFormat.format(new Date(shuttingTime)));
  }
  variables.put("start-time", dateTimeFormat.format(new Date(runtimeBean.getStartTime())));
  variables.put("uptime-in-ms", runtimeBean.getUptime() + "");
  variables.put("vm-name", runtimeBean.getVmName());
  variables.put("vm-vender", runtimeBean.getVmVendor());
  variables.put("vm-version", runtimeBean.getVmVersion());

  //BuildServer Version and Id
  variables.put("buildserver-version", GitBuildId.getVersion() + "");
  variables.put("buildserver-git-fingerprint", GitBuildId.getFingerprint() + "");

  // OS
  OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
  variables.put("os-arch", osBean.getArch());
  variables.put("os-name", osBean.getName());
  variables.put("os-version", osBean.getVersion());
  variables.put("num-processors", osBean.getAvailableProcessors() + "");
  variables.put("load-average-past-1-min", osBean.getSystemLoadAverage() + "");

  // Memory
  Runtime runtime = Runtime.getRuntime();
  MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
  variables.put("total-memory", runtime.totalMemory() + "");
  variables.put("free-memory", runtime.freeMemory() + "");
  variables.put("max-memory", runtime.maxMemory() + "");
  variables.put("used-heap", memoryBean.getHeapMemoryUsage().getUsed() + "");
  variables.put("used-non-heap", memoryBean.getNonHeapMemoryUsage().getUsed() + "");

  // Build requests
  variables.put("count-async-build-requests", asyncBuildRequests.get() + "");
  variables.put("rejected-async-build-requests", rejectedAsyncBuildRequests.get() + "");
  variables.put("successful-async-build-requests", successfulBuildRequests.get() + "");
  variables.put("failed-async-build-requests", failedBuildRequests.get() + "");

  // Build tasks
  int max = buildExecutor.getMaxActiveTasks();
  if (max == 0) {
    variables.put("maximum-simultaneous-build-tasks-allowed", "unlimited");
  } else {
    variables.put("maximum-simultaneous-build-tasks-allowed", max + "");
  }
  variables.put("completed-build-tasks", buildExecutor.getCompletedTaskCount() + "");
  maximumActiveBuildTasks = Math.max(maximumActiveBuildTasks, buildExecutor.getActiveTaskCount());
  variables.put("maximum-simultaneous-build-tasks-occurred", maximumActiveBuildTasks + "");
  variables.put("active-build-tasks", buildExecutor.getActiveTaskCount() + "");

  StringBuilder html = new StringBuilder();
  html.append("<html><body><tt>");
  for (Map.Entry<String, String> variable : variables.entrySet()) {
    html.append("<b>").append(variable.getKey()).append("</b> ")
      .append(variable.getValue()).append("<br>");
  }
  html.append("</tt></body></html>");
  return Response.ok(html.toString(), MediaType.TEXT_HTML_TYPE).build();
}
 
Example 18
Project: athena   File: Controller.java   View Source Code Vote up 4 votes
public Long getSystemUptime() {
    RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
    return rb.getUptime();
}
 
Example 19
Project: jdk8u-jdk   File: ProcessTools.java   View Source Code Vote up 4 votes
/**
 * Get the process id of the current running Java process
 *
 * @return Process id
 */
public static int getProcessId() throws Exception {

    // Get the current process id using a reflection hack
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    Field jvm = runtime.getClass().getDeclaredField("jvm");

    jvm.setAccessible(true);
    VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);

    Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");

    pid_method.setAccessible(true);

    int pid = (Integer) pid_method.invoke(mgmt);

    return pid;
}
 
Example 20
Project: monarch   File: MemberConfigurationInfo.java   View Source Code Vote up 4 votes
public MemberConfigurationInfo() {
  RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
  setJvmInputArguments(runtimeBean.getInputArguments());

}