Java 类java.lang.management.OperatingSystemMXBean 实例源码

项目:CentauriCloud    文件:LoadTimer.java   
private void sendLoad() {
    long freeRam = 0;
    double cpuLoad = 0;

    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
        method.setAccessible(true);
        if (method.getName().startsWith("get")
                && Modifier.isPublic(method.getModifiers())) {
            Object value = 0;
            try {
                value = method.invoke(operatingSystemMXBean);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (method.getName().equals("getFreePhysicalMemorySize"))
                freeRam = (long) value;
            if (method.getName().equals("getSystemCpuLoad"))
                cpuLoad = (double) value;
        }
    }

    Daemon.getInstance().getClient().getChannel().writeAndFlush(new PacketServerLoad(freeRam, cpuLoad));
}
项目:Java-Snippets    文件:EnvironmentInfo.java   
public static void getOsInfo() {
    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    //os general info
    String osName = osBean.getName();
    String osVersion = osBean.getVersion();
    String osArch = osBean.getArch();

    //CPU
    int cores = osBean.getAvailableProcessors();
    String cpuName = System.getenv("PROCESSOR_IDENTIFIER");
    //only on *nix systems
    double loadAvg = osBean.getSystemLoadAverage();

    if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
        getExtendedOsInfo((com.sun.management.OperatingSystemMXBean) osBean);
    }
}
项目:incubator-servicecomb-java-chassis    文件:MetricsServoRegistry.java   
@Override
public String call() {
  Map<String, String> memoryMap = new HashMap<>();
  OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();
  double cpu = osMxBean.getSystemLoadAverage();
  memoryMap.put("cpuLoad", String.format(doubleStringFormatter, round(cpu, doubleRoundPlaces)));

  ThreadMXBean threadmxBean = ManagementFactory.getThreadMXBean();
  int threadCount = threadmxBean.getThreadCount();
  memoryMap.put("cpuRunningThreads", String.valueOf(threadCount));

  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage memHeapUsage = memBean.getHeapMemoryUsage();
  MemoryUsage nonHeapUsage = memBean.getNonHeapMemoryUsage();
  memoryMap.put("heapInit", String.valueOf(memHeapUsage.getInit()));
  memoryMap.put("heapMax", String.valueOf(memHeapUsage.getMax()));
  memoryMap.put("heapCommit", String.valueOf(memHeapUsage.getCommitted()));
  memoryMap.put("heapUsed", String.valueOf(memHeapUsage.getUsed()));
  memoryMap.put("nonHeapInit", String.valueOf(nonHeapUsage.getInit()));
  memoryMap.put("nonHeapMax", String.valueOf(nonHeapUsage.getMax()));
  memoryMap.put("nonHeapCommit", String.valueOf(nonHeapUsage.getCommitted()));
  memoryMap.put("nonHeapUsed", String.valueOf(nonHeapUsage.getUsed()));
  return memoryMap.toString();
}
项目:rapidminer    文件:SystemInfoUtilities.java   
/**
 * Returns free physical memory in MB. If it is run in a 32-bit JVM it may return only a maximum
 * of 2GB even if more memory is available.
 * <p>
 * <strong>Attention:</strong> The returned value is dependant on the OS. For example on Linux
 * you might see less memory than there is actually available due to the OS using it for disk
 * caching. That memory is not actually blocked because the OS would release it if requested,
 * however this method will return the free memory which does NOT contain the ram used for disk
 * caching. Use with care!
 * </p>
 *
 * @return the free phsycial memory in MB or <code>-1</code> if we cannot determine it
 * @since 6.0.004
 *
 */
public static Long getFreePhysicalMemorySize() {
    OperatingSystemMXBean operatingSystemBean = getOperatingSystemBean();

    long memory = 0L;

    // if the system bean is an implementation by sun, we are almost done
    try {
        memory = ((com.sun.management.OperatingSystemMXBean) operatingSystemBean).getFreePhysicalMemorySize();
    } catch (Throwable t) { // NOPMD
        // fallback due to sun implementation not being available
        // in this case we behave as before 6.0.004 where we did not take free memory into
        // account
        return -1L;
    }

    memory /= TENTH_POWER_OF_TWO; // kbyte
    memory /= TENTH_POWER_OF_TWO; // mbyte
    return memory;
}
项目:mycat-src-1.6.1-RELEASE    文件:EnvironmentInformation.java   
/**
 * The maximum JVM heap size, in bytes.
 * 
 * @return The maximum JVM heap size, in bytes.
 */
public static long getMaxJvmHeapMemory() {
    long maxMemory = Runtime.getRuntime().maxMemory();

    if (maxMemory == Long.MAX_VALUE) {
        // amount of free memory unknown
        try {
            // workaround for Oracle JDK
            OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
            Class<?> clazz = Class.forName("com.sun.management.OperatingSystemMXBean");
            Method method = clazz.getMethod("getTotalPhysicalMemorySize");
            maxMemory = (Long) method.invoke(operatingSystemMXBean) / 4;
        }
        catch (Throwable e) {
            throw new RuntimeException("Could not determine the amount of free memory.\n" +
                    "Please set the maximum memory for the JVM, e.g. -Xmx512M for 512 megabytes.");
        }
    }

    return maxMemory;
}
项目:mycat-src-1.6.1-RELEASE    文件:EnvironmentInformation.java   
/**
 * Gets an estimate of the size of the free heap memory. The estimate may vary, depending on the current
 * level of memory fragmentation and the number of dead objects. For a better (but more heavy-weight)
 * estimate, use {@link #getSizeOfFreeHeapMemoryWithDefrag()}.
 * 
 * @return An estimate of the size of the free heap memory, in bytes.
 */
public static long getSizeOfFreeHeapMemory() {
    Runtime r = Runtime.getRuntime();
    long maxMemory = r.maxMemory();

    if (maxMemory == Long.MAX_VALUE) {
        // amount of free memory unknown
        try {
            // workaround for Oracle JDK
            OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
            Class<?> clazz = Class.forName("com.sun.management.OperatingSystemMXBean");
            Method method = clazz.getMethod("getTotalPhysicalMemorySize");
            maxMemory = (Long) method.invoke(operatingSystemMXBean) / 4;
        } catch (Throwable e) {
            throw new RuntimeException("Could not determine the amount of free memory.\n" +
                    "Please set the maximum memory for the JVM, e.g. -Xmx512M for 512 megabytes.");
        }
    }

    return maxMemory - r.totalMemory() + r.freeMemory();
}
项目:MantaroRPG    文件:AsyncInfoMonitor.java   
public static void start() {
    if (started) throw new IllegalStateException("Already Started.");
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    ThreadMXBean thread = ManagementFactory.getThreadMXBean();
    Runtime r = Runtime.getRuntime();
    int mb = 0x100000;

    lastSystemTime = System.nanoTime();
    lastProcessCpuTime = calculateProcessCpuTime(os);

    Async.task("AsyncInfoMonitorThread", () -> {
        threadCount = thread.getThreadCount();
        availableProcessors = r.availableProcessors();
        freeMemory = Runtime.getRuntime().freeMemory() / mb;
        maxMemory = Runtime.getRuntime().maxMemory() / mb;
        totalMemory = Runtime.getRuntime().totalMemory() / mb;
        cpuUsage = calculateCpuUsage(os);
        vpsCPUUsage = getVpsCPUUsage(os);
        vpsFreeMemory = calculateVPSFreeMemory(os);
        vpsMaxMemory = calculateVPSMaxMemory(os);
        vpsUsedMemory = vpsMaxMemory - vpsFreeMemory;
    }, 1);
    started = true;
}
项目:micrometer    文件:ProcessorMetrics.java   
@Override
public void bindTo(MeterRegistry registry) {
    Runtime runtime = Runtime.getRuntime();

    Gauge.builder("system.cpu.count", runtime, Runtime::availableProcessors)
        .tags(tags)
        .description("The number of processors available to the Java virtual machine")
        .register(registry);

    OperatingSystemMXBean operatingSystemBean = ManagementFactory.getOperatingSystemMXBean();
    if(operatingSystemBean != null && operatingSystemBean.getSystemLoadAverage() >= 0) {
        Gauge.builder("system.load.average.1m", operatingSystemBean, OperatingSystemMXBean::getSystemLoadAverage)
            .tags(tags)
            .description("The sum of the number of runnable entities queued to available processors and the number " +
                "of runnable entities running on the available processors averaged over a period of time")
            .register(registry);
    }
}
项目:traccar-service    文件:Log.java   
public static void logSystemInfo() {
    try {
        OperatingSystemMXBean operatingSystemBean = ManagementFactory.getOperatingSystemMXBean();
        Log.info("Operating system"
                + " name: " + operatingSystemBean.getName()
                + " version: " + operatingSystemBean.getVersion()
                + " architecture: " + operatingSystemBean.getArch());

        RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        Log.info("Java runtime"
                + " name: " + runtimeBean.getVmName()
                + " vendor: " + runtimeBean.getVmVendor()
                + " version: " + runtimeBean.getVmVersion());

        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        Log.info("Memory limit"
                + " heap: " + memoryBean.getHeapMemoryUsage().getMax() / (1024 * 1024) + "mb"
                + " non-heap: " + memoryBean.getNonHeapMemoryUsage().getMax() / (1024 * 1024) + "mb");

        Log.info("Character encoding: "
                + System.getProperty("file.encoding") + " charset: " + Charset.defaultCharset());

    } catch (Exception error) {
        Log.warning("Failed to get system info");
    }
}
项目:OneClient    文件:OperatingSystem.java   
private static long getOSMemory(String methodName, String warning) {
    long ram = 0;
    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    Method m;
    try {
        m = operatingSystemMXBean.getClass().getDeclaredMethod(methodName);
        m.setAccessible(true);
        Object value = m.invoke(operatingSystemMXBean);
        if (value != null) {
            ram = Long.valueOf(value.toString()) / 1024 / 1024;
        } else {
            OneClientLogging.logger.warn(warning);
            ram = 1024;
        }
    } catch (Exception e) {
        OneClientLogging.error(e);
    }

    return ram;
}
项目:uavstack    文件:JVMToolHelper.java   
public static Map<String, Double> readCPUUsage(OperatingSystemMXBean osMBean) {

        Map<String, Double> m = new LinkedHashMap<String, Double>();

        Double procCPU = (Double) ReflectionHelper.invoke("com.sun.management.OperatingSystemMXBean", osMBean,
                "getProcessCpuLoad", null, null);
        Double systemCPU = (Double) ReflectionHelper.invoke("com.sun.management.OperatingSystemMXBean", osMBean,
                "getSystemCpuLoad", null, null);

        if (procCPU == null) {
            procCPU = getProcessCpuUtilization();
            systemCPU = -1D;
        }

        DecimalFormat formatter = new DecimalFormat("00.0");

        m.put("cpu_p", Double.valueOf(formatter.format(procCPU * 100)));
        m.put("cpu_s", Double.valueOf(formatter.format(systemCPU * 100)));

        return m;
    }
项目:uavstack    文件:JVMToolHelper.java   
/**
 * 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;
}
项目:uavstack    文件:JVMStateCapHandler.java   
protected void readCPUUsage(MonitorElementInstance inst) {

        OperatingSystemMXBean osMBean = ManagementFactory.getOperatingSystemMXBean();
        Double procCPU = (Double) ReflectionHelper.invoke("com.sun.management.OperatingSystemMXBean", osMBean,
                "getProcessCpuLoad", null, null);
        Double systemCPU = (Double) ReflectionHelper.invoke("com.sun.management.OperatingSystemMXBean", osMBean,
                "getSystemCpuLoad", null, null);

        if (procCPU == null) {
            procCPU = JVMToolHelper.getProcessCpuUtilization();
            systemCPU = -1D;
        }

        inst.setValue("cpu_p", Double.valueOf(formatter.format(procCPU * 100)));
        inst.setValue("cpu_s", Double.valueOf(formatter.format(systemCPU * 100)));
    }
项目:GabrielBot    文件:AsyncInfoMonitor.java   
public static void start() {
    if (started) throw new IllegalStateException("Already Started.");
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    ThreadMXBean thread = ManagementFactory.getThreadMXBean();
    Runtime r = Runtime.getRuntime();
    int mb = 0x100000;

    lastSystemTime = System.nanoTime();
    lastProcessCpuTime = calculateProcessCpuTime(os);

    Async.task("AsyncInfoMonitorThread", () -> {
        threadCount = thread.getThreadCount();
        availableProcessors = r.availableProcessors();
        freeMemory = Runtime.getRuntime().freeMemory() / mb;
        maxMemory = Runtime.getRuntime().maxMemory() / mb;
        totalMemory = Runtime.getRuntime().totalMemory() / mb;
        cpuUsage = calculateCpuUsage(os);
        vpsCPUUsage = getVpsCPUUsage(os);
        vpsFreeMemory = calculateVPSFreeMemory(os);
        vpsMaxMemory = calculateVPSMaxMemory(os);
        vpsUsedMemory = vpsMaxMemory - vpsFreeMemory;
    }, 1);
    started = true;
}
项目:ThriftyPaxos    文件:Utils.java   
/**
 * Scale the value with the available memory. If 1 GB of RAM is available,
 * the value is returned, if 2 GB are available, then twice the value, and
 * so on.
 *
 * @param value the value to scale
 * @return the scaled value
 */
public static int scaleForAvailableMemory(int value) {
    long maxMemory = Runtime.getRuntime().maxMemory();
    if (maxMemory != Long.MAX_VALUE) {
        // we are limited by an -XmX parameter
        return (int) (value * maxMemory / (1024 * 1024 * 1024));
    }
    try {
        OperatingSystemMXBean mxBean = ManagementFactory
                .getOperatingSystemMXBean();
        // this method is only available on the class
        // com.sun.management.OperatingSystemMXBean, which mxBean
        // is an instance of under the Oracle JDK, but it is not present on
        // Android and other JDK's
        Method method = Class.forName(
                "com.sun.management.OperatingSystemMXBean").
                getMethod("getTotalPhysicalMemorySize");
        long physicalMemorySize = ((Number) method.invoke(mxBean)).longValue();
        return (int) (value * physicalMemorySize / (1024 * 1024 * 1024));
    } catch (Exception e) {
        // ignore
    }
    return value;
}
项目:stallion-core    文件:HealthInfo.java   
public HealthInfo hydrateSystemHealth() {
    Runtime rt = Runtime.getRuntime();
    long memUsage = (rt.totalMemory() - rt.freeMemory());
    long usedMB = memUsage / 1024 / 1024;
    system.setJvmMemoryUsage(memUsage);
    system.setJvmMemoryUsageMb(usedMB);
    system.setDiskFreeAppDirectory(new File(Settings.instance().getTargetFolder()).getUsableSpace());
    system.setDiskFreeDataDirectory(new File(Settings.instance().getDataDirectory()).getUsableSpace());
    system.setDiskFreeDataDirectoryMb(new File(Settings.instance().getDataDirectory()).getUsableSpace() / 1024 / 1024);
    system.setDiskFreeLogDirectory(new File("/tmp").getUsableSpace());
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    if(os instanceof UnixOperatingSystemMXBean){
        UnixOperatingSystemMXBean unixBean = (UnixOperatingSystemMXBean) os;
        //unixBean.
        // get system load
        // get process CPU load

        system.setFileHandlesOpen(unixBean.getOpenFileDescriptorCount());
    }
    return this;
}
项目:bigstreams    文件:QuorumBase.java   
@Override
public void tearDown() throws Exception {
    LOG.info("TearDown started");

    OperatingSystemMXBean osMbean =
        ManagementFactory.getOperatingSystemMXBean();
    if (osMbean != null && osMbean instanceof UnixOperatingSystemMXBean) {
        UnixOperatingSystemMXBean unixos =
            (UnixOperatingSystemMXBean)osMbean;
        LOG.info("fdcount after test is: "
                + unixos.getOpenFileDescriptorCount());
    }

    shutdownServers();

    for (String hp : hostPort.split(",")) {
        Assert.assertTrue("waiting for server down",
                   ClientBase.waitForServerDown(hp,
                                       ClientBase.CONNECTION_TIMEOUT));
        LOG.info(hp + " is no longer accepting client connections");
    }

    JMXEnv.tearDown();
}
项目:bigstreams    文件:QuorumBase.java   
@Override
public void tearDown() throws Exception {
    LOG.info("TearDown started");

    OperatingSystemMXBean osMbean =
        ManagementFactory.getOperatingSystemMXBean();
    if (osMbean != null && osMbean instanceof UnixOperatingSystemMXBean) {
        UnixOperatingSystemMXBean unixos =
            (UnixOperatingSystemMXBean)osMbean;
        LOG.info("fdcount after test is: "
                + unixos.getOpenFileDescriptorCount());
    }

    shutdownServers();

    for (String hp : hostPort.split(",")) {
        Assert.assertTrue("waiting for server down",
                   ClientBase.waitForServerDown(hp,
                                       ClientBase.CONNECTION_TIMEOUT));
        LOG.info(hp + " is no longer accepting client connections");
    }

    JMXEnv.tearDown();
}
项目:JavaGraphicsEngine    文件:PerformanceMonitor.java   
public synchronized double getProcessorUsage() {
    if (lastSystemTime == 0) {
        baselineCounters();
        return -1;
    }

    long systemTime = System.nanoTime();
    long processCPUTime = 0;

    if ( bean instanceof com.sun.management.OperatingSystemMXBean )
        processCPUTime = ( (com.sun.management.OperatingSystemMXBean) bean).getProcessCpuTime();

    double cpuUsage = (processCPUTime - lastProcessCPUTime) / ((double) (systemTime - lastSystemTime));
    lastSystemTime = systemTime;
    lastProcessCPUTime = processCPUTime;

    return cpuUsage / availableProcessors;
}
项目:scelight    文件:LUtils.java   
/**
 * Returns the system info.
 * 
 * @return the system info
 */
public static SysInfoBean getSysInfo() {
    final SysInfoBean sysInfo = new SysInfoBean();

    final OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
    sysInfo.setOsName( bean.getName() );
    sysInfo.setOsVersion( bean.getVersion() );
    sysInfo.setAvailProcs( bean.getAvailableProcessors() );

    sysInfo.setUserName( System.getProperty( "user.name" ) );
    sysInfo.setUserCountry( System.getProperty( "user.country" ) );
    // Set time zone using TimeZone class, "user.timezone" property is not guaranteed to be present
    // (See javadoc of System.getProperties())
    sysInfo.setUserTimeZone( TimeZone.getDefault().getID() );

    sysInfo.setDate( new Date() );

    try {
        // On windows "/" is the root of the current drive, so use "c:/" instead
        sysInfo.setMainRootSize( Files.getFileStore( Paths.get( LEnv.OS == OpSys.WINDOWS ? "c:/" : "/" ) ).getTotalSpace() );
    } catch ( final IOException ie ) {
        LEnv.LOGGER.error( "Failed to get main root size!", ie );
    }

    return sysInfo;
}
项目:Legacy-GN4R    文件:SystemInfo.java   
public void printUsage()
{
    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods())
    {
        method.setAccessible(true);
        if (method.getName().startsWith("get")
                && Modifier.isPublic(method.getModifiers()))
        {
            Object value;
            try
            {
                value = method.invoke(operatingSystemMXBean);
            }
            catch (Exception e)
            {
                value = e;
            } // try
            System.out.println(method.getName() + " = " + value);
        } // if
    } // for
}
项目:cibet    文件:VMLoadControlJMXBean.java   
private static synchronized int systemCpuLoadAvailable() {
   if (systemCpuLoadAvailable == -1) {
      Object systemLoad = retrieveLoadAttribute(SYSTEMATTRIBUTE);
      if (systemLoad == null) {
         OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
         double averageLoad = operatingSystemMXBean.getSystemLoadAverage();
         if (averageLoad >= 0) {
            log.info(
                  "System CPU load is measured with the Java method getSystemLoadAverage() of the OperatingSystemMXBean.");
            systemCpuLoadAvailable = 1;
         } else {
            log.warn("Unable to measure System CPU load on this operating system and Java VM");
            systemCpuLoadAvailable = 0;
         }

      } else {
         log.warn("System CPU load is measured with attribute " + SYSTEMATTRIBUTE + " of OperatingSystemMXBean. "
               + "This may be an expensive method dependend on the operating system and Java VM");
         systemCpuLoadAvailable = 2;
      }
   }
   return systemCpuLoadAvailable;
}
项目:cibet    文件:VMLoadControlJMXBean.java   
@JMXBeanAttribute(name = "CPU: System Load Average (%)", description = "the recent cpu usage for the whole system. -1 if not available", sortValue = "f1")
public double getSystemCpuLoad() {
   switch (systemCpuLoadAvailable) {
   case 0:
      return -1;
   case 1:
      OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
      double load = operatingSystemMXBean.getSystemLoadAverage() * 100
            / operatingSystemMXBean.getAvailableProcessors();
      return load;

   case 2:
      return (double) retrieveLoadAttribute(SYSTEMATTRIBUTE) * 100;

   default:
      return -1;
   }
}
项目:little_mitm    文件:TestUtils.java   
public static long getOpenFileDescriptorsAndPrintMemoryUsage() {
    // Below courtesy of:
    // http://stackoverflow.com/questions/10999076/programmatically-print-the-heap-usage-that-is-typically-printed-on-jvm-exit-when
    MemoryUsage mu = ManagementFactory.getMemoryMXBean()
            .getHeapMemoryUsage();
    MemoryUsage muNH = ManagementFactory.getMemoryMXBean()
            .getNonHeapMemoryUsage();
    System.out.println("Init :" + mu.getInit() + "\nMax :" + mu.getMax()
            + "\nUsed :" + mu.getUsed() + "\nCommitted :"
            + mu.getCommitted() + "\nInit NH :" + muNH.getInit()
            + "\nMax NH :" + muNH.getMax() + "\nUsed NH:" + muNH.getUsed()
            + "\nCommitted NH:" + muNH.getCommitted());

    OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();

    if (osMxBean instanceof UnixOperatingSystemMXBean) {
        UnixOperatingSystemMXBean unixOsMxBean = (UnixOperatingSystemMXBean) osMxBean;
        return unixOsMxBean.getOpenFileDescriptorCount();
    } else {
        throw new UnsupportedOperationException("Unable to determine number of open file handles on non-Unix system");
    }
}
项目:LagMonitor    文件:EnvironmentCommand.java   
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!isAllowed(sender, command)) {
        sender.sendMessage(ChatColor.DARK_RED + "Not whitelisted");
        return true;
    }

    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();

    //os general info
    sender.sendMessage(PRIMARY_COLOR + "OS Name: " + SECONDARY_COLOR + osBean.getName());
    sender.sendMessage(PRIMARY_COLOR + "Platform name: " + SECONDARY_COLOR + OS.getOs().getPlatformName());

    sender.sendMessage(PRIMARY_COLOR + "OS Version: " + SECONDARY_COLOR + osBean.getVersion());
    sender.sendMessage(PRIMARY_COLOR + "OS Arch: " + SECONDARY_COLOR + osBean.getArch());

    //CPU
    sender.sendMessage(PRIMARY_COLOR + "Cores: " + SECONDARY_COLOR + osBean.getAvailableProcessors());
    sender.sendMessage(PRIMARY_COLOR + "CPU: " + SECONDARY_COLOR + System.getenv("PROCESSOR_IDENTIFIER"));
    sender.sendMessage(PRIMARY_COLOR + "Load Average: " + SECONDARY_COLOR + osBean.getSystemLoadAverage());
    printExtendOsInfo(sender);

    displayDiskSpace(sender);
    return true;
}
项目:LagMonitor    文件:MonitorSaveTask.java   
private int onMonitorSave(Storage storage) {
    Runtime runtime = Runtime.getRuntime();
    int maxMemory = LagUtils.byteToMega(runtime.maxMemory());
    //we need the free ram not the free heap
    int usedRam = LagUtils.byteToMega(runtime.totalMemory() - runtime.freeMemory());
    int freeRam = maxMemory - usedRam;

    float freeRamPct = round((freeRam * 100) / maxMemory, 4);

    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    float loadAvg = round(osBean.getSystemLoadAverage(), 4);
    if (loadAvg == -1) {
        //windows doesn't support this
        loadAvg = 0;
    }

    NativeData nativeData = plugin.getNativeData();
    float systemUsage = round(nativeData.getCPULoad() * 100, 4);
    float procUsage = round(nativeData.getProcessCPULoad() * 100, 4);

    int totalOsMemory = LagUtils.byteToMega(nativeData.getTotalMemory());
    int freeOsRam = LagUtils.byteToMega(nativeData.getFreeMemory());

    float freeOsRamPct = round((freeOsRam * 100) / totalOsMemory, 4);
    return storage.saveMonitor(procUsage, systemUsage, freeRam, freeRamPct, freeOsRam, freeOsRamPct, loadAvg);
}
项目:rapidminer-studio    文件:SystemInfoUtilities.java   
/**
 * Returns free physical memory in MB. If it is run in a 32-bit JVM it may return only a maximum
 * of 2GB even if more memory is available.
 * <p>
 * <strong>Attention:</strong> The returned value is dependant on the OS. For example on Linux
 * you might see less memory than there is actually available due to the OS using it for disk
 * caching. That memory is not actually blocked because the OS would release it if requested,
 * however this method will return the free memory which does NOT contain the ram used for disk
 * caching. Use with care!
 * </p>
 *
 * @return the free phsycial memory in MB or <code>-1</code> if we cannot determine it
 * @since 6.0.004
 *
 */
public static Long getFreePhysicalMemorySize() {
    OperatingSystemMXBean operatingSystemBean = getOperatingSystemBean();

    long memory = 0L;

    // if the system bean is an implementation by sun, we are almost done
    try {
        memory = ((com.sun.management.OperatingSystemMXBean) operatingSystemBean).getFreePhysicalMemorySize();
    } catch (Throwable t) { // NOPMD
        // fallback due to sun implementation not being available
        // in this case we behave as before 6.0.004 where we did not take free memory into
        // account
        return -1L;
    }

    memory /= TENTH_POWER_OF_TWO; // kbyte
    memory /= TENTH_POWER_OF_TWO; // mbyte
    return memory;
}
项目:LagMonitor    文件:MonitorSaveTask.java   
private int onMonitorSave(Storage storage) {
    Runtime runtime = Runtime.getRuntime();
    int maxMemory = LagUtils.byteToMega(runtime.maxMemory());
    //we need the free ram not the free heap
    int usedRam = LagUtils.byteToMega(runtime.totalMemory() - runtime.freeMemory());
    int freeRam = maxMemory - usedRam;

    float freeRamPct = round((freeRam * 100) / maxMemory, 4);

    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    float loadAvg = round(osBean.getSystemLoadAverage(), 4);
    if (loadAvg == -1) {
        //windows doesn't support this
        loadAvg = 0;
    }

    NativeData nativeData = plugin.getNativeData();
    float systemUsage = round(nativeData.getCPULoad() * 100, 4);
    float procUsage = round(nativeData.getProcessCPULoad() * 100, 4);

    int totalOsMemory = LagUtils.byteToMega(nativeData.getTotalMemory());
    int freeOsRam = LagUtils.byteToMega(nativeData.getFreeMemory());

    float freeOsRamPct = round((freeOsRam * 100) / totalOsMemory, 4);
    return storage.saveMonitor(procUsage, systemUsage, freeRam, freeRamPct, freeOsRam, freeOsRamPct, loadAvg);
}
项目:putnami-gradle-plugin    文件:GwtCompileTask.java   
private int evalWorkers(CompilerOption options) {
    long workers = Runtime.getRuntime().availableProcessors();
    OperatingSystemMXBean osMBean = ManagementFactory.getOperatingSystemMXBean();
    if (osMBean instanceof com.sun.management.OperatingSystemMXBean) {
        com.sun.management.OperatingSystemMXBean sunOsMBean = (com.sun.management.OperatingSystemMXBean) osMBean;
        long memPerWorker = 1024L * 1024L * options.getLocalWorkersMem();
        long nbFreeMemInGb = sunOsMBean.getFreePhysicalMemorySize() / memPerWorker;

        if (nbFreeMemInGb < workers) {
            workers = nbFreeMemInGb;
        }
        if (workers < 1) {
            workers = 1;
        }
    }
    return (int) workers;
}
项目:search    文件:SystemInfoHandlerTest.java   
public void testMagickGetter() {

    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();

    // make one directly
    SimpleOrderedMap<Object> info = new SimpleOrderedMap<>();
    info.add( "name", os.getName() );
    info.add( "version", os.getVersion() );
    info.add( "arch", os.getArch() );

    // make another using addGetterIfAvaliable 
    SimpleOrderedMap<Object> info2 = new SimpleOrderedMap<>();
    SystemInfoHandler.addGetterIfAvaliable( os, "name", info2 );
    SystemInfoHandler.addGetterIfAvaliable( os, "version", info2 );
    SystemInfoHandler.addGetterIfAvaliable( os, "arch", info2 );

    // make sure they got the same thing
    assertEquals( info.toString(), info2.toString() );
  }
项目:simple-boot    文件:File.java   
@Override
protected void doHealthCheck(final Builder builder)
        throws Exception {
    final OperatingSystemMXBean os = getOperatingSystemMXBean();
    if (os instanceof UnixOperatingSystemMXBean) {
        final UnixOperatingSystemMXBean unix
                = (UnixOperatingSystemMXBean) os;
        builder.withDetail("max-file-descriptors",
                unix.getMaxFileDescriptorCount()).
                withDetail("open-file-descriptors",
                        unix.getOpenFileDescriptorCount());
    }

    final java.io.File here = new java.io.File(".");
    builder.withDetail("usable-disk", here.getUsableSpace()).
            withDetail("total-disk", here.getTotalSpace());

    builder.up();
}
项目:simple-boot    文件:Memory.java   
@Override
protected void doHealthCheck(final Builder builder)
        throws Exception {
    final OperatingSystemMXBean os = getOperatingSystemMXBean();
    if (os instanceof com.sun.management.OperatingSystemMXBean) {
        final com.sun.management.OperatingSystemMXBean oracle
                = (com.sun.management.OperatingSystemMXBean) os;
        builder.withDetail("committed-virtual-memory",
                oracle.getCommittedVirtualMemorySize()).
                withDetail("free-physical-memory",
                        oracle.getFreePhysicalMemorySize()).
                withDetail("free-swap-space",
                        oracle.getFreeSwapSpaceSize()).
                withDetail("total-physical-memory",
                        oracle.getTotalPhysicalMemorySize()).
                withDetail("total-swap-space",
                        oracle.getTotalSwapSpaceSize());
        builder.up();
    }
}
项目:simple-boot    文件:Cpu.java   
@Override
protected void doHealthCheck(final Builder builder)
        throws Exception {
    final OperatingSystemMXBean os = getOperatingSystemMXBean();
    builder.withDetail("processors", os.getAvailableProcessors()).
            withDetail("system-loadavg", os.getSystemLoadAverage());

    if (os instanceof com.sun.management.OperatingSystemMXBean) {
        final com.sun.management.OperatingSystemMXBean oracle
                = (com.sun.management.OperatingSystemMXBean) os;
        builder.withDetail("process-cpu-load", oracle.getProcessCpuLoad()).
                withDetail("process-cpu-time",
                        ofNanos(oracle.getProcessCpuTime()).toString()).
                withDetail("system-cpu-load", oracle.getSystemCpuLoad());
    }

    builder.up();
}
项目:gerrit    文件:GetSummary.java   
private JvmSummaryInfo getJvmSummary() {
  OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
  RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();

  JvmSummaryInfo jvmSummary = new JvmSummaryInfo();
  jvmSummary.vmVendor = runtimeBean.getVmVendor();
  jvmSummary.vmName = runtimeBean.getVmName();
  jvmSummary.vmVersion = runtimeBean.getVmVersion();
  jvmSummary.osName = osBean.getName();
  jvmSummary.osVersion = osBean.getVersion();
  jvmSummary.osArch = osBean.getArch();
  jvmSummary.user = System.getProperty("user.name");

  try {
    jvmSummary.host = InetAddress.getLocalHost().getHostName();
  } catch (UnknownHostException e) {
    // Ignored
  }

  jvmSummary.currentWorkingDirectory = path(Paths.get(".").toAbsolutePath().getParent());
  jvmSummary.site = path(sitePath);
  return jvmSummary;
}
项目:LagMonitor    文件:EnvironmentCommand.java   
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!isAllowed(sender, command)) {
        sender.sendMessage(ChatColor.DARK_RED + "Not whitelisted");
        return true;
    }

    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();

    //os general info
    sender.sendMessage(PRIMARY_COLOR + "OS Name: " + SECONDARY_COLOR + osBean.getName());
    sender.sendMessage(PRIMARY_COLOR + "Platform name: " + SECONDARY_COLOR + OS.getOs().getPlatformName());

    sender.sendMessage(PRIMARY_COLOR + "OS Version: " + SECONDARY_COLOR + osBean.getVersion());
    sender.sendMessage(PRIMARY_COLOR + "OS Arch: " + SECONDARY_COLOR + osBean.getArch());

    //CPU
    sender.sendMessage(PRIMARY_COLOR + "Cores: " + SECONDARY_COLOR + osBean.getAvailableProcessors());
    sender.sendMessage(PRIMARY_COLOR + "CPU: " + SECONDARY_COLOR + System.getenv("PROCESSOR_IDENTIFIER"));
    sender.sendMessage(PRIMARY_COLOR + "Load Average: " + SECONDARY_COLOR + osBean.getSystemLoadAverage());
    printExtendOsInfo(sender);

    displayDiskSpace(sender);
    return true;
}
项目:tEFMA    文件:AbstractDoubleDescriptionImpl.java   
private void logOptions(MetabolicNetwork metaNet, EfmOutputCallback callback) {
    final RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean();
    final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
    final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    LOG.info("Elemetary flux mode computation");
    LOG.info("Implementation:");
    LOG.info("..algorithm name   : " + getImplName());
    LOG.info("..model type       : " + getFactoryName(mEfmModelFactory));
    LOG.info("..memory type      : " + getFactoryName(mMemoryFactory));
    LOG.info("..output type      : " + getCallbackName(callback));
    LOG.info("System:");
    LOG.info("..hostname         : " + getHostName());
    LOG.info("..operating system : " + osBean.getArch() + "/" + osBean.getName() + "/" + osBean.getVersion());
    LOG.info("..processors       : " + osBean.getAvailableProcessors());
    LOG.info("..vm               : " + rtBean.getVmVendor() + "/" + rtBean.getVmName() + "/" + rtBean.getVmVersion());
    LOG.info("..vm-spec          : " + rtBean.getSpecVendor() + "/" + rtBean.getSpecName() + "/" + rtBean.getSpecVersion());
    LOG.info("..vm arguments     : " + rtBean.getInputArguments());
    LOG.info("..memory, commited : " + (memBean.getHeapMemoryUsage().getCommitted() / 1000 / 1000) + "M");
    LOG.info("..memory, used     : " + (memBean.getHeapMemoryUsage().getUsed() / 1000 / 1000) + "M");
    mConfig.log(LOG, Level.INFO);
}
项目:logspace    文件:MemoryAgent.java   
@Override
public void execute(AgentOrder agentOrder) {
    OperatingSystemMXBean operatingSystemBean = ManagementFactory.getOperatingSystemMXBean();

    if (!(operatingSystemBean instanceof com.sun.management.OperatingSystemMXBean)) {
        return;
    }

    com.sun.management.OperatingSystemMXBean operatingSystem = (com.sun.management.OperatingSystemMXBean) operatingSystemBean;

    OsEventBuilder osEventBuilder = createMemoryBuilder(this.getEventBuilderData());

    osEventBuilder.setTotalMemory(operatingSystem.getTotalPhysicalMemorySize());
    osEventBuilder.setFreeMemory(operatingSystem.getFreePhysicalMemorySize());
    osEventBuilder.setUsedMemory(operatingSystem.getTotalPhysicalMemorySize() - operatingSystem.getFreePhysicalMemorySize());
    osEventBuilder.setCommittedVirtualMemory(operatingSystem.getCommittedVirtualMemorySize());

    this.sendEvent(osEventBuilder.toEvent());
}
项目:incubator-netbeans    文件:CPUInfo.java   
static void logCPUInfo() {
    LogRecord log = new LogRecord(Level.FINEST, MESSAGE); // NOI18N
    OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
    Object [] params = new Object[]{bean.getAvailableProcessors()};
    log.setParameters(params);
    Logger.getLogger(Installer.UI_PERFORMANCE_LOGGER_NAME).log(log);
}
项目:rapidminer    文件:SystemInfoUtilities.java   
/**
 * Returns total physical memory in MB. If it is run in a 32-bit JVM it may return only a
 * maximum of 4GB even if more memory is available.
 *
 * @return the amount of physical memory in MB
 * @throws IOException
 *             if something goes wrong
 */
public static Long getTotalPhysicalMemorySize() throws IOException {
    OperatingSystemMXBean operatingSystemBean = getOperatingSystemBean();

    long memory = 0L;

    // if the system bean is an implementation by sun, we are almost done
    try {
        memory = ((com.sun.management.OperatingSystemMXBean) operatingSystemBean).getTotalPhysicalMemorySize();
    } catch (Throwable t) {  // NOPMD
        // // fallback because sun implementation is not available
        switch (getOperatingSystem()) {
            case OSX:
                memory = readOSXTotalMemory();
                break;
            case WINDOWS:
                memory = readWindowsTotalMemory();
                break;
            case UNIX:
                memory = readUnixTotalMemory();
                break;
            case SOLARIS:
                memory = readSolarisTotalMemory();
                break;
            case OTHER:
            default:
                memory = readOtherTotalMemory();
                break;
        }
    }

    memory /= TENTH_POWER_OF_TWO; // kbyte
    memory /= TENTH_POWER_OF_TWO; // mbyte
    return memory;
}
项目:elasticsearch_my    文件:Probes.java   
public static short getLoadAndScaleToPercent(Method method, OperatingSystemMXBean osMxBean) {
    if (method != null) {
        try {
            double load = (double) method.invoke(osMxBean);
            if (load >= 0) {
                return (short) (load * 100);
            }
        } catch (Exception e) {
            return -1;
        }
    }
    return -1;
}