Get OS-level system information

后端 未结 16 2067
情话喂你
情话喂你 2020-11-22 02:02

I\'m currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows.

Has anyone been abl

16条回答
  •  我寻月下人不归
    2020-11-22 02:34

    The java.lang.management package does give you a whole lot more info than Runtime - for example it will give you heap memory (ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()) separate from non-heap memory (ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage()).

    You can also get process CPU usage (without writing your own JNI code), but you need to cast the java.lang.management.OperatingSystemMXBean to a com.sun.management.OperatingSystemMXBean. This works on Windows and Linux, I haven't tested it elsewhere.

    For example ... call the get getCpuUsage() method more frequently to get more accurate readings.

    public class PerformanceMonitor { 
        private int  availableProcessors = getOperatingSystemMXBean().getAvailableProcessors();
        private long lastSystemTime      = 0;
        private long lastProcessCpuTime  = 0;
    
        public synchronized double getCpuUsage()
        {
            if ( lastSystemTime == 0 )
            {
                baselineCounters();
                return;
            }
    
            long systemTime     = System.nanoTime();
            long processCpuTime = 0;
    
            if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )
            {
                processCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();
            }
    
            double cpuUsage = (double) ( processCpuTime - lastProcessCpuTime ) / ( systemTime - lastSystemTime );
    
            lastSystemTime     = systemTime;
            lastProcessCpuTime = processCpuTime;
    
            return cpuUsage / availableProcessors;
        }
    
        private void baselineCounters()
        {
            lastSystemTime = System.nanoTime();
    
            if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )
            {
                lastProcessCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();
            }
        }
    }
    

提交回复
热议问题