Search code examples
javamemoryjvmjvm-arguments

Is there a way to increase Java heap space in the code itself?


Possible Duplicate:
Is it possible to dynamically change maximum java heap size?

I know there is an XMX option for the Java launcher, but is there some kind of preprocessing directive that does this instead (so that all computers that run my code will have their heap increased).

As it is right now, java.exe reaches ~280MB max only (before it crashes) - is this normal?


Solution

  • "launch a new Process with more memory" can this be done in the code?

    Yes. See this simplistic example.

    import java.awt.EventQueue;
    import javax.swing.JOptionPane;
    import java.io.File;
    
    class BigMemory {
    
        public static void main(String[] args) throws Exception {
            if (args.length==0) {
                ProcessBuilder pb = new ProcessBuilder(
                    "java",
                    "-Xmx1024m",
                    "BigMemory",
                    "anArgument"
                    );
                pb.directory(new File("."));
                Process process = pb.start();
                process.waitFor();
                System.out.println("Exit value: " + process.exitValue());
            } else {
                Runnable r = new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(
                            null,
                            "Max Memory: " +
                            Runtime.getRuntime().maxMemory() +
                            " bytes.");
                    }
                };
                EventQueue.invokeLater(r);
            }
        }
    }