Monday, May 6, 2013

Monitoring Windows Resources through Java

This article describes about how to monitor CPU load, Memory free space and HDD free space in Windows using Java. We use com.sun.management.OperatingSystemMXBean class for monitor CPU load and memory usage. You have to have JDK 1.7 to use this class.

Monitoring CPU load


1.    OperatingSystemMXBean bean = (OperatingSystemMXBean)java.lang.management. ManagementFactory.getOperatingSystemMXBean();
2.    double dCpu_usage = (double)(bean.getSystemCpuLoad()*100);

Description

Line 1: Create an OperatingSystemMXBean object.
Line 2: getSystemCpuLoad() method will return the CPU load as a decimal value between 0 and 1 for the consumer. So you have to multiply it from 100 to display as a percentage.


Monitor Free memory space

1.   You have to create an OperatingSystemMXBean object same as in CPU load monitoring.
2.   Int lFree_mem = bean.getFreePhysicalMemorySize()/(1024*1024);

Description

Line 2: bean.getFreePhysicalMemorySize() will return free memory space in bytes. So you have to divide it 1024*1024 to convert into MB.


Monitor Free HDD space

1.   File drive = new File(“c:\\");
2.   int free_space = drive.getFreeSpace()/(1024*1024*1024);

Description

Line 1: Create a simple File (java.io.File) object and give your HDD letter as path of the file.
Line 2:  getFreeSpace() method will return free space of your HDD in bytes. To convert it into GB you have to divide it from 1024*1024*1024

No comments:

Post a Comment