Java Code Examples for com.sun.management.OperatingSystemMXBean#getSystemCpuLoad()

The following examples show how to use com.sun.management.OperatingSystemMXBean#getSystemCpuLoad() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GetSystemCpuLoad.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
        ManagementFactory.getOperatingSystemMXBean();
    double load;
    for(int i=0; i<10; i++) {
        load = mbean.getSystemCpuLoad();
        if((load<0.0 || load>1.0) && load != -1.0) {
            throw new RuntimeException("getSystemCpuLoad() returns " + load
                   +  " which is not in the [0.0,1.0] interval");
        }
        try {
            Thread.sleep(200);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 2
Source File: GetSystemCpuLoad.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
        ManagementFactory.getOperatingSystemMXBean();
    double load;
    for(int i=0; i<10; i++) {
        load = mbean.getSystemCpuLoad();
        if((load<0.0 || load>1.0) && load != -1.0) {
            throw new RuntimeException("getSystemCpuLoad() returns " + load
                   +  " which is not in the [0.0,1.0] interval");
        }
        try {
            Thread.sleep(200);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 3
Source File: GetSystemCpuLoad.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
        ManagementFactory.getOperatingSystemMXBean();
    double load;
    for(int i=0; i<10; i++) {
        load = mbean.getSystemCpuLoad();
        if((load<0.0 || load>1.0) && load != -1.0) {
            throw new RuntimeException("getSystemCpuLoad() returns " + load
                   +  " which is not in the [0.0,1.0] interval");
        }
        try {
            Thread.sleep(200);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 4
Source File: GetSystemCpuLoad.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
        ManagementFactory.getOperatingSystemMXBean();
    double load;
    for(int i=0; i<10; i++) {
        load = mbean.getSystemCpuLoad();
        if((load<0.0 || load>1.0) && load != -1.0) {
            throw new RuntimeException("getSystemCpuLoad() returns " + load
                   +  " which is not in the [0.0,1.0] interval");
        }
        try {
            Thread.sleep(200);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 5
Source File: GetSystemCpuLoad.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
        ManagementFactory.getOperatingSystemMXBean();
    double load;
    for(int i=0; i<10; i++) {
        load = mbean.getSystemCpuLoad();
        if((load<0.0 || load>1.0) && load != -1.0) {
            throw new RuntimeException("getSystemCpuLoad() returns " + load
                   +  " which is not in the [0.0,1.0] interval");
        }
        try {
            Thread.sleep(200);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 6
Source File: GetSystemCpuLoad.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
        ManagementFactory.getOperatingSystemMXBean();
    double load;
    for(int i=0; i<10; i++) {
        load = mbean.getSystemCpuLoad();
        if((load<0.0 || load>1.0) && load != -1.0) {
            throw new RuntimeException("getSystemCpuLoad() returns " + load
                   +  " which is not in the [0.0,1.0] interval");
        }
        try {
            Thread.sleep(200);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 7
Source File: GetSystemCpuLoad.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
        ManagementFactory.getOperatingSystemMXBean();
    double load;
    for(int i=0; i<10; i++) {
        load = mbean.getSystemCpuLoad();
        if((load<0.0 || load>1.0) && load != -1.0) {
            throw new RuntimeException("getSystemCpuLoad() returns " + load
                   +  " which is not in the [0.0,1.0] interval");
        }
        try {
            Thread.sleep(200);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 8
Source File: GetSystemCpuLoad.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
        ManagementFactory.getOperatingSystemMXBean();
    double load;
    for(int i=0; i<10; i++) {
        load = mbean.getSystemCpuLoad();
        if((load<0.0 || load>1.0) && load != -1.0) {
            throw new RuntimeException("getSystemCpuLoad() returns " + load
                   +  " which is not in the [0.0,1.0] interval");
        }
        try {
            Thread.sleep(200);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 9
Source File: ClusterMonitor.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private UsageUtil getMachineUsage() {
  OperatingSystemMXBean operatingSystemMXBean
      = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);

  // Returns the amount of free physical memory in bytes.
  long freePhysicalMemorySize = operatingSystemMXBean.getFreePhysicalMemorySize();

  // Returns the total amount of physical memory in bytes.
  long totalPhysicalMemorySize = operatingSystemMXBean.getTotalPhysicalMemorySize();

  // Returns the "recent cpu usage" for the whole system.
  double systemCpuLoad = operatingSystemMXBean.getSystemCpuLoad();

  int process = Runtime.getRuntime().availableProcessors();

  UsageUtil monitorUtil = new UsageUtil();
  monitorUtil.memoryUsed = totalPhysicalMemorySize - freePhysicalMemorySize;
  monitorUtil.memoryCapacity = totalPhysicalMemorySize;
  monitorUtil.cpuUsed = (long) (process * systemCpuLoad * 100);
  monitorUtil.cpuCapacity = process * 100;

  return monitorUtil;
}
 
Example 10
Source File: GetSystemCpuLoad.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
        ManagementFactory.getOperatingSystemMXBean();
    double load;
    for(int i=0; i<10; i++) {
        load = mbean.getSystemCpuLoad();
        if((load<0.0 || load>1.0) && load != -1.0) {
            throw new RuntimeException("getSystemCpuLoad() returns " + load
                   +  " which is not in the [0.0,1.0] interval");
        }
        try {
            Thread.sleep(200);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 11
Source File: GetSystemCpuLoad.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
        ManagementFactory.getOperatingSystemMXBean();
    double load;
    for(int i=0; i<10; i++) {
        load = mbean.getSystemCpuLoad();
        if((load<0.0 || load>1.0) && load != -1.0) {
            throw new RuntimeException("getSystemCpuLoad() returns " + load
                   +  " which is not in the [0.0,1.0] interval");
        }
        try {
            Thread.sleep(200);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 12
Source File: IndexAdminController.java    From Roothub with GNU Affero General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(Model model) {
	// 查询当天新增话题
    model.addAttribute("topic_count", topicService.countToday());
    // 查询当天新增评论
    model.addAttribute("comment_count", replyService.count());
    // 查询当天新增用户
    model.addAttribute("user_count", userService.countToday());
    //查询当天新增节点
    model.addAttribute("node_count", nodeService.countToday());
    // 获取操作系统的名字
    model.addAttribute("os_name", System.getProperty("os.name"));
    // 内存
    int kb = 1024;
    OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
        .getOperatingSystemMXBean();
    // 总的物理内存(G)
    float totalMemorySize = (float) osmxb.getTotalPhysicalMemorySize() / kb / kb / kb;
    
    //已使用的物理内存(G)
    float usedMemory = (float) (osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / kb / kb /kb;
    // 获取系统cpu负载
    double systemCpuLoad = osmxb.getSystemCpuLoad();
    // 获取jvm线程负载
    double processCpuLoad = osmxb.getProcessCpuLoad();
    
    DecimalFormat df = new DecimalFormat("0.0");
    model.addAttribute("totalMemorySize", df.format(totalMemorySize));
    model.addAttribute("usedMemory", df.format(usedMemory));
    model.addAttribute("systemCpuLoad", df.format(systemCpuLoad));
    model.addAttribute("processCpuLoad", df.format(processCpuLoad));

	return "/admin/index";
}
 
Example 13
Source File: IndexAdminController.java    From Roothub with GNU Affero General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/console", method = RequestMethod.GET)
public String console(Model model) {
	// 查询当天新增话题
    model.addAttribute("topic_count", topicService.countToday());
    // 查询当天新增评论
    model.addAttribute("comment_count", replyService.count());
    // 查询当天新增用户
    model.addAttribute("user_count", userService.countToday());
    //查询当天新增节点
    model.addAttribute("node_count", nodeService.countToday());
    // 获取操作系统的名字
    model.addAttribute("os_name", System.getProperty("os.name"));
    // 内存
    int kb = 1024;
    OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
        .getOperatingSystemMXBean();
    // 总的物理内存(G)
    float totalMemorySize = (float) osmxb.getTotalPhysicalMemorySize() / kb / kb / kb;
    
    //已使用的物理内存(G)
    float usedMemory = (float) (osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / kb / kb /kb;
    // 获取系统cpu负载
    double systemCpuLoad = osmxb.getSystemCpuLoad();
    // 获取jvm线程负载
    double processCpuLoad = osmxb.getProcessCpuLoad();
    
    DecimalFormat df = new DecimalFormat("0.0");
    model.addAttribute("totalMemorySize", df.format(totalMemorySize));
    model.addAttribute("usedMemory", df.format(usedMemory));
    model.addAttribute("systemCpuLoad", df.format(systemCpuLoad));
    model.addAttribute("processCpuLoad", df.format(processCpuLoad));

	return "/admin/console";
}
 
Example 14
Source File: IndexAdminController.java    From pybbs with GNU Affero General Public License v3.0 5 votes vote down vote up
@RequiresUser
@GetMapping({"/", "/index"})
public String index(Model model) {
    // 查询当天新增话题
    model.addAttribute("topic_count", topicService.countToday());
    // 查询当天新增标签
    model.addAttribute("tag_count", tagService.countToday());
    // 查询当天新增评论
    model.addAttribute("comment_count", commentService.countToday());
    // 查询当天新增用户
    model.addAttribute("user_count", userService.countToday());

    // 获取操作系统的名字
    model.addAttribute("os_name", System.getProperty("os.name"));

    // 内存
    int kb = 1024;
    OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    // 总的物理内存
    long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
    //已使用的物理内存
    long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / kb;
    // 获取系统cpu负载
    double systemCpuLoad = osmxb.getSystemCpuLoad();
    // 获取jvm线程负载
    double processCpuLoad = osmxb.getProcessCpuLoad();

    model.addAttribute("totalMemorySize", totalMemorySize);
    model.addAttribute("usedMemory", usedMemory);
    model.addAttribute("systemCpuLoad", systemCpuLoad);
    model.addAttribute("processCpuLoad", processCpuLoad);

    return "admin/index";
}
 
Example 15
Source File: SystemStatusListener.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
        currentLoad = osBean.getSystemLoadAverage();
        /**
         * Java Doc copied from {@link OperatingSystemMXBean#getSystemCpuLoad()}:</br>
         * Returns the "recent cpu usage" for the whole system. This value is a double in the [0.0,1.0] interval.
         * A value of 0.0 means that all CPUs were idle during the recent period of time observed, while a value
         * of 1.0 means that all CPUs were actively running 100% of the time during the recent period being
         * observed. All values betweens 0.0 and 1.0 are possible depending of the activities going on in the
         * system. If the system recent cpu usage is not available, the method returns a negative value.
         */
        currentCpuUsage = osBean.getSystemCpuLoad();

        StringBuilder sb = new StringBuilder();
        if (currentLoad > SystemRuleManager.getHighestSystemLoad()) {
            sb.append("load:").append(currentLoad).append(";");
            sb.append("cpu:").append(currentCpuUsage).append(";");
            sb.append("qps:").append(Constants.ENTRY_NODE.passQps()).append(";");
            sb.append("rt:").append(Constants.ENTRY_NODE.avgRt()).append(";");
            sb.append("thread:").append(Constants.ENTRY_NODE.curThreadNum()).append(";");
            sb.append("success:").append(Constants.ENTRY_NODE.successQps()).append(";");
            sb.append("minRt:").append(Constants.ENTRY_NODE.minRt()).append(";");
            sb.append("maxSuccess:").append(Constants.ENTRY_NODE.maxSuccessQps()).append(";");
            RecordLog.info(sb.toString());
        }

    } catch (Throwable e) {
        RecordLog.info("could not get system error ", e);
    }
}
 
Example 16
Source File: GetSystemInfo.java    From FATE-Serving with Apache License 2.0 4 votes vote down vote up
public static double getSystemCpuLoad() {
    OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    double systemCpuLoad = osmxb.getSystemCpuLoad();
    return systemCpuLoad;
}
 
Example 17
Source File: NamenodeAnalyticsMethods.java    From NNAnalytics with Apache License 2.0 4 votes vote down vote up
/**
 * SYSTEM endpoint is meant to show the system resource usage of the NNA instance in PLAINTEXT
 * form. TODO: Convert the output to JSON form.
 */
@GET
@Path("/system")
@Produces({MediaType.TEXT_PLAIN})
public Response system() {
  try {
    before();
    Runtime runtime = Runtime.getRuntime();
    OperatingSystemMXBean systemMxBean =
        (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
    MemoryMXBean mb = ManagementFactory.getMemoryMXBean();
    MemoryUsage memNonHeap = mb.getNonHeapMemoryUsage();
    MemoryUsage memHeap = mb.getHeapMemoryUsage();

    StringBuilder sb = new StringBuilder();
    int availableCores = runtime.availableProcessors();
    double cpuLoad = systemMxBean.getSystemCpuLoad();
    double procLoad = systemMxBean.getProcessCpuLoad();

    sb.append("Server uptime (ms): ").append(rb.getUptime()).append("\n\n");

    sb.append("Available Processor Cores: ").append(availableCores).append("\n");
    sb.append("System CPU Load: ").append(cpuLoad).append("\n");
    sb.append("Process CPU Load: ").append(procLoad).append("\n\n");

    sb.append("Non-Heap Used Memory (KB): ").append(memNonHeap.getUsed() / 1024).append("\n");
    sb.append("Non-Heap Committed Memory (KB): ")
        .append((memNonHeap.getCommitted() / 1024))
        .append("\n");
    sb.append("Non-Heap Max Memory (KB): ").append((memNonHeap.getMax() / 1024)).append("\n\n");

    sb.append("Heap Used Memory (KB): ").append(memHeap.getUsed() / 1024).append("\n");
    sb.append("Heap Committed Memory (KB): ")
        .append((memHeap.getCommitted() / 1024))
        .append("\n");
    sb.append("Heap Max Memory (KB): ").append((memHeap.getMax() / 1024)).append("\n\n");

    sb.append("Max Memory (KB): ").append((runtime.maxMemory() / 1024)).append("\n");

    return Response.ok(sb.toString(), MediaType.TEXT_PLAIN).build();
  } catch (RuntimeException rtex) {
    return handleException(rtex);
  } catch (Exception ex) {
    return handleException(ex);
  } finally {
    after();
  }
}
 
Example 18
Source File: UberUtil.java    From antsdb with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static double getSystemCpuLoad() {
    OperatingSystemMXBean bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    return bean.getSystemCpuLoad();
}
 
Example 19
Source File: SystemUsageDataCollector.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public List<HBData> collectData()
{
    logger.debug("Preparing repository usage (system) data...");

    Runtime runtime = Runtime.getRuntime();
    Map<String, Object> systemUsageValues = new HashMap<>();

    // operating system MBean info
    Map<String, Object> cpu = new HashMap<>();
    OperatingSystemMXBean osMBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
    if (osMBean != null)
    {
        if (osMBean instanceof UnixOperatingSystemMXBean)
        {
            long openFileDescriptorCount = ((UnixOperatingSystemMXBean) osMBean).getOpenFileDescriptorCount();
            systemUsageValues.put("openFileDescriptorCount", new Long(openFileDescriptorCount));
        }

        // processor info
        double processCpuLoad = osMBean.getProcessCpuLoad() * 100;
        double systemCpuLoad  = osMBean.getSystemCpuLoad()  * 100;
        int intProcessCpuLoad = (int) Math.round(processCpuLoad);
        int intSystemCpuLoad  = (int) Math.round(systemCpuLoad);

        cpu.put("percentageProcessLoad", new Integer(intProcessCpuLoad) );
        cpu.put("percentageSystemLoad", new Integer(intSystemCpuLoad));
        cpu.put("systemLoadAverage", new Double(osMBean.getSystemLoadAverage()));
    }
    cpu.put("availableProcessors", new Integer( runtime.availableProcessors()));
    systemUsageValues.put("cpu", cpu);

    // database connections info
    if (dataSource instanceof BasicDataSource)
    {
        Map<String, Object> db = new HashMap<>();
        int idleConnections = ((BasicDataSource) dataSource).getNumIdle();
        int activeConnections = ((BasicDataSource) dataSource).getNumActive();
        db.put("idleConnections", new Integer(idleConnections));
        db.put("activeConnections", new Integer(activeConnections));
        systemUsageValues.put("db", db);
    }

    // memory info
    Map<String, Object> mem = new HashMap<>();
    mem.put("free", runtime.freeMemory());
    mem.put("max", runtime.maxMemory());
    mem.put("total", runtime.totalMemory());
    systemUsageValues.put( "mem", mem);

    HBData systemUsageData = new HBData(
            this.currentRepoDescriptorDAO.getDescriptor().getId(),
            this.getCollectorId(),
            this.getCollectorVersion(),
            new Date(),
            systemUsageValues);

    return Arrays.asList(systemUsageData);
}
 
Example 20
Source File: HostTask.java    From bistoury with GNU General Public License v3.0 4 votes vote down vote up
private static HostInfo getHostInfo(MxBean mxBean) {
    OperatingSystemMXBean osBean = mxBean.getOsBean();
    ThreadMXBean threadBean = mxBean.getThreadBean();

    HostInfo hostInfo = new HostInfo();
    String osName = System.getProperty("os.name");
    int availableProcessors = Runtime.getRuntime().availableProcessors();
    String cpuLoadAverages = null;
    if (osName != null && osName.toLowerCase().contains("linux")) {
        try {
            File file = new File(LOADAVG_FILENAME);
            cpuLoadAverages = FileUtil.readFile(file);
        } catch (IOException e) {
            logger.error("get CPU Load Averages error", e);
        }
    }

    double systemLoadAverage = osBean.getSystemLoadAverage();
    // 可使用内存
    long totalMemory = Runtime.getRuntime().totalMemory() / KB;
    // 剩余内存
    long freeMemory = Runtime.getRuntime().freeMemory() / KB;
    // 最大可使用内存
    long maxMemory = Runtime.getRuntime().maxMemory() / KB;

    //总交换空间
    long totalSwapSpaceSize = osBean.getTotalSwapSpaceSize() / KB;
    //空闲交换空间
    long freeSwapSpaceSize = osBean.getFreeSwapSpaceSize() / KB;
    //总物理内存
    long totalPhysicalMemorySize = osBean.getTotalPhysicalMemorySize() / KB;
    //空闲物理内存
    long freePhysicalMemorySize = osBean.getFreePhysicalMemorySize() / KB;
    //系统CPU利用率
    double systemCpuLoad = osBean.getSystemCpuLoad();

    long totalThread = threadBean.getTotalStartedThreadCount();

    //获取磁盘信息
    getDiskInfo(hostInfo);

    hostInfo.setAvailableProcessors(availableProcessors);
    hostInfo.setSystemLoadAverage(systemLoadAverage);
    hostInfo.setCpuLoadAverages(Strings.nullToEmpty(cpuLoadAverages));
    hostInfo.setOsName(osName);
    hostInfo.setTotalMemory(totalMemory);
    hostInfo.setFreeMemory(freeMemory);
    hostInfo.setMaxMemory(maxMemory);
    hostInfo.setTotalSwapSpaceSize(totalSwapSpaceSize);
    hostInfo.setFreeSwapSpaceSize(freeSwapSpaceSize);
    hostInfo.setTotalPhysicalMemorySize(totalPhysicalMemorySize);
    hostInfo.setFreePhysicalMemorySize(freePhysicalMemorySize);
    hostInfo.setUsedMemory(totalPhysicalMemorySize - freePhysicalMemorySize);
    hostInfo.setTotalThread(totalThread);
    hostInfo.setCpuRatio(systemCpuLoad);
    return hostInfo;
}