java.lang.management.PlatformManagedObject#java.lang.management.OperatingSystemMXBean源码实例Demo

下面列出了java.lang.management.PlatformManagedObject#java.lang.management.OperatingSystemMXBean 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: LagMonitor   文件: MonitorSaveTask.java
private int save() {
    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 < 0) {
        //windows doesn't support this
        loadAvg = 0;
    }

    NativeManager nativeData = plugin.getNativeData();
    float systemUsage = round(nativeData.getCPULoad() * 100, 4);
    float processUsage = 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(processUsage, systemUsage, freeRam, freeRamPct, freeOsRam, freeOsRamPct, loadAvg);
}
 
源代码2 项目: LagMonitor   文件: NativeManager.java
public void setupNativeAdapter() {
    try {
        if (!loadExternalJNI()) {
            if (!(osBean instanceof com.sun.management.OperatingSystemMXBean)) {
                logger.severe("You're not using Oracle Java nor using the native library. " +
                        "You won't be able to read some native data");
            }

            return;
        }
    } catch (IOException | ReflectiveOperationException ex) {
        logger.log(Level.WARNING, "Cannot load JNA library. We continue without it", ex);
        return;
    }

    logger.info("Found JNA native library. Enabling extended native data support to display more data");
    try {
        info = new SystemInfo();

        //make a test call
        pid = info.getOperatingSystem().getProcessId();
    } catch (UnsatisfiedLinkError | NoClassDefFoundError linkError) {
        logger.log(Level.INFO, "Cannot load native library. Continuing without it...", linkError);
        info = null;
    }
}
 
源代码3 项目: lucene-solr   文件: SystemInfoHandlerTest.java
public void testMagickGetter() throws Exception {

    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 MetricUtils.addMXBeanMetrics()
    SimpleOrderedMap<Object> info2 = new SimpleOrderedMap<>();
    MetricUtils.addMXBeanMetrics( os, OperatingSystemMXBean.class, null, (k, v) -> {
      info2.add(k, ((Gauge)v).getValue());
    } );

    // make sure they got the same thing
    for (String p : Arrays.asList("name", "version", "arch")) {
      assertEquals(info.get(p), info2.get(p));
    }
  }
 
源代码4 项目: apm-agent-java   文件: JmxUtils.java
@Nullable
public synchronized static Method getOperatingSystemMBeanMethod(OperatingSystemMXBean operatingSystemBean, String methodName) {
    if (!initialized) {
        // lazy initialization - try loading the classes as late as possible
        init();
    }
    if (operatingSystemBeanClass == null) {
        return null;
    }
    try {
        // ensure the Bean we have is actually an instance of the interface
        operatingSystemBeanClass.cast(operatingSystemBean);
        return operatingSystemBeanClass.getMethod(methodName);
    } catch (ClassCastException | NoSuchMethodException | SecurityException e) {
        return null;
    }
}
 
源代码5 项目: LagMonitor   文件: MonitorSaveTask.java
private int save() {
    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 < 0) {
        //windows doesn't support this
        loadAvg = 0;
    }

    NativeManager nativeData = plugin.getNativeData();
    float systemUsage = round(nativeData.getCPULoad() * 100, 4);
    float processUsage = 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(processUsage, systemUsage, freeRam, freeRamPct, freeOsRam, freeOsRamPct, loadAvg);
}
 
源代码6 项目: visualvm   文件: CpuMonitorProbe.java
CpuMonitorProbe(MonitoredDataResolver resolver, Application application,
                Jvm jvm) {
    super(2, createItemDescriptors(), resolver);
    cpuSupported = jvm.isCpuMonitoringSupported();
    gcSupported = jvm.isCollectionTimeSupported();
    int pCount = 1;
    JmxModel jmxModel = JmxModelFactory.getJmxModelFor(application);
    if (jmxModel != null && jmxModel.getConnectionState() == ConnectionState.CONNECTED) {
        JvmMXBeans mxbeans = JvmMXBeansFactory.getJvmMXBeans(jmxModel);
        if (mxbeans != null) {
            OperatingSystemMXBean osbean = mxbeans.getOperatingSystemMXBean();
            if (osbean != null) pCount = osbean.getAvailableProcessors();
        }
    }
    processorsCount = pCount;
}
 
源代码7 项目: Plan   文件: SystemUsage.java
/**
 * Check how active the system is (CPU) or if not available, using system load average.
 * <p>
 * - On some OSes CPU usage information is not available, and system load average is used instead.
 * - On some OSes system load average is not available.
 *
 * @return 0.0 to 100.0 if CPU, or system load average, or -1 if nothing is available.
 */
public static double getAverageSystemLoad() {
    double averageUsage;

    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
        com.sun.management.OperatingSystemMXBean nativeOsBean = (com.sun.management.OperatingSystemMXBean) osBean;
        averageUsage = nativeOsBean.getSystemCpuLoad();
    } else {
        int availableProcessors = osBean.getAvailableProcessors();
        averageUsage = osBean.getSystemLoadAverage() / availableProcessors;
    }
    if (averageUsage < 0) {
        averageUsage = -1; // If unavailable, getSystemLoadAverage() returns -1
    }
    return averageUsage * 100.0;
}
 
源代码8 项目: ns4_gear_watchdog   文件: SystemMonitor.java
Report(OperatingSystemMXBean osBean) {
    map.put(OS_NAME, osBean.getName());
    map.put(OS_VERSION, osBean.getVersion());
    map.put(OS_ARCH, osBean.getArch());
    map.put(SYSTEM_AVAILABLE_PROCESSORS, osBean.getAvailableProcessors());
    map.put(SYSTEM_LOAD_AVERAGE, osBean.getSystemLoadAverage());
}
 
源代码9 项目: crate   文件: 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;
}
 
源代码10 项目: javamelody   文件: JavaInformations.java
private static double buildSystemLoadAverage() {
	// System load average for the last minute.
	// The system load average is the sum of
	// the number of runnable entities queued to the available processors
	// and the number of runnable entities running on the available processors
	// averaged over a period of time.
	final OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
	if (operatingSystem.getSystemLoadAverage() >= 0) {
		// systemLoadAverage n'existe qu'à partir du jdk 1.6
		return operatingSystem.getSystemLoadAverage();
	}
	return -1;
}
 
源代码11 项目: dubbox   文件: LoadStatusChecker.java
public Status check() {
	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	double load;
	try {
	    Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage", new Class<?>[0]);
	    load = (Double)method.invoke(operatingSystemMXBean, new Object[0]);
	} catch (Throwable e) {
	    load = -1;
	}
	int cpu = operatingSystemMXBean.getAvailableProcessors();
    return new Status(load < 0 ? Status.Level.UNKNOWN : (load < cpu ? Status.Level.OK : Status.Level.WARN), "Load: " + load + " / CPU: " + cpu);
}
 
源代码12 项目: datacollector   文件: TestFileContext.java
private long getOpenFileDescriptors() {
  OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
  if (os instanceof UnixOperatingSystemMXBean) {
    return ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount();
  } else {
    return -1;
  }
}
 
源代码13 项目: rocketmq-4.3.0   文件: StoreUtil.java
@SuppressWarnings("restriction")
public static long getTotalPhysicalMemorySize() {
    long physicalTotal = 1024 * 1024 * 1024 * 24L;
    OperatingSystemMXBean osmxb = ManagementFactory.getOperatingSystemMXBean();
    if (osmxb instanceof com.sun.management.OperatingSystemMXBean) {
        physicalTotal = ((com.sun.management.OperatingSystemMXBean) osmxb).getTotalPhysicalMemorySize();
    }

    return physicalTotal;
}
 
源代码14 项目: jdk8u_jdk   文件: MXBeanInteropTest1.java
private final int doOperatingSystemMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- OperatingSystemMXBean") ;

    try {
        ObjectName operationName =
                new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(operationName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t" + mbInfo);
        OperatingSystemMXBean operation = null ;

        operation =
                JMX.newMXBeanProxy(mbsc,
                operationName,
                OperatingSystemMXBean.class) ;
        System.out.println("getArch\t\t"
                + operation.getArch());
        System.out.println("getAvailableProcessors\t\t"
                + operation.getAvailableProcessors());
        System.out.println("getName\t\t"
                + operation.getName());
        System.out.println("getVersion\t\t"
                + operation.getVersion());

        System.out.println("---- OK\n") ;
    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
源代码15 项目: nifi   文件: DiagnosticAnalysisTask.java
private void analyzeCpuUsage(final List<String> details) {
    final OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();

    final double loadAverage = os.getSystemLoadAverage();
    final int availableProcs = os.getAvailableProcessors();

    if (loadAverage > availableProcs) {
        details.add(String.format("1-minute CPU Load Average is %1$.2f, which exceeds the %2$d available cores. CPU is over-utilized.", loadAverage, availableProcs));
    } else if (loadAverage > 0.9 * availableProcs) {
        details.add(String.format("1-minute CPU Load Average is %1$.2f, which exceeds 90%% of the %2$d available cores. CPU may struggle to keep up.", loadAverage, availableProcs));
    }
}
 
源代码16 项目: dragonwell8_jdk   文件: MXBeanInteropTest1.java
private final int doOperatingSystemMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- OperatingSystemMXBean") ;

    try {
        ObjectName operationName =
                new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(operationName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t" + mbInfo);
        OperatingSystemMXBean operation = null ;

        operation =
                JMX.newMXBeanProxy(mbsc,
                operationName,
                OperatingSystemMXBean.class) ;
        System.out.println("getArch\t\t"
                + operation.getArch());
        System.out.println("getAvailableProcessors\t\t"
                + operation.getAvailableProcessors());
        System.out.println("getName\t\t"
                + operation.getName());
        System.out.println("getVersion\t\t"
                + operation.getVersion());

        System.out.println("---- OK\n") ;
    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
源代码17 项目: wisdom   文件: CpuGaugeSet.java
/**
 * This method uses a Sun specific class (implementation of the Operating System MX Bean.
 * @return the CPU system load, or {@literal -1.0} if not available.
 */
private Double getSystemCpuLoad() {
    if (bean instanceof com.sun.management.OperatingSystemMXBean) { //NOSONAR
        return ((com.sun.management.OperatingSystemMXBean) bean).getSystemCpuLoad() * 100.0;  //NOSONAR
    } else {
        return -1.0;
    }
}
 
源代码18 项目: Doradus   文件: CassandraNode.java
private OperatingSystemMXBean getOperatingSystemMXBeanProxy() {
	if (osServiceProxy == null) {
		try {
			setConnection();
		} catch (Exception ex) {
			throwException("Can't create proxy of OperatingSystemMXBean",
					ex);
		}
	}
	return osServiceProxy;
}
 
源代码19 项目: metrics   文件: FileDescriptorRatioGauge.java
/**
 * Creates a new gauge using the given OS bean.
 *
 * @param os    an {@link OperatingSystemMXBean}
 */
public FileDescriptorRatioGauge(OperatingSystemMXBean os, long timeout, TimeUnit unit) {
    this.os = os;
    cachedRatio = new CachedGauge<Ratio>(timeout, unit) {
        @Override
        protected Ratio loadValue() {
            return getRatioInternal();
        }
    };
}
 
源代码20 项目: ping   文件: ServerWatch.java
public JsonObject osInfo() {
    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    return Json.createObjectBuilder().
            add("System Load Average", osBean.getSystemLoadAverage()).
            add("Available CPUs", osBean.getAvailableProcessors()).
            add("Architecture", osBean.getArch()).
            add("OS Name", osBean.getName()).
            add("Version", osBean.getVersion()).build();

}
 
源代码21 项目: TencentKona-8   文件: MXBeanInteropTest1.java
private final int doOperatingSystemMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- OperatingSystemMXBean") ;

    try {
        ObjectName operationName =
                new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(operationName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t" + mbInfo);
        OperatingSystemMXBean operation = null ;

        operation =
                JMX.newMXBeanProxy(mbsc,
                operationName,
                OperatingSystemMXBean.class) ;
        System.out.println("getArch\t\t"
                + operation.getArch());
        System.out.println("getAvailableProcessors\t\t"
                + operation.getAvailableProcessors());
        System.out.println("getName\t\t"
                + operation.getName());
        System.out.println("getVersion\t\t"
                + operation.getVersion());

        System.out.println("---- OK\n") ;
    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
源代码22 项目: rtg-tools   文件: Environment.java
/**
 * Get number of available processors.
 * @return number of available processors.
 */
public static int getAvailableProcessors() {
  final OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
  if (bean != null) {
    return bean.getAvailableProcessors();
  }
  throw new IllegalStateException();
}
 
源代码23 项目: bidder   文件: Performance.java
/**
 * Get CPU performance as a String, adjusted by cores
 * 
 * @return String. Returns a cpu percentage string
 */
public static String getCpuPerfAsString() {
	OperatingSystemMXBean mx = java.lang.management.ManagementFactory.getOperatingSystemMXBean();
	int cores = Runtime.getRuntime().availableProcessors();
	double d = mx.getSystemLoadAverage() * 100 / cores;
       return formatter.format(d);
}
 
源代码24 项目: LagMonitor   文件: NativeManager.java
public double getProcessCPULoad() {
    if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
        com.sun.management.OperatingSystemMXBean nativeOsBean = (com.sun.management.OperatingSystemMXBean) osBean;
        return nativeOsBean.getProcessCpuLoad();
    }

    return -1;
}
 
源代码25 项目: rocketmq   文件: StoreUtil.java
@SuppressWarnings("restriction")
public static long getTotalPhysicalMemorySize() {
    long physicalTotal = 1024 * 1024 * 1024 * 24L;
    OperatingSystemMXBean osmxb = ManagementFactory.getOperatingSystemMXBean();
    if (osmxb instanceof com.sun.management.OperatingSystemMXBean) {
        physicalTotal = ((com.sun.management.OperatingSystemMXBean) osmxb).getTotalPhysicalMemorySize();
    }

    return physicalTotal;
}
 
源代码26 项目: DataLink   文件: VMInfo.java
public static long getLongFromOperatingSystem(OperatingSystemMXBean operatingSystem, String methodName) {
    try {
        final Method method = operatingSystem.getClass().getMethod(methodName, (Class<?>[]) null);
        method.setAccessible(true);
        return (Long) method.invoke(operatingSystem, (Object[]) null);
    } catch (final Exception e) {
        LOG.info(String.format("OperatingSystemMXBean %s failed, Exception = %s ", methodName, e.getMessage()));
    }

    return -1;
}
 
源代码27 项目: chassis   文件: ChassisConfiguration.java
/**
 * Initializes the metrics registry
 *
 * @return metric registry bean
 */
@Bean
public MetricRegistry metricRegistry() {
    final MetricRegistry bean = new MetricRegistry();

    // add JVM metrics
    bean.register("jvm.gc", new GarbageCollectorMetricSet());
    bean.register("jvm.memory", new MemoryUsageGaugeSet());
    bean.register("jvm.thread-states", new ThreadStatesGaugeSet());
    bean.register("jvm.fd", new FileDescriptorRatioGauge());
    bean.register("jvm.load-average", new Gauge<Double>() {
        private OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();

        public Double getValue() {
            try {
                return mxBean.getSystemLoadAverage();
            } catch (Exception e) {
                // not supported
                return -1d;
            }
        }
    });

    // add Logback metrics
    final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);
    final InstrumentedAppender appender = new InstrumentedAppender(bean);
    appender.setContext(root.getLoggerContext());
    appender.start();
    root.addAppender(appender);

    return bean;
}
 
源代码28 项目: DeconvolutionLab2   文件: ProcessorMeter.java
@Override
public void setDetail() {
	Runtime runt = Runtime.getRuntime();
	int i = 0;
	RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
	add(i++, new String[] { "JVM", "Available processors", "" + runt.availableProcessors() });
	add(i++, new String[] { "Runtime", "Uptime", "" + NumFormat.time(rt.getUptime()*1e6) });
	OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
	for (Method method : os.getClass().getDeclaredMethods()) {
		method.setAccessible(true);
		if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) {
			try {
				String name = split(method.getName());
				if (name.contains("Size"))
					add(i++, new String[] { "OS", name, NumFormat.bytes(Double.parseDouble(method.invoke(os).toString())) });
				else if (name.contains("Time"))
					add(i++, new String[] { "OS", name, NumFormat.time(Double.parseDouble(method.invoke(os).toString())) });
				else if (name.contains("Load"))
					add(i++, new String[] { "OS", name, NumFormat.nice(100 * Double.parseDouble(method.invoke(os).toString()))+"%" });
				else
					add(i++, new String[] { "OS", name, "" + method.invoke(os).toString() });
			}
			catch (Exception e) {
			}
		}
	}		
}
 
源代码29 项目: DeconvolutionLab2   文件: SystemUsage.java
public static double getLoad() {
	try {
		OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
		return os.getSystemLoadAverage();
	}
	catch (Exception ex) {
	}
	return 0;
}
 
源代码30 项目: dubbo3   文件: LoadStatusChecker.java
public Status check() {
	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	double load;
	try {
	    Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage");
	    load = (Double)method.invoke(operatingSystemMXBean);
	} catch (Throwable e) {
	    load = -1;
	}
	int cpu = operatingSystemMXBean.getAvailableProcessors();
    return new Status(load < 0 ? Status.Level.UNKNOWN : (load < cpu ? Status.Level.OK : Status.Level.WARN), (load < 0 ? "" : "load:" + load + ",") + "cpu:" + cpu);
}