Recently, I was working on a project to obtain system information such as CPU share. At first I thought I wanted to use the dynamic link library, but later I found that I could do it like the following without calling jni, which saved me a lot of new technologies. Time o(∩_∩)o...
In Java, you can obtain information such as total physical memory, remaining physical memory, used physical memory, etc. The following examples can obtain this information and obtain the memory usage rate under Windows.
First, write a MonitorInfoBean class to load some monitoring information, including physical memory, remaining physical memory, used physical memory, memory usage and other fields. The code of this class is as follows:
package com.amgkaka.performance; /** */ /** * JavaBean class that monitors information. * @author amg * @version 1.0 * Creation date: 2008-4-25 - 10:37:00 am */ public class MonitorInfoBean { /** */ /** Memory is usable. */ private long totalMemory; /** */ /** Remaining memory. */ private long freeMemory; /** */ /** Maximum memory available. */ private long maxMemory; /** */ /** Operating system. */ private String osName; /** */ /** Total physical memory. */ private long totalMemorySize; /** */ /** Remaining physical memory. */ private long freePhysicalMemorySize; /** */ /** Physical memory used. */ private long usedMemory; /** */ /** Total number of threads. */ private int totalThread ; /* * */ /** cpu usage. */ private double cpuRatio; public long getFreeMemory() { return freeMemory; } public void setFreeMemory( long freeMemory) { this .fre eMemory = freeMemory; } public long getFreePhysicalMemorySize() { return freePhysicalMemorySize; } public void setFreePhysicalMemorySize( long freePhysicalMemorySize) { this .freePhysicalMemorySize = freePhysicalMemorySize; } public long ge tMaxMemory() { return maxMemory; } public void setMaxMemory( long maxMemory) { this .maxMemory = maxMemory; } public String getOsName() { return osName; } public void setOsName(String osName) { this .osName = osName; } public long getTotalMemory() { return totalMemory; } public void setTotalM emory( long totalMemory) { this .totalMemory = totalMemory; } public long getTotalMemorySize() { return totalMemorySize; } public void setTotalMemorySize( long totalMemorySize) { this .totalMemorySize = totalMemorySize; } public int getTotalThread() { return tot alThread; } public void setTotalThread( int totalThread) { this .totalThread = totalThread; } public long getUsedMemory() { return usedMemory ; } public void setUsedMemory( long usedMemory) { this .usedMemory = usedMemory; } public double getCpuRatio() { return cpuRatio; } public void s etCpuRatio( double cpuRatio) { this .cpuRatio = cpuRatio; } }
Then write an interface to obtain the current monitoring information. The code of this class is as follows:
package com.amgkaka.performance; /** */ /** * Business logic interface for obtaining system information. * @author amg * @version 1.0 * Creation date: 2008-3-11 - 10:06:06 am * /public interface IMonitorService { /** */ /** * Get the current monitoring object. * @return Return the constructed monitoring object* @throws Exception * @author amgkaka * Creation date: 2008-4-25 - 10:00 am 45:08 */ public MonitorInfoBean getMonitorInfoBean() throws Exception; }
The implementation class MonitorServiceImpl of this class is as follows:
package com.amgkaka.performance; import java.io.InputStreamReader; import java.io.LineNumberReader; import sun.management.ManagementFactory; import com.s un.management.OperatingSystemMXBean; /** */ /** * Get system information Business logic implementation class. * @author amg * @version 1.0 Creation date: 2008-3-11 - 10:06:06 am */ public class MonitorServiceImpl implements IMonitorService { //It can be set longer to prevent reading and running This system The CPU occupancy rate during checking is not accurate. Private static final int CPUTIME = 5000; private static final int PERCENT = 100; private static final int FAULTLENGTH = 10; /** */ /** * Get Get the current monitoring object. * @return Return the constructed monitoring object* @throws Exception * @author amg * Creation date: 2008-4-25 - 10:45:08 am */ public MonitorInfoBean getMonitorInfoBean() throws Exc episode { int kb = 1024 ; // Memory can be used long totalMemory = Runtime.getRuntime().totalMemory() / kb; // Remaining memory long freeMemory = Runtime.getRuntime().freeMemory() / kb; // Maximum memory can be used ong maxMemory = Runtime.getRuntime( ).maxMemory() / kb; OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory .getOperatingSystemMXBean(); // Operating System String osName = System.get Property("os.name" ); // Total physical memory long totalMemorySize = osmxb.getTotalPhysicalMemorySize () / kb; // Remaining physical memory long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb; // Used physical memory long usedMemory = (osmxb.getTotalPhysi calMemorySize() - osmxb .getFreePhysicalMemorySize()) / kb; // Get the total number of threads ThreadGroup parentThread; for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null ; parentThread = pa rentThread.getParent()); int totalThread = parentThread.activeCount(); double cpuRatio = 0 ; if (osName.toLowerCase().startsWith( "windows" )) { cpuRatio = this .getCpuRatioForWindows(); } // Construct the return object MonitorInfoBean infoBean = new Monitor InfoBean(); infoBean.setFreeMemory(freeMemory); infoBean.setFreePhysicalMemorySize (freePhysicalMemorySize); infoBean.setMaxMemory(maxMemory); infoBean.setOsName(osName); infoBean.setTotalMemory(totalMemory); infoBean.setTotalMemory(totalMemory); infoBean .setTotalMemorySize(totalMemorySize); infoBean.setTotalThread(totalThread); infoBean.setUsedMemory(usedMemory); infoBean.setCpuRatio( : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : cpuRatio); return infoBean; } /** */ /** * Get CPU usage. * @return Return CPU usage* @author amg * Creation date: 2008-4-25 - 06:05:11 pm */ private double getCpuRatioForWindows() { try { String procCmd = System.getenv("windir" ) + "//system32//wbem//wmic.exe process get Caption,CommandLin e," + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount " ; // Get process information long [] c0 = readCpu(Runtime.getRuntime().exec(procCmd)); Thread.sleep(CPUTIME); long [] c1 = readCpu(Runtime.getRuntime().ex ec(procCmd) ); if (c0 != null && c1 != null ) { long idletime = c1[ 0 ] - c0[ 0 ]; long busytime = c1[ 1 ] - c0[ 1 ]; return Double.valueOf( PERCENT * (busytime ) / (busytime + idletime)) .doubleValue(); } else { return 0.0 ; } } catch (Exception ex) { ex.printStackTrace(); return 0.0 ; } } /** */ /** * Read the CPU Information. * @param proc * @return * @author amg * Creation date: 2008-4-25 - 06:10:14 pm */ private long [] readCpu( final Process proc) { long [] retn = new long [ 2 ]; try { proc.getOutputStream().close(); InputStreamReader ir = new InputStreamReader(proc.getInputStream()); LineNumberReader input = new LineNumberRea der(ir); String line = input.readLine(); if (line = = null || line.length() < FAULTLENGTH) { return null ; } int capidx = line.indexOf( "Caption" ); int cmdidx = line.indexOf( "CommandLine" ); int rocidx = line.indexOf( "ReadOperationCount " ); int umtidx = line.indexOf( "UserModeTime" ); int kmtidx = line.indexOf( "KernelModeTime" ); int wocidx = line.indexOf( "WriteOperationCount " ); long idletime = 0 ; long kneltime = 0 ; long usertime = 0 ; while ((line = input.readLine()) != null ) { if (line.length() < wocidx) { continue ; } // Fields appearing order: Caption, CommandLine, KernelModeTime,Rea dOperationCount, // ThreadCount,UserModeTime,WriteOperation String caption = Bytes.substring(line, capidx, cmdidx - 1 ) .trim(); String cmd = Bytes.substring(line, cmdid x, kmtidx - 1 ).trim(); if (cmd.indexOf ( "wmic.exe" ) >= 0 ) { continue ; } // log.info("line="+line); if (caption.equals( "System Idle Process" ) || caption.equals("System" )) { idletime += Long.valueOf( Bytes.substring(line, kmtidx, rocidx - 1 ).trim()) .longValue(); idletime += Long.valueOf( Bytes.substring(line, umtidx, wocidx - 1 ).trim()) .longValue(); continue ; } kneltime += Long.valueOf( Bytes.substring(line, kmtidx, rocidx - 1 ).trim()) .longValue(); usertime += Long.valueOf( Bytes.substring(line, umtidx, wocidx - 1 ).trim()) .longValue(); } retn[0 ] = idletime; retn[1 ] = kneltime + usertime; return retn; } catch ( Exception ex) { ex .printStackTrace(); } finally { try { proc.getInputStream().close(); } catch (Exception e) { e.printStackTrace(); } } return null ; } /** */ /** * Test method . * @param args * @throws Exception * @author amg * Creation date: 2008-4-30 - 04:47:29 pm */ public static void main(String[] args) throws Exception { IM onitorService service = new MonitorServiceImpl( ); MonitorInfoBean monitorInfo = service.getMonitorInfoBean(); System.out.println("cpu occupancy=" + monitorInfo.getCpuRatio()); System.out.println("can be used Save=" + monitorInfo.getTotalMemory()) ; System.out.println("Remaining Memory=" + monitorInfo.getFreeMemory()); System.out.println("Maximum usable memory=" + monitorInfo.getMaxMemory()); System.out.printl n("Operating system =" + monitorInfo.getOsName()); System.out.println("Total physical memory=" + monitorInfo.getTotalMemorySize() + "kb"); System.out.println("Remaining physical memory=" + monitorInfo .getFreeMemory() + "kb" ); System.out.println("Physical memory used=" + monitorInfo.getUsedMemory() + "kb" ); System.out.println("Total number of threads=" + monitorInfo. getTotalThread() + "kb" ); } }
This implementation class requires a tool class that writes byte by yourself. The code of this class is as follows:
package com.amgkaka.performance; /** */ /** * byte operation class. * @author amg * @version 1.0 * Creation date: 2008-4-30 - 04:57:23 pm */ public class Bytes { /** */ /** * Since String.subString has problems with Chinese character processing (considering a Chinese character as a byte), there are hidden dangers when * contains Chinese characters. The adjustment is as follows: * @param src Intercepted string * @param start_idx Start coordinate (including this coordinate) * @param end_idx Cutoff coordinate (including this coordinate) * @return */ public static String substring(String src, int start_idx, int en d_idx){ byte [] b = src.getBytes(); String tgt = "" ; for ( int i=start_idx; i<=end_idx; i++){ tgt +=(char )b[i]; } return tgt; } }
Run the MonitorBeanImpl class and readers will see the current memory, CPU utilization and other information.
PS: Method to get all host names in the LAN
import java.net.InetAddress;import java.net.UnknownHostException;public class A { static public void main(String[] args) { try { //Get IP address I through the host name netAddress address = InetAddress.getByName("192.168.9.148 "); System.out.println("192.168.9.148"+": "+address.getHostAddress());// Get the host name through IP String ips="192.168.9.",ip; InetAddress addip; for( int i=148;i<255;i++){ ip=ips+i; addip=InetAddress.getByName(ip); System.out.println(ip+": "+addip.getHostName()); } } catc h(UnknownHostException uhe) { System.err.println("Unable to find: "+"192.168.9.148"); } } }