Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 864
Wuschelbeutel Kartoffelhuhn Avatar asked Dec 08 '12 23:12

Wuschelbeutel Kartoffelhuhn


2 Answers

The answer is "no".

The memory size is passed to the JVM on start up. The code running inside the JVM can not change it.

IF you think about it, it makes sense, because the JVM is a program not written in java that can execute java byte code. IT wouldn't be safe to allow the java code to control its container.

like image 93
Bohemian Avatar answered Sep 18 '22 22:09

Bohemian


"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);
        }
    }
}
like image 42
Andrew Thompson Avatar answered Sep 21 '22 22:09

Andrew Thompson