views:

150

answers:

3

I am coding an application that creates JVMs and needs to control the memory usage of the processes spawned by the JVM.

+1  A: 

If by 'control' you mean 'limit to a known upper bound', then you can simply pass

-Xms`lower_bound`

and

-Xmx`upper_bound`

to the vm's args when you spawn the process. see the approproate setting here

Chii
+2  A: 

You can connect to JVM process using JMX to get information about memory status / allocations and also provoke garbage collection. But you first need to enable JMX monitoring of your JVM: http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html.

Superfilin
+1  A: 

I assume that you are talking about non-Java "processes" spawned using Runtime.exec(...) etc.

The answer is that this is OS specific and not something that the standard Java libraries support. But if you were going to do this in Linux (or UNIX) I can think of three approaches:

  • Have Java spawn the command via a shell wrapper script that uses the ulimit builtin to reduce the memory limits, then execs the actual command; see man 1 ulimit.
  • Write a little C command that does the same as the shell wrapper. This will have less overhead than the wrapper script approach.
  • Try to do the same with JNI and a native code library. Not recommended because you'd probably need to replicate the behavior of Process and ProcessBuilder, and that could be very difficult.
Stephen C