tags:

views:

175

answers:

2

How do I set the maximal jvm-memory without adding an extra batch-script to my Programm. Answer is provided below.

A: 

My approach is to add a parameter to my program which i set when the jvm is configured properly.

Like this:

public static void main(final String args[]) {
        if ((args.length != 0) && args[0].equals("xmx_set"))
            runClient();
        else {
            try {
                Runtime.getRuntime().exec("java -Xmx256M -jar client.jar xmx_set");
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }
Fabian Zeindl
That's looks pretty brittle to me, it interferes with normal command line parameters, ignores any other command line parameters you've put on, and also any other JVM args you've specified. Can't say I'm a fan...
Jon Skeet
Also, it means that the script or whatever that launches your program cannot get the PID of the actual running JVM. And the JVM processes parent process will end up as 0, which changes the way certain things behave on UNIX ...
Stephen C
I find this solution useful if you want to provide a simple clickable jar for GUI-users.Anywhere else I won't do that just to avoid some start-scripts.
Fabian Zeindl
A: 

It's a good question, but your implmenetation assumes a lot. I presume you have to document the name of your jar for your users to invoke "java -jar xyz.jar" on so can you also include in the documentation that "-Xmx256M" is required?

You may have more luck using a java launcher, such as this one for Windows, where you put the launcher config (path, max memory etc.) in a separate file. For cross platform, there's LaunchAnywhere, and others, which function similarly. See http://stackoverflow.com/questions/147181/how-can-i-convert-my-java-program-to-an-exe-file

To improve upon your existing scheme:

  • use the java.home system property to resolve the location of the JDK/JRE
  • use the java.class.path to set up the class path, and similarly for java.library.path if your application requires native code.
  • pass command arguments passed to your main method to the spanwed process

But still, this seems to be a lot of effort that at best represents a leaky abstraction, when instead simple and clear documentation would suffice.

mdma