Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows batch & java: Combining -XX:OnOutOfMemoryError command and batch parameters

I am completely new to Windows batch programming. What I want to achieve is to write a startup script for a Java application. Yet, it does not start the Java application, but rather prints out

Usage: java [-options] class [args...]

(to execute a class)

or java [-options] -jar jarfile [args...]

(to execute a jar file)

...

which indicates that my parameters are not correctly recognized.


Here is my MCVE for the not-working script:

set memory=600000
java -XX:OnOutOfMemoryError="taskkill /PID %p" -Xmx%memory%K -jar MyApp.jar

In the real scenario, memory is calculated to set the optimal maximal heap size for the application.


Leaving out one of both parameters makes the app start. So

java -XX:OnOutOfMemoryError="taskkill /PID %p" -jar MyApp.jar

and

set memory=600000
java -Xmx%memory%K -jar MyApp.jar

works, but I need both parameters to work in one call.

like image 941
Markus Weninger Avatar asked Oct 30 '22 07:10

Markus Weninger


1 Answers

If you put @echo on and @echo off in your script you can see what command is actually being executed.

You say that the resulting command is:

java -XX:OnOutOfMemoryError="taskkill /PID memoryK -jar MyApp.jar

which makes it look like the % of %p is being considered an "opening" % for the substitution.

Aside from the quotes not being balanced, this means that you are effectively not giving java a command to run - the -jar MyApp.jar is actually inside the -XX:OnOutOfMemoryError string.

Try replacing the single % with %% - according to this question, that is how to write a literal % in a BAT file:

java -XX:OnOutOfMemoryError="taskkill /PID %%p" -Xmx%memory%K -jar MyApp.jar
like image 71
Andy Turner Avatar answered Nov 09 '22 23:11

Andy Turner