Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the -Xmx when start running a jar file?

Tags:

java

jar

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!

like image 909
Judking Avatar asked Nov 22 '13 16:11

Judking


People also ask

How do I specify jar manifest?

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.

What is CVF in jar command?

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.


2 Answers

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 function

The -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.

like image 137
Philipp Merkle Avatar answered Sep 21 '22 02:09

Philipp Merkle


Three methods:

  • Command Line:
    • Instruct your users to run your application using "java -jar SampleJavaApp.jar -Xmx1024m"
  • Java Control Panel:
    • Instruct your users to dedicate more memory to java by default: Win7 guide
  • Restart your jar with the appropriate Xmx value.

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;     } } 
like image 28
DKATyler Avatar answered Sep 24 '22 02:09

DKATyler