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

The following examples show how to use com.sun.management.OperatingSystemMXBean#getTotalPhysicalMemorySize() . 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: WindowsSystemCommander.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 获取windows 监控
 * https://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/OperatingSystemMXBean.html
 *
 * @return 返回cpu占比和内存占比
 */
@Override
public JSONObject getAllMonitor() {
    OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    JSONObject jsonObject = new JSONObject();
    double total = operatingSystemMXBean.getTotalPhysicalMemorySize();
    double free = operatingSystemMXBean.getFreePhysicalMemorySize();
    jsonObject.put("memory", String.format("%.2f", (total - free) / total * 100));
    //最近系统cpu使用量
    double systemCpuLoad = operatingSystemMXBean.getSystemCpuLoad();
    if (systemCpuLoad <= 0) {
        systemCpuLoad = 0;
    }
    jsonObject.put("cpu", String.format("%.2f", systemCpuLoad * 100));
    jsonObject.put("disk", getHardDisk());
    return jsonObject;
}
 
Example 2
Source File: HealthStatisticsReader.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public CartridgeStatistics getCartridgeStatistics() throws IOException {
    OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    double totalMemory = (double) (osBean.getTotalPhysicalMemorySize() / MB);
    double usedMemory = (double) ((totalMemory - (osBean.getFreePhysicalMemorySize() / MB)));
    double loadAvg = (double) osBean.getSystemLoadAverage();
    // assume system cores = available cores to JVM
    int cores = osBean.getAvailableProcessors();
    double memoryConsumption = (usedMemory / totalMemory) * 100;
    double loadAvgPercentage = (loadAvg / cores) * 100;

    if (log.isDebugEnabled()) {
        log.debug("Memory consumption: [totalMemory] " + totalMemory + "Mb [usedMemory] " + usedMemory + "Mb: " + memoryConsumption + "%");
        log.debug("Processor consumption: [loadAverage] " + loadAvg + " [cores] " + cores + ": " + loadAvgPercentage + "%");
    }

    return (new CartridgeStatistics(memoryConsumption, loadAvgPercentage));
}
 
Example 3
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 4
Source File: ClusterMonitor.java    From submarine 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 5
Source File: FreeMemoryGauge.java    From dropwizard-wavefront with Apache License 2.0 5 votes vote down vote up
@Override
public Long getValue() {
  OperatingSystemMXBean mbean = (com.sun.management.OperatingSystemMXBean)
      ManagementFactory.getOperatingSystemMXBean();

  return mbean.getTotalPhysicalMemorySize() - mbean.getCommittedVirtualMemorySize();
}
 
Example 6
Source File: OSProcessHelper.java    From uavstack with Apache License 2.0 5 votes vote down vote up
private static void analyseWinMem(String resultString, Map<String, Map<String, String>> resultMap,
        Map<String, List<Long>> timeRecord) {

    long sysTime = System.currentTimeMillis() * 10000;
    OperatingSystemMXBean osmb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    long totalMem = osmb.getTotalPhysicalMemorySize();
    String[] lines = resultString.split("\n");
    int beginline = 3; // data begin at line 3
    for (int i = beginline; i < lines.length; i++) {
        if (lines[i].length() == 0) {
            continue;
        }
        String statusArgs[] = lines[i].split("\\s+");
        String pid = statusArgs[1];
        Map<String, String> statusMap = resultMap.get(pid);
        long mem = Long.parseLong(statusArgs[3]);
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        float memrate = (float) mem / (float) totalMem;
        String memRate = decimalFormat.format(memrate * 100);
        statusMap.put(MEM, String.valueOf(mem / 1024));
        statusMap.put(MEMRATE, memRate);
        String kernelmodetime = statusArgs[0];
        String usermodetime = statusArgs[2];
        long nt = Long.parseLong(kernelmodetime) + Long.parseLong(usermodetime);
        List<Long> otList;
        otList = new ArrayList<Long>(2);
        otList.add(nt);
        otList.add(sysTime);
        timeRecord.put(pid, otList);
    }
}
 
Example 7
Source File: MonitorSer.java    From luckyBlog with Apache License 2.0 5 votes vote down vote up
public int getFreeMemory() {
    OperatingSystemMXBean osmxb = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
    long totalVirtualMemory = osmxb.getTotalPhysicalMemorySize();
    long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
    Double compare = (freePhysicalMemorySize * 1.0 / totalVirtualMemory) * 100;
    return compare.intValue();
}
 
Example 8
Source File: LicenseVerifyManager.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
private void checkRam(ExtraParam param) {
    // Unit MB
    int expectRam = param.ram();
    if (expectRam == NO_LIMIT) {
        return;
    }
    OperatingSystemMXBean mxBean = (OperatingSystemMXBean) ManagementFactory
                                   .getOperatingSystemMXBean();
    long actualRam = mxBean.getTotalPhysicalMemorySize() / Bytes.MB;
    if (actualRam > expectRam) {
        throw newLicenseException(
              "The server's ram(MB) '%s' exceeded the limit(MB) '%s'",
              actualRam, expectRam);
    }
}
 
Example 9
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 10
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 11
Source File: MonitorSerImpl.java    From jcalaBlog with MIT License 5 votes vote down vote up
@Override
public int getFreeMemory(){
        OperatingSystemMXBean osmxb = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
        long totalVirtualMemory = osmxb.getTotalPhysicalMemorySize();
        long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
        Double compare = (freePhysicalMemorySize * 1.0 / totalVirtualMemory) * 100;
        return compare.intValue();
}
 
Example 12
Source File: GetSystemInfo.java    From FATE-Serving with Apache License 2.0 5 votes vote down vote up
public static long getTotalMemorySize() {
    int kb = 1024;
    OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
    return totalMemorySize;
}
 
Example 13
Source File: ServerLoadStatus.java    From summerframework with Apache License 2.0 5 votes vote down vote up
public void calculateSystemInfo() {
    this.osName = System.getProperty("os.name");
    int kb = 1024;
    OperatingSystemMXBean osmxb = (OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();
    this.systemLoadAverage = osmxb.getSystemLoadAverage();
    this.availableProcessors = osmxb.getAvailableProcessors();
    this.freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
    this.totalPhysicalMemorySize = osmxb.getTotalPhysicalMemorySize();
    this.usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / kb;

}
 
Example 14
Source File: ServerArgument.java    From incubator-iotdb with Apache License 2.0 4 votes vote down vote up
private long totalPhysicalMemory() {
  OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
  long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / 1024 / 1024;
  return totalMemorySize;
}
 
Example 15
Source File: DataxMachineUtil.java    From DataLink with Apache License 2.0 4 votes vote down vote up
public static long getMachineTotalMemory() {
    OperatingSystemMXBean osmb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    return osmb.getTotalPhysicalMemorySize();
}
 
Example 16
Source File: MemoryInformation.java    From FlyingAgent with Apache License 2.0 4 votes vote down vote up
MemoryInformation() {
    OperatingSystemMXBean os = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    physicalMemorySize = (os.getTotalPhysicalMemorySize());
    freePhysicalMemory = (os.getFreePhysicalMemorySize());
    inUseMemorySize = (physicalMemorySize - freePhysicalMemory);
}
 
Example 17
Source File: WindowsSystemCommander.java    From Jpom with MIT License 4 votes vote down vote up
/**
     * 将windows的tasklist转为集合
     *
     * @param header 是否包含投信息
     * @param result 进程信息
     * @return jsonArray
     */
    private static List<ProcessModel> formatWindowsProcess(String result, boolean header) {
        List<String> list = StrSpliter.splitTrim(result, StrUtil.LF, true);
        if (list.isEmpty()) {
            return null;
        }
        List<ProcessModel> processModels = new ArrayList<>();
        ProcessModel processModel;
        for (int i = header ? 2 : 0, len = list.size(); i < len; i++) {
            String param = list.get(i);
            List<String> memList = StrSpliter.splitTrim(param, StrUtil.SPACE, true);
            processModel = new ProcessModel();
            int pid = Convert.toInt(memList.get(1), 0);
            processModel.setPid(pid);
            //
            String name = memList.get(0);
            processModel.setCommand(name);
            //使用内存 kb
            String mem = memList.get(4).replace(",", "");
            long aLong = Convert.toLong(mem, 0L);
//            FileUtil.readableFileSize()
            processModel.setRes(aLong / 1024 + " MB");
            String status = memList.get(6);
            processModel.setStatus(formatStatus(status));
            //
            processModel.setUser(memList.get(7));
            processModel.setTime(memList.get(8));

            try {
                OperatingSystemMXBean operatingSystemMXBean = JvmUtil.getOperatingSystemMXBean(memList.get(1));
                if (operatingSystemMXBean != null) {
                    //最近jvm cpu使用率
                    double processCpuLoad = operatingSystemMXBean.getProcessCpuLoad() * 100;
                    if (processCpuLoad <= 0) {
                        processCpuLoad = 0;
                    }
                    processModel.setCpu(String.format("%.2f", processCpuLoad) + "%");
                    //服务器总内存
                    long totalMemorySize = operatingSystemMXBean.getTotalPhysicalMemorySize();
                    BigDecimal total = new BigDecimal(totalMemorySize / 1024);
                    // 进程
                    double v = new BigDecimal(aLong).divide(total, 4, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                    processModel.setMem(String.format("%.2f", v) + "%");
                }
            } catch (Exception ignored) {

            }
            processModels.add(processModel);
        }
        return processModels;
    }
 
Example 18
Source File: VMSummary.java    From vi with Apache License 2.0 4 votes vote down vote up
public VMSummary(){
    MemoryMXBean bean = ManagementFactory.getMemoryMXBean();
    MemoryUsage u = bean.getHeapMemoryUsage();
    heapCommitedMemory= (u.getCommitted());
    heapUsedMemory=(u.getUsed());
    heapMaxMemory=(u.getMax());

    u = bean.getNonHeapMemoryUsage();
    nonHeapCommitedMemory=(u.getCommitted());
    nonHeapUsedMemory=(u.getUsed());
    nonHeapMaxMemory=(u.getMax());

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    currentThreadCount=threadBean.getThreadCount();
    daemonThreadCount= threadBean.getDaemonThreadCount();
    totalStartedThreadCount= threadBean.getTotalStartedThreadCount();
    peakThreadCount = threadBean.getPeakThreadCount();

    ClassLoadingMXBean classLoadingBean = ManagementFactory.getClassLoadingMXBean();
    loadedClassCount=classLoadingBean.getLoadedClassCount();
    totalLoadedClassCount=classLoadingBean.getTotalLoadedClassCount();
    unloadedClassCount=classLoadingBean.getUnloadedClassCount();
    getGCStatus();

    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    classPath = runtimeBean.getClassPath();
    libraryPath = runtimeBean.getLibraryPath();
    vmOptions = TextUtils.join(" ",runtimeBean.getInputArguments());
    bootClassPath = runtimeBean.getBootClassPath();
    upTime = runtimeBean.getUptime();

    vmName=runtimeBean.getVmName();
    vmVendor= runtimeBean.getVmVendor();


    OperatingSystemMXBean osBean= (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

    processCpuTime = osBean.getProcessCpuTime();

    jdkVersion=System.getProperty("java.version");
    jitCompiler=System.getProperty("java.vm.name");

    os = osBean.getName() + " "+osBean.getVersion();
    osArch = osBean.getArch();
    availableProcessors = osBean.getAvailableProcessors();

     commitedVirtualMemory = osBean.getCommittedVirtualMemorySize();
    freePhysicalMemorySize =(osBean.getFreePhysicalMemorySize());
    totalPhysicalMemorySize =(osBean.getTotalPhysicalMemorySize());

    freeSwapSpaceSize =(osBean.getFreeSwapSpaceSize());
    totalSwapSpaceSize =(osBean.getTotalSwapSpaceSize());

    List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();
    gcInfos = new ArrayList<>(beans.size());
    for (GarbageCollectorMXBean b : beans) {
        GCBean gcBean = new GCBean();
        gcBean.name =b.getName();
        gcBean.gcCount = b.getCollectionCount();
        gcBean.gcTime = b.getCollectionTime();
        gcInfos.add(gcBean);
    }

}
 
Example 19
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;
}
 
Example 20
Source File: SystemSupplier.java    From joyrpc with Apache License 2.0 2 votes vote down vote up
/**
 * 获取内存大小
 *
 * @return 内存大小
 */
protected long getMemory() {
    OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    return osmxb.getTotalPhysicalMemorySize();
}