2

I'm writing a Java program that runs external executables using java.lang.ProcessBuilder. This program should be able to watch running time and memory usage of a child process and terminate if it exceeds some predefined limits.

For time-based measurement it's pretty simple to achieve:

boolean inTime = process.waitFor(60, TimeUnit.SECONDS);

But I haven't found any methods for watching memory usage of a child process. Are there any ways to achieve this in Java?

Thanks in advance!

despectra
  • 103
  • 11

3 Answers3

2

i don't know what you are asking exactly ,but if you are looking for how much memory your method will take while execution or runtime time

Java Mission Control read this

you will find JFR and Mbeans right hand side after you open JMC(write "jmc" in terminal) and JFR will give you every single method name also it's child method name as well as how much memory they are taking

this is how you can check-::

make a program with 3-4 methods , iterate them more than 5 lac so it will take so much time and you are able to watch what happening while execution

now open flight recorder and go to (memory->Allocations-> Allocations in new tlab-> allocation Profile)

hope you find your ans Here

Coder
  • 1,129
  • 10
  • 24
0

What you can do is to use local attach and fetch heap usage from the MemoryMXBean and the uptime from the RuntimeMXBean. See the class com.sun.tools.attach.VirtualMachine.

It's too much code to show, but you can look here

http://dontpanic.42.nl/2012/05/connecting-to-jvm-programmatically.html

for an example on how to list the virtual machines that are running, how to attach to them and start a management agent. Once you have a MBeanServerConnection you can do this:

MemoryMXBean memoryMBean = JMX.newMXBeanProxy(
                connection, new ObjectName("java.lang:type=Memory"), MemoryMXBean.class);
RuntimeMXBean runtimeMBean =     JMX.newMXBeanProxy(
                connection, new ObjectName("java.lang:type=Runtime"), RuntimeMXBean.class);
String pid = runtimeMBean.getName().split("@")[0];
long uptime = runtimeMBean.getUptime();
long memoryUsed = memoryMBean.getHeapMemoryUsage().getUsed();

You can then kill the process, for example like this:

Runtime.getRuntime().exec("kill " + pid);
Kire Haglin
  • 6,569
  • 22
  • 27
-1

I hope below will help: If your child process can send back details somehow I found this - Runtime rt = Runtime.getRuntime(); long usedMB = (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024; logger.information(this, "memory usage" + usedMB);

in this thread; may be can help: How to monitor Java memory usage?

If you want to monitor from outside process this looks interesting - similar question I would say: Get memory usage and execution time from a process initiated with the ProcessBuilder

and in one answer someone is pointing to this link: How do I access memory usage programmatically via JMX?

Community
  • 1
  • 1
Adi
  • 49
  • 4