I would like to get the total physical memory, the CPU usage, and and the amount of memory being used. I have looked into Runtime.freeMemory()
, but that isn't the free memory for the whole system.
Asked
Active
Viewed 2.5k times
9

Deduplicator
- 44,692
- 7
- 66
- 118

Connor
- 107
- 1
- 1
- 2
-
possible duplicate of [How to monitor the computer's cpu, memory, and disk usage in Java?](http://stackoverflow.com/questions/47177/how-to-monitor-the-computers-cpu-memory-and-disk-usage-in-java) – Mat Jun 08 '11 at 19:53
-
1did you go through the list of previous questions about this? look at the "related" section on the right of this page. Please specify what exactly you're missing if it's not covered in there already. – Mat Jun 08 '11 at 19:55
-
also a duplicate of http://stackoverflow.com/questions/1011063/how-many-hardware-details-can-a-java-applet-discover – Ethan Heilman Jun 08 '11 at 19:59
-
1-1: Clearly no research performed here. There are a gazillion ways to find out this information, including half a gazillion right here on this page, under "Related". The same list appeared as you wrote your post. – Lightness Races in Orbit Jan 05 '12 at 03:15
5 Answers
6
I know I'm late with my answer, but I think this code is interesting. This is an adaptation of "closed" code, and should be revised before aplying directly:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.Process;
import java.lang.Runtime;
import java.util.HashMap;
/**
* SystemStatusReader is a collection of methods to read system status (cpu and memory)
*
* @author Andreu Correa Casablanca
*/
public class SystemStatusReader
{
public static final int CONSERVATIVE = 0;
public static final int AVERAGE = 1;
public static final int OPTIMISTIC = 2;
/**
* cpuUsage gives us the percentage of cpu usage
*
* mpstat -P ALL out stream example:
*
* Linux 3.2.0-30-generic (castarco-laptop) 10/09/12 _x86_64_ (2 CPU) - To discard
* - To discard
* 00:16:30 CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle - To discard
* 00:16:30 all 17,62 0,03 3,55 0,84 0,00 0,03 0,00 0,00 77,93
* 00:16:30 0 17,36 0,05 3,61 0,83 0,00 0,05 0,00 0,00 78,12
* 00:16:30 1 17,88 0,02 3,49 0,86 0,00 0,01 0,00 0,00 77,74
*
* @param measureMode Indicates if we want optimistic, convervative or average measurements.
*/
public static Double cpuUsage (int measureMode) throws Exception {
BufferedReader mpstatReader = null;
String mpstatLine;
String[] mpstatChunkedLine;
Double selected_idle;
try {
Runtime runtime = Runtime.getRuntime();
Process mpstatProcess = runtime.exec("mpstat -P ALL");
mpstatReader = new BufferedReader(new InputStreamReader(mpstatProcess.getInputStream()));
// We discard the three first lines
mpstatReader.readLine();
mpstatReader.readLine();
mpstatReader.readLine();
mpstatLine = mpstatReader.readLine();
if (mpstatLine == null) {
throw new Exception("mpstat didn't work well");
} else if (measureMode == SystemStatusReader.AVERAGE) {
mpstatChunkedLine = mpstatLine.replaceAll(",", ".").split("\\s+");
selected_idle = Double.parseDouble(mpstatChunkedLine[10]);
} else {
selected_idle = (measureMode == SystemStatusReader.CONSERVATIVE)?200.:0.;
Double candidate_idle;
int i = 0;
while((mpstatLine = mpstatReader.readLine()) != null) {
mpstatChunkedLine = mpstatLine.replaceAll(",", ".").split("\\s+");
candidate_idle = Double.parseDouble(mpstatChunkedLine[10]);
if (measureMode == SystemStatusReader.CONSERVATIVE) {
selected_idle = (selected_idle < candidate_idle)?selected_idle:candidate_idle;
} else if (measureMode == SystemStatusReader.OPTIMISTIC) {
selected_idle = (selected_idle > candidate_idle)?selected_idle:candidate_idle;
}
++i;
}
if (i == 0) {
throw new Exception("mpstat didn't work well");
}
}
} catch (Exception e) {
throw e; // It's not desirable to handle the exception here
} finally {
if (mpstatReader != null) try {
mpstatReader.close();
} catch (IOException e) {
// Do nothing
}
}
return 100-selected_idle;
}
/**
* memoryUsage gives us data about memory usage (RAM and SWAP)
*/
public static HashMap<String, Integer> memoryUsage () throws Exception {
BufferedReader freeReader = null;
String freeLine;
String[] freeChunkedLine;
HashMap<String, Integer> usageData = new HashMap<String, Integer>();
try {
Runtime runtime = Runtime.getRuntime();
Process freeProcess = runtime.exec("free -k"); // We measure memory in kilobytes to obtain a greater granularity
freeReader = new BufferedReader(new InputStreamReader(freeProcess.getInputStream()));
// We discard the first line
freeReader.readLine();
freeLine = freeReader.readLine();
if (freeLine == null) {
throw new Exception("free didn't work well");
}
freeChunkedLine = freeLine.split("\\s+");
usageData.put("total", Integer.parseInt(freeChunkedLine[1]));
freeLine = freeReader.readLine();
if (freeLine == null) {
throw new Exception("free didn't work well");
}
freeChunkedLine = freeLine.split("\\s+");
usageData.put("used", Integer.parseInt(freeChunkedLine[2]));
freeLine = freeReader.readLine();
if (freeLine == null) {
throw new Exception("free didn't work well");
}
freeChunkedLine = freeLine.split("\\s+");
usageData.put("swap_total", Integer.parseInt(freeChunkedLine[1]));
usageData.put("swap_used", Integer.parseInt(freeChunkedLine[2]));
} catch (Exception e) {
throw e;
} finally {
if (freeReader != null) try {
freeReader.close();
} catch (IOException e) {
// Do nothing
}
}
return usageData;
}
}

castarco
- 1,368
- 2
- 17
- 33
-
This would only work on a *nix system, wouldn't work on Windows. – Kyle Falconer Jun 29 '15 at 21:09
4
You can use SIGAR (http://support.hyperic.com/display/SIGAR/Home). I believe this is cross platform (I've only tried it on Windows) and I know it works (because I've tried it).
Javadoc: http://www.hyperic.com/support/docs/sigar/
Binaries: http://support.hyperic.com/display/SIGAR/Home#Home-binaries

Ryan Amos
- 5,422
- 4
- 36
- 56
-
The javadoc doesn't match the binarys. I can't seem to find the CpuPerc class in the JAR file i downloaded. – TheDoctor Aug 05 '14 at 16:06
-
@TheDoctor Weird. I have no idea what's wrong. It seems like those links are still up to date. I know they have to use native code, so perhaps your OS doesn't have an interface with SIGAR? I'd suggest double checking the little things -- are you on the latest version? Do you have the right imports? Etc. – Ryan Amos Aug 05 '14 at 22:48
2
static final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
...
long start = threadBean.getCurrentThreadCpuTime();
for (int i = 0; i < 10000000; i++) {
...
}
long finish = threadBean.getCurrentThreadCpuTime();

user1329572
- 6,176
- 5
- 29
- 39

Dmitri Gudkov
- 2,093
- 16
- 15
0
Use JMX via 'jconsole', if this if for interactive use. It displays nice realtime graphs, and lots of other diagnostic information.

StaxMan
- 113,358
- 34
- 211
- 239
-
Can you enlighten us on what the Java libraries and methods are that JMX uses to get memory info, and in our own programs, how can we use those methods in the same way that JVisualVM or Jconsole.exe does? – djangofan Jun 21 '11 at 20:52
-
I assume JConsole et al just use regular JMX access via TCP port; and JVM itself exposes many JMX attributes. – StaxMan Jun 21 '11 at 22:45