Java Code Examples for java.lang.management.OperatingSystemMXBean

The following examples show how to use java.lang.management.OperatingSystemMXBean. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: LagMonitor   Source File: MonitorSaveTask.java    License: MIT License 6 votes vote down vote up
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);
}
 
Example 2
Source Project: LagMonitor   Source File: NativeManager.java    License: MIT License 6 votes vote down vote up
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;
    }
}
 
Example 3
Source Project: lucene-solr   Source File: SystemInfoHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
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));
    }
  }
 
Example 4
Source Project: apm-agent-java   Source File: JmxUtils.java    License: Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example 5
Source Project: LagMonitor   Source File: MonitorSaveTask.java    License: MIT License 6 votes vote down vote up
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);
}
 
Example 6
Source Project: visualvm   Source File: CpuMonitorProbe.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 7
Source Project: Plan   Source File: SystemUsage.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Source Project: ns4_gear_watchdog   Source File: SystemMonitor.java    License: Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 9
Source Project: crate   Source File: Probes.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 10
Source Project: javamelody   Source File: JavaInformations.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source Project: dubbox   Source File: LoadStatusChecker.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 12
Source Project: datacollector   Source File: TestFileContext.java    License: Apache License 2.0 5 votes vote down vote up
private long getOpenFileDescriptors() {
  OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
  if (os instanceof UnixOperatingSystemMXBean) {
    return ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount();
  } else {
    return -1;
  }
}
 
Example 13
Source Project: rocketmq-4.3.0   Source File: StoreUtil.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 14
Source Project: jdk8u_jdk   Source File: MXBeanInteropTest1.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 ;
}
 
Example 15
Source Project: nifi   Source File: DiagnosticAnalysisTask.java    License: Apache License 2.0 5 votes vote down vote up
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));
    }
}
 
Example 16
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 ;
}
 
Example 17
Source Project: wisdom   Source File: CpuGaugeSet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 18
Source Project: Doradus   Source File: CassandraNode.java    License: Apache License 2.0 5 votes vote down vote up
private OperatingSystemMXBean getOperatingSystemMXBeanProxy() {
	if (osServiceProxy == null) {
		try {
			setConnection();
		} catch (Exception ex) {
			throwException("Can't create proxy of OperatingSystemMXBean",
					ex);
		}
	}
	return osServiceProxy;
}
 
Example 19
Source Project: metrics   Source File: FileDescriptorRatioGauge.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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();
        }
    };
}
 
Example 20
Source Project: ping   Source File: ServerWatch.java    License: Apache License 2.0 5 votes vote down vote up
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();

}
 
Example 21
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 ;
}
 
Example 22
Source Project: rtg-tools   Source File: Environment.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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();
}
 
Example 23
Source Project: bidder   Source File: Performance.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 24
Source Project: LagMonitor   Source File: NativeManager.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 25
Source Project: rocketmq   Source File: StoreUtil.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 26
Source Project: DataLink   Source File: VMInfo.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 27
Source Project: chassis   Source File: ChassisConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 28
@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) {
			}
		}
	}		
}
 
Example 29
public static double getLoad() {
	try {
		OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
		return os.getSystemLoadAverage();
	}
	catch (Exception ex) {
	}
	return 0;
}
 
Example 30
Source Project: dubbo3   Source File: LoadStatusChecker.java    License: Apache License 2.0 5 votes vote down vote up
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);
}