问题
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?
回答1:
"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);
}
}
}
回答2:
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.
回答3:
It wouldn't be a maximum if you could increase it.
The reason it cannot be increased is that it allocated on start up. It can only get set before the JVM starts.
What you can do is relauch the application with a higher maximum. e.g. on start you check the maximum and if it not high enough you run the same program except with a higher maximum.
Note: if you use off heap memory, it can be GB or even TBs more as it is not part of the maximum.
As it is right now, java.exe reaches ~280MB max only (before it crashes) - is this normal?
Crashes can mean just about anything and the reason could be just about anything. I suggest you investigate in more detail exactly why it is not working and I suspect you will find that the maximum memory is not the issue. (Unless you have a small 1 GB machine in which case the default maximum memory would be about 250 MB)
来源:https://stackoverflow.com/questions/13783086/is-there-a-way-to-increase-java-heap-space-in-the-code-itself