As we know that we can set -Xmx1024M
in window->preferences->java->installed jres->edit->default vm arguments
in eclipse. But when I package this project into a runnable jar file, how can I set the -Xmx1024M
when running the jar via java -jar A.jar
?
Thanks a lot!
You use the m command-line option to add custom information to the manifest during creation of a JAR file. This section describes the m option. The Jar tool automatically puts a default manifest with the pathname META-INF/MANIFEST. MF into any JAR file you create.
In the case of creating a JAR file, the options "cvf" will create JAR file ( c ) with specified name ( f ) and print out verbose output ( v ) regarding this creation.
Unfortunately, existing answers are wrong in one crucial point.
-Xmx
must be passed to the Java runtime environment, not to the executed jar.
Wrong:
java -jar JavaApplication.jar -Xmx1024m
Correct:
java -Xmx1024m -jar JavaApplication.jar
More specifically, the java launcher needs to be used as follows:
java [options] -jar file.jar [arguments]
[options]
are passed to the Java runtime environment[arguments]
are passed to the main functionThe -Xmx
parameter belongs to the (nonstandard) JVM options, and--being an option--needs to be listed before -jar (or at least before file.jar). The JVM will not recognize an -Xmx
argument passed to the main function as proposed in other answers.
Three methods:
The last option is "evil" but doesn't require any extra effort from your users. Here's a sample block of code:
public static void main(String[] args) throws IOException, URISyntaxException { String currentPath=SampleJavaApp.class .getProtectionDomain() .getCodeSource().getLocation() .toURI().getPath() .replace('/', File.separator.charAt(0)).substring(1); if(args.length==0 && Runtime.getRuntime().maxMemory()/1024/1024<980) { Runtime.getRuntime().exec("java -Xmx1024m -jar "+currentPath+" restart"); return; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With