Finding how much virtual memory is allocated to a process - java

Is there a way to find out how much total virtual memory is allocated to a specific process? I have a program and I am also putting in a performance tracker which will monitor how much memory the process is using and how much is left for it to use.
To do this, I need to know how much memory is allocated to the process. Is there a way to do this in Java? I am running on Windows 7.
Also, I have currently been using the Sigar classes to monitor other memory statistics. Does sigar have a specific class/function that can find what I am looking for?

You can use Visualvm.
In your code to calculate memory used:-
Runtime runtime = Runtime.getRuntime(); // Get the Java runtime
long memory = runtime.totalMemory() - runtime.freeMemory(); // Calculate the used memory

To add more on what #Mitesh mentioned,
int var=1; // for bytes. you can change here to print in MB or KB as you wish
log.info("************************* PRINTING MEMORY USAGE - BEGIN **************");
Runtime runtime = Runtime.getRuntime();
/* Total number of processors or cores available to the JVM */
log.info("Available processors (cores): "
+ runtime.availableProcessors());
/* This will return Long.MAX_VALUE if there is no preset limit */
long maxMemory = runtime.maxMemory();
/* Maximum amount of memory the JVM will attempt to use */
log.info("Maximum memory : "
+ (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory / var));
/* Total memory currently available to the JVM */
long totalMemory = runtime.totalMemory() / var;
log.info("Total memory available to JVM : "
+ totalMemory);
/* Total amount of free memory available to the JVM */
long freeMemory = runtime.freeMemory() / var;
log.info("Free memory : " + freeMemory);
// Calculate the used memory
long usedMemory = totalMemory - freeMemory;
log.info("Used memory : " + usedMemory);

Related

How to run custom clean-up code to prevent JVM from throwing OutOfMemory? [duplicate]

I will be running a genetic algorithm on my roommate's computer for the whole weekend, and I'm afraid that it could run out of memory over such a long run. However, my algorithm works in such a way that would make it reasonably easy to trim less useful results, so if there was a way to tell when my program is about to run out of heap space, I could probably make room and keep going for some more time.
Is there a way to be notified when the JVM is running out of heap space, before the OutOfMemoryError?
You can register a javax.management.NotificationListener that is called when a certain threshold is hit.
Something like
final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
final NotificationEmitter ne = (NotificationEmitter) memBean;
ne.addNotificationListener(listener, null, null);
final List<MemoryPoolMXBean> memPools = ManagementFactory
.getMemoryPoolMXBeans();
for (final MemoryPoolMXBean mp : memPools) {
if (mp.isUsageThresholdSupported()) {
final MemoryUsage mu = mp.getUsage();
final long max = mu.getMax();
final long alert = (max * threshold) / 100;
mp.setUsageThreshold(alert);
}
}
Where listener is your own implementation of NotificationListener.
You can try this:
// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
As found here - http://www.exampledepot.com/egs/java.lang/GetHeapSize.html
Just use WeakReferences for the discardable results, then they will be discarded if necessary for space reasons.
I am not sure about this, but can't JConsole solve your purpose ??

Can't consume entire memory

I am trying to write a program which should consume memory of a specific size. An issue I am wondering of is that I am getting outOfMemory exception when there is actually a free space in the heap.
Here is the code:
import java.util.Vector;
import java.lang.*;
public class MemoryEater1 {
public static void main(String[] args) {
try {
long mb = Long.valueOf(args[0]);
Vector v = new Vector();
Runtime rt = Runtime.getRuntime();
while (true) {
if (v.size() > 0) {
if (((long) v.size())*100 < mb) {
System.out.println("total memory: " + rt.totalMemory()/1024/1024);
System.out.println("max memory: " + rt.maxMemory()/1024/1024);
System.out.println("free memory: " + rt.freeMemory()/1024/1024);
System.out.println("Trying to add 100 mb");
//100mb
byte b[] = new byte[104857600];
v.add(b);
}
} else {
//100mb
byte b[] = new byte[104857600];
v.add(b);
System.out.println("Added 100 mb");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The command to start it:
java -Xmx4096m MemoryEater1 3000
And the output:
total memory: 2867
max memory: 3641
free memory: 59
Trying to add 100 mb
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at MemoryEater1.main(MemoryEater1.java:18)
Well the difference between max memory and total memory is 774mb, which should be enough to consume 100mb more, but still there is the error, and even the machine resources are sufficient enough:
[user#machine ~]$ free -m
total used free shared buffers cached
Mem: 15950 3447 12502 0 210 2389
-/+ buffers/cache: 847 15102
Swap: 4031 1759218603 8941
Why can that be?
I don't think it's fragmentation as you only have one thread allocating memory and not reclaiming anything.
It's your particular garbage collector to blame, they manage memory differently resulting in more or less being unavailable for your app. You can find out which one is used by analyzing the output of java -XX:+PrintCommandLineFlags).
You can try to use G1 which manages memory differently.
java -Xmx4096m -XX:+UseG1GC MemoryEater1 3000
Or play with generation sizes e.g. -XX:NewSize and so on.
For more information read up VM options and anything on garbage collector algorithms e.g. [GC tuning]
Here's a quick illustration how splitting memory for different generations can make it unavailable (http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html).
It is possible to set the JVM flags for an amount of memory greater than the physical memory on your machine. With the information given so far, it seem most likely that you lack the physical memory to allocate this array. In other words, the JVM requests more memory from the OS and the OS says there's none to give.
Another possibility is the memory fragmentation issue noted in the comments to your question. I think that less likely, however, in this case because of the structure of your program. I don't think it can be ruled out though.

Calculating Used Memory of a JVM

I want to calculate the used memory of a JVM heap. I did the following in a sample application.
Set JVM heap size as Xms=200mb and Xmx=200mb.
Did the calculation as follows using Java Runtime APIs. It gave me following output for sample program.
Runtime total memory : 192413696
Runtime max memory : 192413696
Runtime free memory : 39734096
Runtime available memory = (max - total + free) = 39734096
Percentage of used memory = 100*(max-available)/max = 100*(192413696-
39734096)/192413696 = 79.35%
Did another calculation via JMX : java.lang:type=Memory (Using MBean)
It gave me following output for the same program.
Used memory : 127737896
Max memory : 201850880
Percentage of used memory = 100*(used/max) = 100* (127737896/201850880)=
63.28%
Could you please help me with the following ?
What is the reason for the difference between using JMX and Java Run time APIs ?
If I want to know the memory occupied in my JVM heap which is the right approach (point 2 or point 3). My intention is to raise alerts before an out of memory occurs for my JVM.
I have another observation as well. When I use CMS algorithm (with -Xms and -Xms set to 32GB and Occupancy fraction set to 70%) I could see the difference between the free memory calculated using MBeans and java runtime freeMemory(). When I was using G1 I could not find these difference (the Mbeans and run time API gave same value).
Runtime rt = Runtime.getRuntime();
long mem = rt.totalMemory();
long fm = rt.freeMemory();
long mm = rt.maxMemory();
long used = mm - fm;
The calculation should be usedMemory / MaxMemory * 100
Used Memory = 127737896
Max Memory = 201850880
127737896 / 201850880 * 100 = 63.28%

How to get total JVM heap size, used memory using Java

pro-grammatically how to get total Heap size, used heap memory ?
You can use Runtime class methods
maxMemory() , freeMemory() and totalMemory()
and if you want to use any tools then there are so many tools like jProfiler.
You can use MemoryMXBean to get info about your heap
MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
System.out.println(mbean.getHeapMemoryUsage());
which outputs
init = 134217728(131072K) used = 2044912(1996K)
committed = 128974848(125952K) max = 1897922560(1853440K)

Can a Java program detect that it's running low on heap space?

I will be running a genetic algorithm on my roommate's computer for the whole weekend, and I'm afraid that it could run out of memory over such a long run. However, my algorithm works in such a way that would make it reasonably easy to trim less useful results, so if there was a way to tell when my program is about to run out of heap space, I could probably make room and keep going for some more time.
Is there a way to be notified when the JVM is running out of heap space, before the OutOfMemoryError?
You can register a javax.management.NotificationListener that is called when a certain threshold is hit.
Something like
final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
final NotificationEmitter ne = (NotificationEmitter) memBean;
ne.addNotificationListener(listener, null, null);
final List<MemoryPoolMXBean> memPools = ManagementFactory
.getMemoryPoolMXBeans();
for (final MemoryPoolMXBean mp : memPools) {
if (mp.isUsageThresholdSupported()) {
final MemoryUsage mu = mp.getUsage();
final long max = mu.getMax();
final long alert = (max * threshold) / 100;
mp.setUsageThreshold(alert);
}
}
Where listener is your own implementation of NotificationListener.
You can try this:
// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
As found here - http://www.exampledepot.com/egs/java.lang/GetHeapSize.html
Just use WeakReferences for the discardable results, then they will be discarded if necessary for space reasons.
I am not sure about this, but can't JConsole solve your purpose ??

Categories

Resources